utils.h revision 6eb987dd8afd001898f262263203a1a3ff3fcf83
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#ifndef ART_RUNTIME_UTILS_H_
18#define ART_RUNTIME_UTILS_H_
19
20#include <pthread.h>
21
22#include <limits>
23#include <memory>
24#include <string>
25#include <type_traits>
26#include <vector>
27
28#include "arch/instruction_set.h"
29#include "base/logging.h"
30#include "base/mutex.h"
31#include "globals.h"
32#include "primitive.h"
33
34namespace art {
35
36class DexFile;
37
38namespace mirror {
39class ArtField;
40class ArtMethod;
41class Class;
42class Object;
43class String;
44}  // namespace mirror
45
46enum TimeUnit {
47  kTimeUnitNanosecond,
48  kTimeUnitMicrosecond,
49  kTimeUnitMillisecond,
50  kTimeUnitSecond,
51};
52
53template <typename T>
54bool ParseUint(const char *in, T* out) {
55  char* end;
56  unsigned long long int result = strtoull(in, &end, 0);  // NOLINT(runtime/int)
57  if (in == end || *end != '\0') {
58    return false;
59  }
60  if (std::numeric_limits<T>::max() < result) {
61    return false;
62  }
63  *out = static_cast<T>(result);
64  return true;
65}
66
67template <typename T>
68bool ParseInt(const char* in, T* out) {
69  char* end;
70  long long int result = strtoll(in, &end, 0);  // NOLINT(runtime/int)
71  if (in == end || *end != '\0') {
72    return false;
73  }
74  if (result < std::numeric_limits<T>::min() || std::numeric_limits<T>::max() < result) {
75    return false;
76  }
77  *out = static_cast<T>(result);
78  return true;
79}
80
81template<typename T>
82static constexpr bool IsPowerOfTwo(T x) {
83  return (x & (x - 1)) == 0;
84}
85
86template<int n, typename T>
87static inline bool IsAligned(T x) {
88  static_assert((n & (n - 1)) == 0, "n is not a power of two");
89  return (x & (n - 1)) == 0;
90}
91
92template<int n, typename T>
93static inline bool IsAligned(T* x) {
94  return IsAligned<n>(reinterpret_cast<const uintptr_t>(x));
95}
96
97template<typename T>
98static inline bool IsAlignedParam(T x, int n) {
99  return (x & (n - 1)) == 0;
100}
101
102#define CHECK_ALIGNED(value, alignment) \
103  CHECK(::art::IsAligned<alignment>(value)) << reinterpret_cast<const void*>(value)
104
105#define DCHECK_ALIGNED(value, alignment) \
106  DCHECK(::art::IsAligned<alignment>(value)) << reinterpret_cast<const void*>(value)
107
108#define DCHECK_ALIGNED_PARAM(value, alignment) \
109  DCHECK(::art::IsAlignedParam(value, alignment)) << reinterpret_cast<const void*>(value)
110
111// Check whether an N-bit two's-complement representation can hold value.
112static inline bool IsInt(int N, intptr_t value) {
113  CHECK_LT(0, N);
114  CHECK_LT(N, kBitsPerIntPtrT);
115  intptr_t limit = static_cast<intptr_t>(1) << (N - 1);
116  return (-limit <= value) && (value < limit);
117}
118
119template <typename T>
120static constexpr T GetIntLimit(size_t bits) {
121  return
122      DCHECK_CONSTEXPR(bits > 0, "bits cannot be zero", 0)
123      DCHECK_CONSTEXPR(bits < kBitsPerByte * sizeof(T), "kBits must be < max.", 0)
124      static_cast<T>(1) << (bits - 1);
125}
126
127template <size_t kBits, typename T>
128static constexpr bool IsInt(T value) {
129  static_assert(kBits > 0, "kBits cannot be zero.");
130  static_assert(kBits <= kBitsPerByte * sizeof(T), "kBits must be <= max.");
131  static_assert(std::is_signed<T>::value, "Needs a signed type.");
132  // Corner case for "use all bits." Can't use the limits, as they would overflow, but it is
133  // trivially true.
134  return (kBits == kBitsPerByte * sizeof(T)) ?
135      true :
136      (-GetIntLimit<T>(kBits) <= value) && (value < GetIntLimit<T>(kBits));
137}
138
139template <size_t kBits, typename T>
140static constexpr bool IsUint(T value) {
141  static_assert(kBits > 0, "kBits cannot be zero.");
142  static_assert(kBits <= kBitsPerByte * sizeof(T), "kBits must be <= max.");
143  static_assert(std::is_integral<T>::value, "Needs an integral type.");
144  // Corner case for "use all bits." Can't use the limits, as they would overflow, but it is
145  // trivially true.
146  return (0 <= value) &&
147      (kBits == kBitsPerByte * sizeof(T) ||
148          (static_cast<typename std::make_unsigned<T>::type>(value) <=
149               GetIntLimit<typename std::make_unsigned<T>::type>(kBits + 1) - 1));
150}
151
152template <size_t kBits, typename T>
153static constexpr bool IsAbsoluteUint(T value) {
154  static_assert(kBits <= kBitsPerByte * sizeof(T), "kBits must be < max.");
155  return (kBits == kBitsPerByte * sizeof(T)) ?
156      true :
157      IsUint<kBits, T>(value < 0 ? -value : value);
158}
159
160static inline uint16_t Low16Bits(uint32_t value) {
161  return static_cast<uint16_t>(value);
162}
163
164static inline uint16_t High16Bits(uint32_t value) {
165  return static_cast<uint16_t>(value >> 16);
166}
167
168static inline uint32_t Low32Bits(uint64_t value) {
169  return static_cast<uint32_t>(value);
170}
171
172static inline uint32_t High32Bits(uint64_t value) {
173  return static_cast<uint32_t>(value >> 32);
174}
175
176// Traits class providing an unsigned integer type of (byte) size `n`.
177template <size_t n>
178struct UnsignedIntegerType {
179  // No defined `type`.
180};
181
182template <>
183struct UnsignedIntegerType<1> { typedef uint8_t type; };
184
185template <>
186struct UnsignedIntegerType<2> { typedef uint16_t type; };
187
188template <>
189struct UnsignedIntegerType<4> { typedef uint32_t type; };
190
191template <>
192struct UnsignedIntegerType<8> { typedef uint64_t type; };
193
194// Type identity.
195template <typename T>
196struct TypeIdentity {
197  typedef T type;
198};
199
200// Like sizeof, but count how many bits a type takes. Pass type explicitly.
201template <typename T>
202static constexpr size_t BitSizeOf() {
203  return sizeof(T) * CHAR_BIT;
204}
205
206// Like sizeof, but count how many bits a type takes. Infers type from parameter.
207template <typename T>
208static constexpr size_t BitSizeOf(T /*x*/) {
209  return sizeof(T) * CHAR_BIT;
210}
211
212// For rounding integers.
213template<typename T>
214static constexpr T RoundDown(T x, typename TypeIdentity<T>::type n) WARN_UNUSED;
215
216template<typename T>
217static constexpr T RoundDown(T x, typename TypeIdentity<T>::type n) {
218  return
219      DCHECK_CONSTEXPR(IsPowerOfTwo(n), , T(0))
220      (x & -n);
221}
222
223template<typename T>
224static constexpr T RoundUp(T x, typename TypeIdentity<T>::type n) WARN_UNUSED;
225
226template<typename T>
227static constexpr T RoundUp(T x, typename TypeIdentity<T>::type n) {
228  return RoundDown(x + n - 1, n);
229}
230
231// For aligning pointers.
232template<typename T>
233static inline T* AlignDown(T* x, uintptr_t n) WARN_UNUSED;
234
235template<typename T>
236static inline T* AlignDown(T* x, uintptr_t n) {
237  return reinterpret_cast<T*>(RoundDown(reinterpret_cast<uintptr_t>(x), n));
238}
239
240template<typename T>
241static inline T* AlignUp(T* x, uintptr_t n) WARN_UNUSED;
242
243template<typename T>
244static inline T* AlignUp(T* x, uintptr_t n) {
245  return reinterpret_cast<T*>(RoundUp(reinterpret_cast<uintptr_t>(x), n));
246}
247
248namespace utils {
249namespace detail {  // Private, implementation-specific namespace. Do not poke outside of this file.
250template <typename T>
251static constexpr inline T RoundUpToPowerOfTwoRecursive(T x, size_t bit) {
252  return bit == (BitSizeOf<T>()) ? x: RoundUpToPowerOfTwoRecursive(x | x >> bit, bit << 1);
253}
254}  // namespace detail
255}  // namespace utils
256
257// Recursive implementation is from "Hacker's Delight" by Henry S. Warren, Jr.,
258// figure 3-3, page 48, where the function is called clp2.
259template <typename T>
260static constexpr inline T RoundUpToPowerOfTwo(T x) {
261  return art::utils::detail::RoundUpToPowerOfTwoRecursive(x - 1, 1) + 1;
262}
263
264// Find the bit position of the most significant bit (0-based), or -1 if there were no bits set.
265template <typename T>
266static constexpr ssize_t MostSignificantBit(T value) {
267  return (value == 0) ? -1 : (MostSignificantBit(value >> 1) + 1);
268}
269
270// How many bits (minimally) does it take to store the constant 'value'? i.e. 1 for 1, 3 for 5, etc.
271template <typename T>
272static constexpr size_t MinimumBitsToStore(T value) {
273  return static_cast<size_t>(MostSignificantBit(value) + 1);
274}
275
276template<typename T>
277static constexpr int CLZ(T x) {
278  static_assert(sizeof(T) <= sizeof(long long), "T too large, must be smaller than long long");  // NOLINT [runtime/int] [4]
279  return (sizeof(T) == sizeof(uint32_t))
280      ? __builtin_clz(x)  // TODO: __builtin_clz[ll] has undefined behavior for x=0
281      : __builtin_clzll(x);
282}
283
284template<typename T>
285static constexpr int CTZ(T x) {
286  return (sizeof(T) == sizeof(uint32_t))
287      ? __builtin_ctz(x)
288      : __builtin_ctzll(x);
289}
290
291template<typename T>
292static inline int WhichPowerOf2(T x) {
293  DCHECK((x != 0) && IsPowerOfTwo(x));
294  return CTZ(x);
295}
296
297template<typename T>
298static constexpr int POPCOUNT(T x) {
299  return (sizeof(T) == sizeof(uint32_t))
300      ? __builtin_popcount(x)
301      : __builtin_popcountll(x);
302}
303
304static inline uint32_t PointerToLowMemUInt32(const void* p) {
305  uintptr_t intp = reinterpret_cast<uintptr_t>(p);
306  DCHECK_LE(intp, 0xFFFFFFFFU);
307  return intp & 0xFFFFFFFFU;
308}
309
310static inline bool NeedsEscaping(uint16_t ch) {
311  return (ch < ' ' || ch > '~');
312}
313
314// Interpret the bit pattern of input (type U) as type V. Requires the size
315// of V >= size of U (compile-time checked).
316template<typename U, typename V>
317static inline V bit_cast(U in) {
318  static_assert(sizeof(U) <= sizeof(V), "Size of U not <= size of V");
319  union {
320    U u;
321    V v;
322  } tmp;
323  tmp.u = in;
324  return tmp.v;
325}
326
327std::string PrintableChar(uint16_t ch);
328
329// Returns an ASCII string corresponding to the given UTF-8 string.
330// Java escapes are used for non-ASCII characters.
331std::string PrintableString(const char* utf8);
332
333// Tests whether 's' starts with 'prefix'.
334bool StartsWith(const std::string& s, const char* prefix);
335
336// Tests whether 's' ends with 'suffix'.
337bool EndsWith(const std::string& s, const char* suffix);
338
339// Used to implement PrettyClass, PrettyField, PrettyMethod, and PrettyTypeOf,
340// one of which is probably more useful to you.
341// Returns a human-readable equivalent of 'descriptor'. So "I" would be "int",
342// "[[I" would be "int[][]", "[Ljava/lang/String;" would be
343// "java.lang.String[]", and so forth.
344std::string PrettyDescriptor(mirror::String* descriptor)
345    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
346std::string PrettyDescriptor(const char* descriptor);
347std::string PrettyDescriptor(mirror::Class* klass)
348    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
349std::string PrettyDescriptor(Primitive::Type type);
350
351// Returns a human-readable signature for 'f'. Something like "a.b.C.f" or
352// "int a.b.C.f" (depending on the value of 'with_type').
353std::string PrettyField(mirror::ArtField* f, bool with_type = true)
354    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
355std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type = true);
356
357// Returns a human-readable signature for 'm'. Something like "a.b.C.m" or
358// "a.b.C.m(II)V" (depending on the value of 'with_signature').
359std::string PrettyMethod(mirror::ArtMethod* m, bool with_signature = true)
360    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
361std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature = true);
362
363// Returns a human-readable form of the name of the *class* of the given object.
364// So given an instance of java.lang.String, the output would
365// be "java.lang.String". Given an array of int, the output would be "int[]".
366// Given String.class, the output would be "java.lang.Class<java.lang.String>".
367std::string PrettyTypeOf(mirror::Object* obj)
368    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
369
370// Returns a human-readable form of the type at an index in the specified dex file.
371// Example outputs: char[], java.lang.String.
372std::string PrettyType(uint32_t type_idx, const DexFile& dex_file);
373
374// Returns a human-readable form of the name of the given class.
375// Given String.class, the output would be "java.lang.Class<java.lang.String>".
376std::string PrettyClass(mirror::Class* c)
377    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
378
379// Returns a human-readable form of the name of the given class with its class loader.
380std::string PrettyClassAndClassLoader(mirror::Class* c)
381    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
382
383// Returns a human-readable version of the Java part of the access flags, e.g., "private static "
384// (note the trailing whitespace).
385std::string PrettyJavaAccessFlags(uint32_t access_flags);
386
387// Returns a human-readable size string such as "1MB".
388std::string PrettySize(int64_t size_in_bytes);
389
390// Returns a human-readable time string which prints every nanosecond while trying to limit the
391// number of trailing zeros. Prints using the largest human readable unit up to a second.
392// e.g. "1ms", "1.000000001s", "1.001us"
393std::string PrettyDuration(uint64_t nano_duration, size_t max_fraction_digits = 3);
394
395// Format a nanosecond time to specified units.
396std::string FormatDuration(uint64_t nano_duration, TimeUnit time_unit,
397                           size_t max_fraction_digits);
398
399// Get the appropriate unit for a nanosecond duration.
400TimeUnit GetAppropriateTimeUnit(uint64_t nano_duration);
401
402// Get the divisor to convert from a nanoseconds to a time unit.
403uint64_t GetNsToTimeUnitDivisor(TimeUnit time_unit);
404
405// Performs JNI name mangling as described in section 11.3 "Linking Native Methods"
406// of the JNI spec.
407std::string MangleForJni(const std::string& s);
408
409// Turn "java.lang.String" into "Ljava/lang/String;".
410std::string DotToDescriptor(const char* class_name);
411
412// Turn "Ljava/lang/String;" into "java.lang.String" using the conventions of
413// java.lang.Class.getName().
414std::string DescriptorToDot(const char* descriptor);
415
416// Turn "Ljava/lang/String;" into "java/lang/String" using the opposite conventions of
417// java.lang.Class.getName().
418std::string DescriptorToName(const char* descriptor);
419
420// Tests for whether 's' is a valid class name in the three common forms:
421bool IsValidBinaryClassName(const char* s);  // "java.lang.String"
422bool IsValidJniClassName(const char* s);     // "java/lang/String"
423bool IsValidDescriptor(const char* s);       // "Ljava/lang/String;"
424
425// Returns whether the given string is a valid field or method name,
426// additionally allowing names that begin with '<' and end with '>'.
427bool IsValidMemberName(const char* s);
428
429// Returns the JNI native function name for the non-overloaded method 'm'.
430std::string JniShortName(mirror::ArtMethod* m)
431    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
432// Returns the JNI native function name for the overloaded method 'm'.
433std::string JniLongName(mirror::ArtMethod* m)
434    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
435
436bool ReadFileToString(const std::string& file_name, std::string* result);
437bool PrintFileToLog(const std::string& file_name, LogSeverity level);
438
439// Returns the current date in ISO yyyy-mm-dd hh:mm:ss format.
440std::string GetIsoDate();
441
442// Returns the monotonic time since some unspecified starting point in milliseconds.
443uint64_t MilliTime();
444
445// Returns the monotonic time since some unspecified starting point in microseconds.
446uint64_t MicroTime();
447
448// Returns the monotonic time since some unspecified starting point in nanoseconds.
449uint64_t NanoTime();
450
451// Returns the thread-specific CPU-time clock in nanoseconds or -1 if unavailable.
452uint64_t ThreadCpuNanoTime();
453
454// Converts the given number of nanoseconds to milliseconds.
455static constexpr inline uint64_t NsToMs(uint64_t ns) {
456  return ns / 1000 / 1000;
457}
458
459// Converts the given number of milliseconds to nanoseconds
460static constexpr inline uint64_t MsToNs(uint64_t ns) {
461  return ns * 1000 * 1000;
462}
463
464#if defined(__APPLE__)
465// No clocks to specify on OS/X, fake value to pass to routines that require a clock.
466#define CLOCK_REALTIME 0xebadf00d
467#endif
468
469// Sleep for the given number of nanoseconds, a bad way to handle contention.
470void NanoSleep(uint64_t ns);
471
472// Initialize a timespec to either a relative time (ms,ns), or to the absolute
473// time corresponding to the indicated clock value plus the supplied offset.
474void InitTimeSpec(bool absolute, int clock, int64_t ms, int32_t ns, timespec* ts);
475
476// Splits a string using the given separator character into a vector of
477// strings. Empty strings will be omitted.
478void Split(const std::string& s, char separator, std::vector<std::string>* result);
479
480// Trims whitespace off both ends of the given string.
481std::string Trim(const std::string& s);
482
483// Joins a vector of strings into a single string, using the given separator.
484template <typename StringT> std::string Join(const std::vector<StringT>& strings, char separator);
485
486// Returns the calling thread's tid. (The C libraries don't expose this.)
487pid_t GetTid();
488
489// Returns the given thread's name.
490std::string GetThreadName(pid_t tid);
491
492// Returns details of the given thread's stack.
493void GetThreadStack(pthread_t thread, void** stack_base, size_t* stack_size, size_t* guard_size);
494
495// Reads data from "/proc/self/task/${tid}/stat".
496void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu);
497
498// Returns the name of the scheduler group for the given thread the current process, or the empty string.
499std::string GetSchedulerGroupName(pid_t tid);
500
501// Sets the name of the current thread. The name may be truncated to an
502// implementation-defined limit.
503void SetThreadName(const char* thread_name);
504
505// Dumps the native stack for thread 'tid' to 'os'.
506void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix = "",
507    mirror::ArtMethod* current_method = nullptr, void* ucontext = nullptr)
508    NO_THREAD_SAFETY_ANALYSIS;
509
510// Dumps the kernel stack for thread 'tid' to 'os'. Note that this is only available on linux-x86.
511void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix = "", bool include_count = true);
512
513// Find $ANDROID_ROOT, /system, or abort.
514const char* GetAndroidRoot();
515
516// Find $ANDROID_DATA, /data, or abort.
517const char* GetAndroidData();
518// Find $ANDROID_DATA, /data, or return nullptr.
519const char* GetAndroidDataSafe(std::string* error_msg);
520
521// Returns the dalvik-cache location, or dies trying. subdir will be
522// appended to the cache location.
523std::string GetDalvikCacheOrDie(const char* subdir, bool create_if_absent = true);
524// Return true if we found the dalvik cache and stored it in the dalvik_cache argument.
525// have_android_data will be set to true if we have an ANDROID_DATA that exists,
526// dalvik_cache_exists will be true if there is a dalvik-cache directory that is present.
527// The flag is_global_cache tells whether this cache is /data/dalvik-cache.
528void GetDalvikCache(const char* subdir, bool create_if_absent, std::string* dalvik_cache,
529                    bool* have_android_data, bool* dalvik_cache_exists, bool* is_global_cache);
530
531// Returns the absolute dalvik-cache path for a DexFile or OatFile. The path returned will be
532// rooted at cache_location.
533bool GetDalvikCacheFilename(const char* file_location, const char* cache_location,
534                            std::string* filename, std::string* error_msg);
535// Returns the absolute dalvik-cache path for a DexFile or OatFile, or
536// dies trying. The path returned will be rooted at cache_location.
537std::string GetDalvikCacheFilenameOrDie(const char* file_location,
538                                        const char* cache_location);
539
540// Returns the system location for an image
541std::string GetSystemImageFilename(const char* location, InstructionSet isa);
542
543// Check whether the given magic matches a known file type.
544bool IsZipMagic(uint32_t magic);
545bool IsDexMagic(uint32_t magic);
546bool IsOatMagic(uint32_t magic);
547
548// Wrapper on fork/execv to run a command in a subprocess.
549bool Exec(std::vector<std::string>& arg_vector, std::string* error_msg);
550
551class VoidFunctor {
552 public:
553  template <typename A>
554  inline void operator() (A a) const {
555    UNUSED(a);
556  }
557
558  template <typename A, typename B>
559  inline void operator() (A a, B b) const {
560    UNUSED(a, b);
561  }
562
563  template <typename A, typename B, typename C>
564  inline void operator() (A a, B b, C c) const {
565    UNUSED(a, b, c);
566  }
567};
568
569template <typename Alloc>
570void Push32(std::vector<uint8_t, Alloc>* buf, int32_t data) {
571  buf->push_back(data & 0xff);
572  buf->push_back((data >> 8) & 0xff);
573  buf->push_back((data >> 16) & 0xff);
574  buf->push_back((data >> 24) & 0xff);
575}
576
577void EncodeUnsignedLeb128(uint32_t data, std::vector<uint8_t>* buf);
578void EncodeSignedLeb128(int32_t data, std::vector<uint8_t>* buf);
579
580// Deleter using free() for use with std::unique_ptr<>. See also UniqueCPtr<> below.
581struct FreeDelete {
582  // NOTE: Deleting a const object is valid but free() takes a non-const pointer.
583  void operator()(const void* ptr) const {
584    free(const_cast<void*>(ptr));
585  }
586};
587
588// Alias for std::unique_ptr<> that uses the C function free() to delete objects.
589template <typename T>
590using UniqueCPtr = std::unique_ptr<T, FreeDelete>;
591
592// C++14 from-the-future import (std::make_unique)
593// Invoke the constructor of 'T' with the provided args, and wrap the result in a unique ptr.
594template <typename T, typename ... Args>
595std::unique_ptr<T> MakeUnique(Args&& ... args) {
596  return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
597}
598
599}  // namespace art
600
601#endif  // ART_RUNTIME_UTILS_H_
602