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