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