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 <string>
23#include <vector>
24
25#include "base/logging.h"
26#include "base/stringpiece.h"
27#include "base/stringprintf.h"
28#include "globals.h"
29#include "primitive.h"
30
31namespace art {
32
33class DexFile;
34
35namespace mirror {
36class ArtField;
37class ArtMethod;
38class Class;
39class Object;
40class String;
41}  // namespace mirror
42
43enum TimeUnit {
44  kTimeUnitNanosecond,
45  kTimeUnitMicrosecond,
46  kTimeUnitMillisecond,
47  kTimeUnitSecond,
48};
49
50template<typename T>
51static inline bool IsPowerOfTwo(T x) {
52  return (x & (x - 1)) == 0;
53}
54
55template<int n, typename T>
56static inline bool IsAligned(T x) {
57  COMPILE_ASSERT((n & (n - 1)) == 0, n_not_power_of_two);
58  return (x & (n - 1)) == 0;
59}
60
61template<int n, typename T>
62static inline bool IsAligned(T* x) {
63  return IsAligned<n>(reinterpret_cast<const uintptr_t>(x));
64}
65
66#define CHECK_ALIGNED(value, alignment) \
67  CHECK(::art::IsAligned<alignment>(value)) << reinterpret_cast<const void*>(value)
68
69#define DCHECK_ALIGNED(value, alignment) \
70  DCHECK(::art::IsAligned<alignment>(value)) << reinterpret_cast<const void*>(value)
71
72// Check whether an N-bit two's-complement representation can hold value.
73static inline bool IsInt(int N, word value) {
74  CHECK_LT(0, N);
75  CHECK_LT(N, kBitsPerWord);
76  word limit = static_cast<word>(1) << (N - 1);
77  return (-limit <= value) && (value < limit);
78}
79
80static inline bool IsUint(int N, word value) {
81  CHECK_LT(0, N);
82  CHECK_LT(N, kBitsPerWord);
83  word limit = static_cast<word>(1) << N;
84  return (0 <= value) && (value < limit);
85}
86
87static inline bool IsAbsoluteUint(int N, word value) {
88  CHECK_LT(0, N);
89  CHECK_LT(N, kBitsPerWord);
90  if (value < 0) value = -value;
91  return IsUint(N, value);
92}
93
94static inline uint16_t Low16Bits(uint32_t value) {
95  return static_cast<uint16_t>(value);
96}
97
98static inline uint16_t High16Bits(uint32_t value) {
99  return static_cast<uint16_t>(value >> 16);
100}
101
102static inline uint32_t Low32Bits(uint64_t value) {
103  return static_cast<uint32_t>(value);
104}
105
106static inline uint32_t High32Bits(uint64_t value) {
107  return static_cast<uint32_t>(value >> 32);
108}
109
110// A static if which determines whether to return type A or B based on the condition boolean.
111template <const bool condition, typename A, typename B>
112struct TypeStaticIf {
113  typedef A value;
114};
115
116// Specialization to handle the false case.
117template <typename A, typename B>
118struct TypeStaticIf<false, A,  B> {
119  typedef B value;
120};
121
122template<typename T>
123static inline T RoundDown(T x, int n) {
124  CHECK(IsPowerOfTwo(n));
125  return (x & -n);
126}
127
128template<typename T>
129static inline T RoundUp(T x, int n) {
130  return RoundDown(x + n - 1, n);
131}
132
133// Implementation is from "Hacker's Delight" by Henry S. Warren, Jr.,
134// figure 3-3, page 48, where the function is called clp2.
135static inline uint32_t RoundUpToPowerOfTwo(uint32_t x) {
136  x = x - 1;
137  x = x | (x >> 1);
138  x = x | (x >> 2);
139  x = x | (x >> 4);
140  x = x | (x >> 8);
141  x = x | (x >> 16);
142  return x + 1;
143}
144
145// Implementation is from "Hacker's Delight" by Henry S. Warren, Jr.,
146// figure 5-2, page 66, where the function is called pop.
147static inline int CountOneBits(uint32_t x) {
148  x = x - ((x >> 1) & 0x55555555);
149  x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
150  x = (x + (x >> 4)) & 0x0F0F0F0F;
151  x = x + (x >> 8);
152  x = x + (x >> 16);
153  return static_cast<int>(x & 0x0000003F);
154}
155
156#define CLZ(x) __builtin_clz(x)
157#define CTZ(x) __builtin_ctz(x)
158
159static inline bool NeedsEscaping(uint16_t ch) {
160  return (ch < ' ' || ch > '~');
161}
162
163static inline std::string PrintableChar(uint16_t ch) {
164  std::string result;
165  result += '\'';
166  if (NeedsEscaping(ch)) {
167    StringAppendF(&result, "\\u%04x", ch);
168  } else {
169    result += ch;
170  }
171  result += '\'';
172  return result;
173}
174
175// Returns an ASCII string corresponding to the given UTF-8 string.
176// Java escapes are used for non-ASCII characters.
177std::string PrintableString(const std::string& utf8);
178
179// Tests whether 's' starts with 'prefix'.
180bool StartsWith(const std::string& s, const char* prefix);
181
182// Tests whether 's' starts with 'suffix'.
183bool EndsWith(const std::string& s, const char* suffix);
184
185// Used to implement PrettyClass, PrettyField, PrettyMethod, and PrettyTypeOf,
186// one of which is probably more useful to you.
187// Returns a human-readable equivalent of 'descriptor'. So "I" would be "int",
188// "[[I" would be "int[][]", "[Ljava/lang/String;" would be
189// "java.lang.String[]", and so forth.
190std::string PrettyDescriptor(const mirror::String* descriptor);
191std::string PrettyDescriptor(const std::string& descriptor);
192std::string PrettyDescriptor(Primitive::Type type);
193std::string PrettyDescriptor(const mirror::Class* klass)
194    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
195
196// Returns a human-readable signature for 'f'. Something like "a.b.C.f" or
197// "int a.b.C.f" (depending on the value of 'with_type').
198std::string PrettyField(const mirror::ArtField* f, bool with_type = true)
199    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
200std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type = true);
201
202// Returns a human-readable signature for 'm'. Something like "a.b.C.m" or
203// "a.b.C.m(II)V" (depending on the value of 'with_signature').
204std::string PrettyMethod(const mirror::ArtMethod* m, bool with_signature = true)
205    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
206std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature = true);
207
208// Returns a human-readable form of the name of the *class* of the given object.
209// So given an instance of java.lang.String, the output would
210// be "java.lang.String". Given an array of int, the output would be "int[]".
211// Given String.class, the output would be "java.lang.Class<java.lang.String>".
212std::string PrettyTypeOf(const mirror::Object* obj)
213    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
214
215// Returns a human-readable form of the type at an index in the specified dex file.
216// Example outputs: char[], java.lang.String.
217std::string PrettyType(uint32_t type_idx, const DexFile& dex_file);
218
219// Returns a human-readable form of the name of the given class.
220// Given String.class, the output would be "java.lang.Class<java.lang.String>".
221std::string PrettyClass(const mirror::Class* c)
222    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
223
224// Returns a human-readable form of the name of the given class with its class loader.
225std::string PrettyClassAndClassLoader(const mirror::Class* c)
226    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
227
228// Returns a human-readable size string such as "1MB".
229std::string PrettySize(size_t size_in_bytes);
230
231// Returns a human-readable time string which prints every nanosecond while trying to limit the
232// number of trailing zeros. Prints using the largest human readable unit up to a second.
233// e.g. "1ms", "1.000000001s", "1.001us"
234std::string PrettyDuration(uint64_t nano_duration);
235
236// Format a nanosecond time to specified units.
237std::string FormatDuration(uint64_t nano_duration, TimeUnit time_unit);
238
239// Get the appropriate unit for a nanosecond duration.
240TimeUnit GetAppropriateTimeUnit(uint64_t nano_duration);
241
242// Get the divisor to convert from a nanoseconds to a time unit
243uint64_t GetNsToTimeUnitDivisor(TimeUnit time_unit);
244
245// Performs JNI name mangling as described in section 11.3 "Linking Native Methods"
246// of the JNI spec.
247std::string MangleForJni(const std::string& s);
248
249// Turn "java.lang.String" into "Ljava/lang/String;".
250std::string DotToDescriptor(const char* class_name);
251
252// Turn "Ljava/lang/String;" into "java.lang.String".
253std::string DescriptorToDot(const char* descriptor);
254
255// Turn "Ljava/lang/String;" into "java/lang/String".
256std::string DescriptorToName(const char* descriptor);
257
258// Tests for whether 's' is a valid class name in the three common forms:
259bool IsValidBinaryClassName(const char* s);  // "java.lang.String"
260bool IsValidJniClassName(const char* s);     // "java/lang/String"
261bool IsValidDescriptor(const char* s);       // "Ljava/lang/String;"
262
263// Returns whether the given string is a valid field or method name,
264// additionally allowing names that begin with '<' and end with '>'.
265bool IsValidMemberName(const char* s);
266
267// Returns the JNI native function name for the non-overloaded method 'm'.
268std::string JniShortName(const mirror::ArtMethod* m)
269    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
270// Returns the JNI native function name for the overloaded method 'm'.
271std::string JniLongName(const mirror::ArtMethod* m)
272    SHARED_LOCKS_REQUIRED(Locks::mutator_lock_);
273
274bool ReadFileToString(const std::string& file_name, std::string* result);
275
276// Returns the current date in ISO yyyy-mm-dd hh:mm:ss format.
277std::string GetIsoDate();
278
279// Returns the monotonic time since some unspecified starting point in milliseconds.
280uint64_t MilliTime();
281
282// Returns the monotonic time since some unspecified starting point in microseconds.
283uint64_t MicroTime();
284
285// Returns the monotonic time since some unspecified starting point in nanoseconds.
286uint64_t NanoTime();
287
288// Returns the thread-specific CPU-time clock in nanoseconds or -1 if unavailable.
289uint64_t ThreadCpuNanoTime();
290
291// Converts the given number of nanoseconds to milliseconds.
292static constexpr inline uint64_t NsToMs(uint64_t ns) {
293  return ns / 1000 / 1000;
294}
295
296// Converts the given number of milliseconds to nanoseconds
297static constexpr inline uint64_t MsToNs(uint64_t ns) {
298  return ns * 1000 * 1000;
299}
300
301#if defined(__APPLE__)
302// No clocks to specify on OS/X, fake value to pass to routines that require a clock.
303#define CLOCK_REALTIME 0xebadf00d
304#endif
305
306// Sleep for the given number of nanoseconds, a bad way to handle contention.
307void NanoSleep(uint64_t ns);
308
309// Initialize a timespec to either an absolute or relative time.
310void InitTimeSpec(bool absolute, int clock, int64_t ms, int32_t ns, timespec* ts);
311
312// Splits a string using the given separator character into a vector of
313// strings. Empty strings will be omitted.
314void Split(const std::string& s, char separator, std::vector<std::string>& result);
315
316// Joins a vector of strings into a single string, using the given separator.
317template <typename StringT> std::string Join(std::vector<StringT>& strings, char separator);
318
319// Returns the calling thread's tid. (The C libraries don't expose this.)
320pid_t GetTid();
321
322// Returns the given thread's name.
323std::string GetThreadName(pid_t tid);
324
325// Returns details of the given thread's stack.
326void GetThreadStack(pthread_t thread, void*& stack_base, size_t& stack_size);
327
328// Reads data from "/proc/self/task/${tid}/stat".
329void GetTaskStats(pid_t tid, char& state, int& utime, int& stime, int& task_cpu);
330
331// Returns the name of the scheduler group for the given thread the current process, or the empty string.
332std::string GetSchedulerGroupName(pid_t tid);
333
334// Sets the name of the current thread. The name may be truncated to an
335// implementation-defined limit.
336void SetThreadName(const char* thread_name);
337
338// Dumps the native stack for thread 'tid' to 'os'.
339void DumpNativeStack(std::ostream& os, pid_t tid, const char* prefix = "", bool include_count = true);
340
341// Dumps the kernel stack for thread 'tid' to 'os'. Note that this is only available on linux-x86.
342void DumpKernelStack(std::ostream& os, pid_t tid, const char* prefix = "", bool include_count = true);
343
344// Find $ANDROID_ROOT, /system, or abort
345const char* GetAndroidRoot();
346
347// Find $ANDROID_DATA, /data, or abort
348const char* GetAndroidData();
349
350// Returns the dalvik-cache location, or dies trying.
351std::string GetDalvikCacheOrDie(const char* android_data);
352
353// Returns the dalvik-cache location for a DexFile or OatFile, or dies trying.
354std::string GetDalvikCacheFilenameOrDie(const std::string& location);
355
356// Check whether the given magic matches a known file type.
357bool IsZipMagic(uint32_t magic);
358bool IsDexMagic(uint32_t magic);
359bool IsOatMagic(uint32_t magic);
360
361class VoidFunctor {
362 public:
363  template <typename A>
364  inline void operator() (A a) const {
365    UNUSED(a);
366  }
367
368  template <typename A, typename B>
369  inline void operator() (A a, B b) const {
370    UNUSED(a);
371    UNUSED(b);
372  }
373
374  template <typename A, typename B, typename C>
375  inline void operator() (A a, B b, C c) const {
376    UNUSED(a);
377    UNUSED(b);
378    UNUSED(c);
379  }
380};
381
382}  // namespace art
383
384#endif  // ART_RUNTIME_UTILS_H_
385