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