• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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_LIBARTBASE_BASE_UTILS_H_
18 #define ART_LIBARTBASE_BASE_UTILS_H_
19 
20 #include <pthread.h>
21 #include <stdlib.h>
22 
23 #include <random>
24 #include <string>
25 
26 #include <android-base/logging.h>
27 #include <android-base/parseint.h>
28 
29 #include "casts.h"
30 #include "globals.h"
31 #include "macros.h"
32 #include "pointer_size.h"
33 
34 #if defined(__linux__)
35 #include <sys/utsname.h>
36 #endif
37 
38 namespace art {
39 
PointerToLowMemUInt32(const void * p)40 static inline uint32_t PointerToLowMemUInt32(const void* p) {
41   uintptr_t intp = reinterpret_cast<uintptr_t>(p);
42   DCHECK_LE(intp, 0xFFFFFFFFU);
43   return intp & 0xFFFFFFFFU;
44 }
45 
46 // Returns a human-readable size string such as "1MB".
47 std::string PrettySize(uint64_t size_in_bytes);
48 
49 // Splits a string using the given separator character into a vector of
50 // strings. Empty strings will be omitted.
51 template<typename StrIn, typename Str>
52 void Split(const StrIn& s, char separator, std::vector<Str>* out_result);
53 
54 template<typename Str>
55 void Split(const Str& s, char separator, size_t len, Str* out_result);
56 
57 template<typename StrIn, typename Str, size_t kLen>
Split(const StrIn & s,char separator,std::array<Str,kLen> * out_result)58 void Split(const StrIn& s, char separator, std::array<Str, kLen>* out_result) {
59   Split<Str>(Str(s), separator, kLen, &((*out_result)[0]));
60 }
61 
62 // Returns the calling thread's tid. (The C libraries don't expose this.)
63 uint32_t GetTid();
64 
65 // Returns the given thread's name.
66 std::string GetThreadName(pid_t tid);
67 
68 // Sets the name of the current thread. The name may be truncated to an
69 // implementation-defined limit.
70 void SetThreadName(const char* thread_name);
71 
72 // Reads data from "/proc/self/task/${tid}/stat".
73 void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu);
74 
75 class VoidFunctor {
76  public:
77   template <typename A>
operator()78   inline void operator()([[maybe_unused]] A a) const {}
79 
80   template <typename A, typename B>
operator()81   inline void operator()([[maybe_unused]] A a, [[maybe_unused]] B b) const {}
82 
83   template <typename A, typename B, typename C>
operator()84   inline void operator()([[maybe_unused]] A a, [[maybe_unused]] B b, [[maybe_unused]] C c) const {}
85 };
86 
EntryPointToCodePointer(const void * entry_point)87 static inline const void* EntryPointToCodePointer(const void* entry_point) {
88   uintptr_t code = reinterpret_cast<uintptr_t>(entry_point);
89   // TODO: Make this Thumb2 specific. It is benign on other architectures as code is always at
90   //       least 2 byte aligned.
91   code &= ~0x1;
92   return reinterpret_cast<const void*>(code);
93 }
94 
95 #if defined(__BIONIC__)
96 struct Arc4RandomGenerator {
97   using result_type = uint32_t;
minArc4RandomGenerator98   static constexpr uint32_t min() { return std::numeric_limits<uint32_t>::min(); }
maxArc4RandomGenerator99   static constexpr uint32_t max() { return std::numeric_limits<uint32_t>::max(); }
operatorArc4RandomGenerator100   uint32_t operator() () { return arc4random(); }
101 };
102 using RNG = Arc4RandomGenerator;
103 #else
104 using RNG = std::random_device;
105 #endif
106 
107 template <typename T>
GetRandomNumber(T min,T max)108 static T GetRandomNumber(T min, T max) {
109   CHECK_LT(min, max);
110   std::uniform_int_distribution<T> dist(min, max);
111   RNG rng;
112   return dist(rng);
113 }
114 
115 // Sleep forever and never come back.
116 NO_RETURN void SleepForever();
117 
118 // Flush CPU caches. Returns true on success, false if flush failed.
119 WARN_UNUSED bool FlushCpuCaches(void* begin, void* end);
120 
121 #if defined(__linux__)
122 bool IsKernelVersionAtLeast(int reqd_major, int reqd_minor);
123 #endif
124 
125 // On some old kernels, a cache operation may segfault.
126 WARN_UNUSED bool CacheOperationsMaySegFault();
127 
128 template <typename Func, typename... Args>
CheckedCall(const Func & function,const char * what,Args...args)129 static inline void CheckedCall(const Func& function, const char* what, Args... args) {
130   int rc = function(args...);
131   if (UNLIKELY(rc != 0)) {
132     PLOG(FATAL) << "Checked call failed for " << what;
133   }
134 }
135 
136 // Forces the compiler to emit a load instruction, but discards the value.
137 // Useful when dealing with memory paging.
138 template <typename T>
ForceRead(const T * pointer)139 inline void ForceRead(const T* pointer) {
140   static_cast<void>(*const_cast<volatile T*>(pointer));
141 }
142 
143 // Lookup value for a given key in /proc/self/status. Keys and values are separated by a ':' in
144 // the status file. Returns value found on success and "<unknown>" if the key is not found or
145 // there is an I/O error.
146 std::string GetProcessStatus(const char* key);
147 
148 // Copy a prefix of /proc/tid/stat of the given length into buf. Return the number of bytes
149 // actually read, 0 on error.
150 size_t GetOsThreadStat(pid_t tid, char* buf, size_t len);
151 
152 // Return a short prefix of /proc/tid/stat as quickly and robustly as possible. Used for debugging
153 // timing issues and possibly issues with /proc itself. Always atomic.
154 std::string GetOsThreadStatQuick(pid_t tid);
155 
156 // Return a concatenation of the output of GetOsThreadStatQuick(tid) for all other tids.
157 // Less robust against concurrent change, but individual stat strings should still always
158 // be consistent. Called only when we are nearly certain to crash anyway.
159 std::string GetOtherThreadOsStats();
160 
161 }  // namespace art
162 
163 #endif  // ART_LIBARTBASE_BASE_UTILS_H_
164