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