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