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