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