utils.cc revision 14ae4a873e91ae8cb1c00013579b5b058268879d
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 <unistd.h>
25
26#include "UniquePtr.h"
27#include "base/stl_util.h"
28#include "base/unix_file/fd_file.h"
29#include "dex_file-inl.h"
30#include "mirror/art_field-inl.h"
31#include "mirror/art_method-inl.h"
32#include "mirror/class-inl.h"
33#include "mirror/class_loader.h"
34#include "mirror/object-inl.h"
35#include "mirror/object_array-inl.h"
36#include "mirror/string.h"
37#include "object_utils.h"
38#include "os.h"
39#include "utf-inl.h"
40
41#if !defined(HAVE_POSIX_CLOCKS)
42#include <sys/time.h>
43#endif
44
45#if defined(HAVE_PRCTL)
46#include <sys/prctl.h>
47#endif
48
49#if defined(__APPLE__)
50#include "AvailabilityMacros.h"  // For MAC_OS_X_VERSION_MAX_ALLOWED
51#include <sys/syscall.h>
52#endif
53
54#include <backtrace/Backtrace.h>  // For DumpNativeStack.
55
56#if defined(__linux__)
57#include <linux/unistd.h>
58#endif
59
60namespace art {
61
62pid_t GetTid() {
63#if defined(__APPLE__)
64  uint64_t owner;
65  CHECK_PTHREAD_CALL(pthread_threadid_np, (NULL, &owner), __FUNCTION__);  // Requires Mac OS 10.6
66  return owner;
67#else
68  // Neither bionic nor glibc exposes gettid(2).
69  return syscall(__NR_gettid);
70#endif
71}
72
73std::string GetThreadName(pid_t tid) {
74  std::string result;
75  if (ReadFileToString(StringPrintf("/proc/self/task/%d/comm", tid), &result)) {
76    result.resize(result.size() - 1);  // Lose the trailing '\n'.
77  } else {
78    result = "<unknown>";
79  }
80  return result;
81}
82
83void GetThreadStack(pthread_t thread, void** stack_base, size_t* stack_size) {
84#if defined(__APPLE__)
85  *stack_size = pthread_get_stacksize_np(thread);
86  void* stack_addr = pthread_get_stackaddr_np(thread);
87
88  // Check whether stack_addr is the base or end of the stack.
89  // (On Mac OS 10.7, it's the end.)
90  int stack_variable;
91  if (stack_addr > &stack_variable) {
92    *stack_base = reinterpret_cast<byte*>(stack_addr) - *stack_size;
93  } else {
94    *stack_base = stack_addr;
95  }
96#else
97  pthread_attr_t attributes;
98  CHECK_PTHREAD_CALL(pthread_getattr_np, (thread, &attributes), __FUNCTION__);
99  CHECK_PTHREAD_CALL(pthread_attr_getstack, (&attributes, stack_base, stack_size), __FUNCTION__);
100  CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attributes), __FUNCTION__);
101#endif
102}
103
104bool ReadFileToString(const std::string& file_name, std::string* result) {
105  UniquePtr<File> file(new File);
106  if (!file->Open(file_name, O_RDONLY)) {
107    return false;
108  }
109
110  std::vector<char> buf(8 * KB);
111  while (true) {
112    int64_t n = TEMP_FAILURE_RETRY(read(file->Fd(), &buf[0], buf.size()));
113    if (n == -1) {
114      return false;
115    }
116    if (n == 0) {
117      return true;
118    }
119    result->append(&buf[0], n);
120  }
121}
122
123std::string GetIsoDate() {
124  time_t now = time(NULL);
125  tm tmbuf;
126  tm* ptm = localtime_r(&now, &tmbuf);
127  return StringPrintf("%04d-%02d-%02d %02d:%02d:%02d",
128      ptm->tm_year + 1900, ptm->tm_mon+1, ptm->tm_mday,
129      ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
130}
131
132uint64_t MilliTime() {
133#if defined(HAVE_POSIX_CLOCKS)
134  timespec now;
135  clock_gettime(CLOCK_MONOTONIC, &now);
136  return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_nsec / 1000000LL;
137#else
138  timeval now;
139  gettimeofday(&now, NULL);
140  return static_cast<uint64_t>(now.tv_sec) * 1000LL + now.tv_usec / 1000LL;
141#endif
142}
143
144uint64_t MicroTime() {
145#if defined(HAVE_POSIX_CLOCKS)
146  timespec now;
147  clock_gettime(CLOCK_MONOTONIC, &now);
148  return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_nsec / 1000LL;
149#else
150  timeval now;
151  gettimeofday(&now, NULL);
152  return static_cast<uint64_t>(now.tv_sec) * 1000000LL + now.tv_usec;
153#endif
154}
155
156uint64_t NanoTime() {
157#if defined(HAVE_POSIX_CLOCKS)
158  timespec now;
159  clock_gettime(CLOCK_MONOTONIC, &now);
160  return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
161#else
162  timeval now;
163  gettimeofday(&now, NULL);
164  return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_usec * 1000LL;
165#endif
166}
167
168uint64_t ThreadCpuNanoTime() {
169#if defined(HAVE_POSIX_CLOCKS)
170  timespec now;
171  clock_gettime(CLOCK_THREAD_CPUTIME_ID, &now);
172  return static_cast<uint64_t>(now.tv_sec) * 1000000000LL + now.tv_nsec;
173#else
174  UNIMPLEMENTED(WARNING);
175  return -1;
176#endif
177}
178
179void NanoSleep(uint64_t ns) {
180  timespec tm;
181  tm.tv_sec = 0;
182  tm.tv_nsec = ns;
183  nanosleep(&tm, NULL);
184}
185
186void InitTimeSpec(bool absolute, int clock, int64_t ms, int32_t ns, timespec* ts) {
187  int64_t endSec;
188
189  if (absolute) {
190#if !defined(__APPLE__)
191    clock_gettime(clock, ts);
192#else
193    UNUSED(clock);
194    timeval tv;
195    gettimeofday(&tv, NULL);
196    ts->tv_sec = tv.tv_sec;
197    ts->tv_nsec = tv.tv_usec * 1000;
198#endif
199  } else {
200    ts->tv_sec = 0;
201    ts->tv_nsec = 0;
202  }
203  endSec = ts->tv_sec + ms / 1000;
204  if (UNLIKELY(endSec >= 0x7fffffff)) {
205    std::ostringstream ss;
206    LOG(INFO) << "Note: end time exceeds epoch: " << ss.str();
207    endSec = 0x7ffffffe;
208  }
209  ts->tv_sec = endSec;
210  ts->tv_nsec = (ts->tv_nsec + (ms % 1000) * 1000000) + ns;
211
212  // Catch rollover.
213  if (ts->tv_nsec >= 1000000000L) {
214    ts->tv_sec++;
215    ts->tv_nsec -= 1000000000L;
216  }
217}
218
219std::string PrettyDescriptor(mirror::String* java_descriptor) {
220  if (java_descriptor == NULL) {
221    return "null";
222  }
223  return PrettyDescriptor(java_descriptor->ToModifiedUtf8());
224}
225
226std::string PrettyDescriptor(mirror::Class* klass) {
227  if (klass == NULL) {
228    return "null";
229  }
230  return PrettyDescriptor(ClassHelper(klass).GetDescriptor());
231}
232
233std::string PrettyDescriptor(const std::string& descriptor) {
234  // Count the number of '['s to get the dimensionality.
235  const char* c = descriptor.c_str();
236  size_t dim = 0;
237  while (*c == '[') {
238    dim++;
239    c++;
240  }
241
242  // Reference or primitive?
243  if (*c == 'L') {
244    // "[[La/b/C;" -> "a.b.C[][]".
245    c++;  // Skip the 'L'.
246  } else {
247    // "[[B" -> "byte[][]".
248    // To make life easier, we make primitives look like unqualified
249    // reference types.
250    switch (*c) {
251    case 'B': c = "byte;"; break;
252    case 'C': c = "char;"; break;
253    case 'D': c = "double;"; break;
254    case 'F': c = "float;"; break;
255    case 'I': c = "int;"; break;
256    case 'J': c = "long;"; break;
257    case 'S': c = "short;"; break;
258    case 'Z': c = "boolean;"; break;
259    case 'V': c = "void;"; break;  // Used when decoding return types.
260    default: return descriptor;
261    }
262  }
263
264  // At this point, 'c' is a string of the form "fully/qualified/Type;"
265  // or "primitive;". Rewrite the type with '.' instead of '/':
266  std::string result;
267  const char* p = c;
268  while (*p != ';') {
269    char ch = *p++;
270    if (ch == '/') {
271      ch = '.';
272    }
273    result.push_back(ch);
274  }
275  // ...and replace the semicolon with 'dim' "[]" pairs:
276  while (dim--) {
277    result += "[]";
278  }
279  return result;
280}
281
282std::string PrettyDescriptor(Primitive::Type type) {
283  std::string descriptor_string(Primitive::Descriptor(type));
284  return PrettyDescriptor(descriptor_string);
285}
286
287std::string PrettyField(mirror::ArtField* f, bool with_type) {
288  if (f == NULL) {
289    return "null";
290  }
291  FieldHelper fh(f);
292  std::string result;
293  if (with_type) {
294    result += PrettyDescriptor(fh.GetTypeDescriptor());
295    result += ' ';
296  }
297  result += PrettyDescriptor(fh.GetDeclaringClassDescriptor());
298  result += '.';
299  result += fh.GetName();
300  return result;
301}
302
303std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type) {
304  if (field_idx >= dex_file.NumFieldIds()) {
305    return StringPrintf("<<invalid-field-idx-%d>>", field_idx);
306  }
307  const DexFile::FieldId& field_id = dex_file.GetFieldId(field_idx);
308  std::string result;
309  if (with_type) {
310    result += dex_file.GetFieldTypeDescriptor(field_id);
311    result += ' ';
312  }
313  result += PrettyDescriptor(dex_file.GetFieldDeclaringClassDescriptor(field_id));
314  result += '.';
315  result += dex_file.GetFieldName(field_id);
316  return result;
317}
318
319std::string PrettyType(uint32_t type_idx, const DexFile& dex_file) {
320  if (type_idx >= dex_file.NumTypeIds()) {
321    return StringPrintf("<<invalid-type-idx-%d>>", type_idx);
322  }
323  const DexFile::TypeId& type_id = dex_file.GetTypeId(type_idx);
324  return PrettyDescriptor(dex_file.GetTypeDescriptor(type_id));
325}
326
327std::string PrettyArguments(const char* signature) {
328  std::string result;
329  result += '(';
330  CHECK_EQ(*signature, '(');
331  ++signature;  // Skip the '('.
332  while (*signature != ')') {
333    size_t argument_length = 0;
334    while (signature[argument_length] == '[') {
335      ++argument_length;
336    }
337    if (signature[argument_length] == 'L') {
338      argument_length = (strchr(signature, ';') - signature + 1);
339    } else {
340      ++argument_length;
341    }
342    std::string argument_descriptor(signature, argument_length);
343    result += PrettyDescriptor(argument_descriptor);
344    if (signature[argument_length] != ')') {
345      result += ", ";
346    }
347    signature += argument_length;
348  }
349  CHECK_EQ(*signature, ')');
350  ++signature;  // Skip the ')'.
351  result += ')';
352  return result;
353}
354
355std::string PrettyReturnType(const char* signature) {
356  const char* return_type = strchr(signature, ')');
357  CHECK(return_type != NULL);
358  ++return_type;  // Skip ')'.
359  return PrettyDescriptor(return_type);
360}
361
362std::string PrettyMethod(mirror::ArtMethod* m, bool with_signature) {
363  if (m == nullptr) {
364    return "null";
365  }
366  MethodHelper mh(m);
367  std::string result(PrettyDescriptor(mh.GetDeclaringClassDescriptor()));
368  result += '.';
369  result += mh.GetName();
370  if (UNLIKELY(m->IsFastNative())) {
371    result += "!";
372  }
373  if (with_signature) {
374    const Signature signature = mh.GetSignature();
375    std::string sig_as_string(signature.ToString());
376    if (signature == Signature::NoSignature()) {
377      return result + sig_as_string;
378    }
379    result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
380        PrettyArguments(sig_as_string.c_str());
381  }
382  return result;
383}
384
385std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature) {
386  if (method_idx >= dex_file.NumMethodIds()) {
387    return StringPrintf("<<invalid-method-idx-%d>>", method_idx);
388  }
389  const DexFile::MethodId& method_id = dex_file.GetMethodId(method_idx);
390  std::string result(PrettyDescriptor(dex_file.GetMethodDeclaringClassDescriptor(method_id)));
391  result += '.';
392  result += dex_file.GetMethodName(method_id);
393  if (with_signature) {
394    const Signature signature = dex_file.GetMethodSignature(method_id);
395    std::string sig_as_string(signature.ToString());
396    if (signature == Signature::NoSignature()) {
397      return result + sig_as_string;
398    }
399    result = PrettyReturnType(sig_as_string.c_str()) + " " + result +
400        PrettyArguments(sig_as_string.c_str());
401  }
402  return result;
403}
404
405std::string PrettyTypeOf(mirror::Object* obj) {
406  if (obj == NULL) {
407    return "null";
408  }
409  if (obj->GetClass() == NULL) {
410    return "(raw)";
411  }
412  ClassHelper kh(obj->GetClass());
413  std::string result(PrettyDescriptor(kh.GetDescriptor()));
414  if (obj->IsClass()) {
415    kh.ChangeClass(obj->AsClass());
416    result += "<" + PrettyDescriptor(kh.GetDescriptor()) + ">";
417  }
418  return result;
419}
420
421std::string PrettyClass(mirror::Class* c) {
422  if (c == NULL) {
423    return "null";
424  }
425  std::string result;
426  result += "java.lang.Class<";
427  result += PrettyDescriptor(c);
428  result += ">";
429  return result;
430}
431
432std::string PrettyClassAndClassLoader(mirror::Class* c) {
433  if (c == NULL) {
434    return "null";
435  }
436  std::string result;
437  result += "java.lang.Class<";
438  result += PrettyDescriptor(c);
439  result += ",";
440  result += PrettyTypeOf(c->GetClassLoader());
441  // TODO: add an identifying hash value for the loader
442  result += ">";
443  return result;
444}
445
446std::string PrettySize(int64_t byte_count) {
447  // The byte thresholds at which we display amounts.  A byte count is displayed
448  // in unit U when kUnitThresholds[U] <= bytes < kUnitThresholds[U+1].
449  static const int64_t kUnitThresholds[] = {
450    0,              // B up to...
451    3*1024,         // KB up to...
452    2*1024*1024,    // MB up to...
453    1024*1024*1024  // GB from here.
454  };
455  static const int64_t kBytesPerUnit[] = { 1, KB, MB, GB };
456  static const char* const kUnitStrings[] = { "B", "KB", "MB", "GB" };
457  const char* negative_str = "";
458  if (byte_count < 0) {
459    negative_str = "-";
460    byte_count = -byte_count;
461  }
462  int i = arraysize(kUnitThresholds);
463  while (--i > 0) {
464    if (byte_count >= kUnitThresholds[i]) {
465      break;
466    }
467  }
468  return StringPrintf("%s%" PRId64 "%s", negative_str, 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("%" PRIu64 "%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("%" PRIu64 ".%03" PRIu64 "%s", whole_part, fractional_part, unit);
546    } else if (zero_fill == 6) {
547      return StringPrintf("%" PRIu64 ".%06" PRIu64 "%s", whole_part, fractional_part, unit);
548    } else {
549      return StringPrintf("%" PRIu64 ".%09" PRIu64 "%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(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(mirror::ArtMethod* m) {
651  std::string long_name;
652  long_name += JniShortName(m);
653  long_name += "__";
654
655  std::string signature(MethodHelper(m).GetSignature().ToString());
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 */
728static bool IsValidPartOfMemberNameUtf8(const char** pUtf8Ptr) {
729  uint8_t c = (uint8_t) **pUtf8Ptr;
730  if (LIKELY(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 };
771static bool 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
900std::string Trim(std::string s) {
901  std::string result;
902  unsigned int start_index = 0;
903  unsigned int end_index = s.size() - 1;
904
905  // Skip initial whitespace.
906  while (start_index < s.size()) {
907    if (!isspace(s[start_index])) {
908      break;
909    }
910    start_index++;
911  }
912
913  // Skip terminating whitespace.
914  while (end_index >= start_index) {
915    if (!isspace(s[end_index])) {
916      break;
917    }
918    end_index--;
919  }
920
921  // All spaces, no beef.
922  if (end_index < start_index) {
923    return "";
924  }
925  // Start_index is the first non-space, end_index is the last one.
926  return s.substr(start_index, end_index - start_index + 1);
927}
928
929template <typename StringT>
930std::string Join(std::vector<StringT>& strings, char separator) {
931  if (strings.empty()) {
932    return "";
933  }
934
935  std::string result(strings[0]);
936  for (size_t i = 1; i < strings.size(); ++i) {
937    result += separator;
938    result += strings[i];
939  }
940  return result;
941}
942
943// Explicit instantiations.
944template std::string Join<std::string>(std::vector<std::string>& strings, char separator);
945template std::string Join<const char*>(std::vector<const char*>& strings, char separator);
946template std::string Join<char*>(std::vector<char*>& strings, char separator);
947
948bool StartsWith(const std::string& s, const char* prefix) {
949  return s.compare(0, strlen(prefix), prefix) == 0;
950}
951
952bool EndsWith(const std::string& s, const char* suffix) {
953  size_t suffix_length = strlen(suffix);
954  size_t string_length = s.size();
955  if (suffix_length > string_length) {
956    return false;
957  }
958  size_t offset = string_length - suffix_length;
959  return s.compare(offset, suffix_length, suffix) == 0;
960}
961
962void SetThreadName(const char* thread_name) {
963  int hasAt = 0;
964  int hasDot = 0;
965  const char* s = thread_name;
966  while (*s) {
967    if (*s == '.') {
968      hasDot = 1;
969    } else if (*s == '@') {
970      hasAt = 1;
971    }
972    s++;
973  }
974  int len = s - thread_name;
975  if (len < 15 || hasAt || !hasDot) {
976    s = thread_name;
977  } else {
978    s = thread_name + len - 15;
979  }
980#if defined(HAVE_ANDROID_PTHREAD_SETNAME_NP)
981  // pthread_setname_np fails rather than truncating long strings.
982  char buf[16];       // MAX_TASK_COMM_LEN=16 is hard-coded into bionic
983  strncpy(buf, s, sizeof(buf)-1);
984  buf[sizeof(buf)-1] = '\0';
985  errno = pthread_setname_np(pthread_self(), buf);
986  if (errno != 0) {
987    PLOG(WARNING) << "Unable to set the name of current thread to '" << buf << "'";
988  }
989#elif defined(__APPLE__) && MAC_OS_X_VERSION_MAX_ALLOWED >= 1060
990  pthread_setname_np(thread_name);
991#elif defined(HAVE_PRCTL)
992  prctl(PR_SET_NAME, (unsigned long) s, 0, 0, 0);  // NOLINT (unsigned long)
993#else
994  UNIMPLEMENTED(WARNING) << thread_name;
995#endif
996}
997
998void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu) {
999  *utime = *stime = *task_cpu = 0;
1000  std::string stats;
1001  if (!ReadFileToString(StringPrintf("/proc/self/task/%d/stat", tid), &stats)) {
1002    return;
1003  }
1004  // Skip the command, which may contain spaces.
1005  stats = stats.substr(stats.find(')') + 2);
1006  // Extract the three fields we care about.
1007  std::vector<std::string> fields;
1008  Split(stats, ' ', fields);
1009  *state = fields[0][0];
1010  *utime = strtoull(fields[11].c_str(), NULL, 10);
1011  *stime = strtoull(fields[12].c_str(), NULL, 10);
1012  *task_cpu = strtoull(fields[36].c_str(), NULL, 10);
1013}
1014
1015std::string GetSchedulerGroupName(pid_t tid) {
1016  // /proc/<pid>/cgroup looks like this:
1017  // 2:devices:/
1018  // 1:cpuacct,cpu:/
1019  // We want the third field from the line whose second field contains the "cpu" token.
1020  std::string cgroup_file;
1021  if (!ReadFileToString(StringPrintf("/proc/self/task/%d/cgroup", tid), &cgroup_file)) {
1022    return "";
1023  }
1024  std::vector<std::string> cgroup_lines;
1025  Split(cgroup_file, '\n', cgroup_lines);
1026  for (size_t i = 0; i < cgroup_lines.size(); ++i) {
1027    std::vector<std::string> cgroup_fields;
1028    Split(cgroup_lines[i], ':', cgroup_fields);
1029    std::vector<std::string> cgroups;
1030    Split(cgroup_fields[1], ',', cgroups);
1031    for (size_t i = 0; i < cgroups.size(); ++i) {
1032      if (cgroups[i] == "cpu") {
1033        return cgroup_fields[2].substr(1);  // Skip the leading slash.
1034      }
1035    }
1036  }
1037  return "";
1038}
1039
1040static std::string CleanMapName(const backtrace_map_t* map) {
1041  if (map == NULL || map->name.empty()) {
1042    return "???";
1043  }
1044  // Turn "/usr/local/google/home/enh/clean-dalvik-dev/out/host/linux-x86/lib/libartd.so"
1045  // into "libartd.so".
1046  size_t last_slash = map->name.rfind('/');
1047  if (last_slash == std::string::npos) {
1048    return map->name;
1049  }
1050  return map->name.substr(last_slash);
1051}
1052
1053void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
1054  UniquePtr<Backtrace> backtrace(Backtrace::Create(BACKTRACE_CURRENT_PROCESS, tid));
1055  if (!backtrace->Unwind(0)) {
1056    os << prefix << "(backtrace::Unwind failed for thread " << tid << ")\n";
1057    return;
1058  } else if (backtrace->NumFrames() == 0) {
1059    os << prefix << "(no native stack frames for thread " << tid << ")\n";
1060    return;
1061  }
1062
1063  for (Backtrace::const_iterator it = backtrace->begin();
1064       it != backtrace->end(); ++it) {
1065    // We produce output like this:
1066    // ]    #00 unwind_backtrace_thread+536 [0x55d75bb8] (libbacktrace.so)
1067    os << prefix;
1068    if (include_count) {
1069      os << StringPrintf("#%02zu ", it->num);
1070    }
1071    if (!it->func_name.empty()) {
1072      os << it->func_name;
1073    } else {
1074      os << "???";
1075    }
1076    if (it->func_offset != 0) {
1077      os << "+" << it->func_offset;
1078    }
1079    os << StringPrintf(" [%p]", reinterpret_cast<void*>(it->pc));
1080    os << " (" << CleanMapName(it->map) << ")\n";
1081  }
1082}
1083
1084#if defined(__APPLE__)
1085
1086// TODO: is there any way to get the kernel stack on Mac OS?
1087void DumpKernelStack(std::ostream&, pid_t, const char*, bool) {}
1088
1089#else
1090
1091void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix, bool include_count) {
1092  if (tid == GetTid()) {
1093    // There's no point showing that we're reading our stack out of /proc!
1094    return;
1095  }
1096
1097  std::string kernel_stack_filename(StringPrintf("/proc/self/task/%d/stack", tid));
1098  std::string kernel_stack;
1099  if (!ReadFileToString(kernel_stack_filename, &kernel_stack)) {
1100    os << prefix << "(couldn't read " << kernel_stack_filename << ")\n";
1101    return;
1102  }
1103
1104  std::vector<std::string> kernel_stack_frames;
1105  Split(kernel_stack, '\n', kernel_stack_frames);
1106  // We skip the last stack frame because it's always equivalent to "[<ffffffff>] 0xffffffff",
1107  // which looking at the source appears to be the kernel's way of saying "that's all, folks!".
1108  kernel_stack_frames.pop_back();
1109  for (size_t i = 0; i < kernel_stack_frames.size(); ++i) {
1110    // Turn "[<ffffffff8109156d>] futex_wait_queue_me+0xcd/0x110" into "futex_wait_queue_me+0xcd/0x110".
1111    const char* text = kernel_stack_frames[i].c_str();
1112    const char* close_bracket = strchr(text, ']');
1113    if (close_bracket != NULL) {
1114      text = close_bracket + 2;
1115    }
1116    os << prefix;
1117    if (include_count) {
1118      os << StringPrintf("#%02zd ", i);
1119    }
1120    os << text << "\n";
1121  }
1122}
1123
1124#endif
1125
1126const char* GetAndroidRoot() {
1127  const char* android_root = getenv("ANDROID_ROOT");
1128  if (android_root == NULL) {
1129    if (OS::DirectoryExists("/system")) {
1130      android_root = "/system";
1131    } else {
1132      LOG(FATAL) << "ANDROID_ROOT not set and /system does not exist";
1133      return "";
1134    }
1135  }
1136  if (!OS::DirectoryExists(android_root)) {
1137    LOG(FATAL) << "Failed to find ANDROID_ROOT directory " << android_root;
1138    return "";
1139  }
1140  return android_root;
1141}
1142
1143const char* GetAndroidData() {
1144  const char* android_data = getenv("ANDROID_DATA");
1145  if (android_data == NULL) {
1146    if (OS::DirectoryExists("/data")) {
1147      android_data = "/data";
1148    } else {
1149      LOG(FATAL) << "ANDROID_DATA not set and /data does not exist";
1150      return "";
1151    }
1152  }
1153  if (!OS::DirectoryExists(android_data)) {
1154    LOG(FATAL) << "Failed to find ANDROID_DATA directory " << android_data;
1155    return "";
1156  }
1157  return android_data;
1158}
1159
1160std::string GetDalvikCacheOrDie(const char* android_data) {
1161  std::string dalvik_cache(StringPrintf("%s/dalvik-cache", android_data));
1162
1163  if (!OS::DirectoryExists(dalvik_cache.c_str())) {
1164    if (StartsWith(dalvik_cache, "/tmp/")) {
1165      int result = mkdir(dalvik_cache.c_str(), 0700);
1166      if (result != 0) {
1167        LOG(FATAL) << "Failed to create dalvik-cache directory " << dalvik_cache;
1168        return "";
1169      }
1170    } else {
1171      LOG(FATAL) << "Failed to find dalvik-cache directory " << dalvik_cache;
1172      return "";
1173    }
1174  }
1175  return dalvik_cache;
1176}
1177
1178std::string GetDalvikCacheFilenameOrDie(const char* location) {
1179  std::string dalvik_cache(GetDalvikCacheOrDie(GetAndroidData()));
1180  if (location[0] != '/') {
1181    LOG(FATAL) << "Expected path in location to be absolute: "<< location;
1182  }
1183  std::string cache_file(&location[1]);  // skip leading slash
1184  if (!EndsWith(location, ".dex") && !EndsWith(location, ".art")) {
1185    cache_file += "/";
1186    cache_file += DexFile::kClassesDex;
1187  }
1188  std::replace(cache_file.begin(), cache_file.end(), '/', '@');
1189  return dalvik_cache + "/" + cache_file;
1190}
1191
1192bool IsZipMagic(uint32_t magic) {
1193  return (('P' == ((magic >> 0) & 0xff)) &&
1194          ('K' == ((magic >> 8) & 0xff)));
1195}
1196
1197bool IsDexMagic(uint32_t magic) {
1198  return DexFile::IsMagicValid(reinterpret_cast<const byte*>(&magic));
1199}
1200
1201bool IsOatMagic(uint32_t magic) {
1202  return (memcmp(reinterpret_cast<const byte*>(magic),
1203                 OatHeader::kOatMagic,
1204                 sizeof(OatHeader::kOatMagic)) == 0);
1205}
1206
1207bool Exec(std::vector<std::string>& arg_vector, std::string* error_msg) {
1208  const std::string command_line(Join(arg_vector, ' '));
1209
1210  CHECK_GE(arg_vector.size(), 1U) << command_line;
1211
1212  // Convert the args to char pointers.
1213  const char* program = arg_vector[0].c_str();
1214  std::vector<char*> args;
1215  for (size_t i = 0; i < arg_vector.size(); ++i) {
1216    const std::string& arg = arg_vector[i];
1217    char* arg_str = const_cast<char*>(arg.c_str());
1218    CHECK(arg_str != nullptr) << i;
1219    args.push_back(arg_str);
1220  }
1221  args.push_back(NULL);
1222
1223  // fork and exec
1224  pid_t pid = fork();
1225  if (pid == 0) {
1226    // no allocation allowed between fork and exec
1227
1228    // change process groups, so we don't get reaped by ProcessManager
1229    setpgid(0, 0);
1230
1231    execv(program, &args[0]);
1232
1233    *error_msg = StringPrintf("Failed to execv(%s): %s", command_line.c_str(), strerror(errno));
1234    return false;
1235  } else {
1236    if (pid == -1) {
1237      *error_msg = StringPrintf("Failed to execv(%s) because fork failed: %s",
1238                                command_line.c_str(), strerror(errno));
1239      return false;
1240    }
1241
1242    // wait for subprocess to finish
1243    int status;
1244    pid_t got_pid = TEMP_FAILURE_RETRY(waitpid(pid, &status, 0));
1245    if (got_pid != pid) {
1246      *error_msg = StringPrintf("Failed after fork for execv(%s) because waitpid failed: "
1247                                "wanted %d, got %d: %s",
1248                                command_line.c_str(), pid, got_pid, strerror(errno));
1249      return false;
1250    }
1251    if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
1252      *error_msg = StringPrintf("Failed execv(%s) because non-0 exit status",
1253                                command_line.c_str());
1254      return false;
1255    }
1256  }
1257  return true;
1258}
1259
1260}  // namespace art
1261