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 #include <stdlib.h>
22 
23 #include <limits>
24 #include <memory>
25 #include <random>
26 #include <string>
27 #include <type_traits>
28 #include <vector>
29 
30 #include "arch/instruction_set.h"
31 #include "base/casts.h"
32 #include "base/logging.h"
33 #include "base/mutex.h"
34 #include "base/stringpiece.h"
35 #include "globals.h"
36 #include "primitive.h"
37 
38 class BacktraceMap;
39 
40 namespace art {
41 
42 class ArtField;
43 class ArtMethod;
44 class DexFile;
45 
46 namespace mirror {
47 class Class;
48 class Object;
49 class String;
50 }  // namespace mirror
51 
52 template <typename T>
ParseUint(const char * in,T * out)53 bool 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 
66 template <typename T>
ParseInt(const char * in,T * out)67 bool 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 
80 // Return whether x / divisor == x * (1.0f / divisor), for every float x.
CanDivideByReciprocalMultiplyFloat(int32_t divisor)81 static constexpr bool CanDivideByReciprocalMultiplyFloat(int32_t divisor) {
82   // True, if the most significant bits of divisor are 0.
83   return ((divisor & 0x7fffff) == 0);
84 }
85 
86 // Return whether x / divisor == x * (1.0 / divisor), for every double x.
CanDivideByReciprocalMultiplyDouble(int64_t divisor)87 static constexpr bool CanDivideByReciprocalMultiplyDouble(int64_t divisor) {
88   // True, if the most significant bits of divisor are 0.
89   return ((divisor & ((UINT64_C(1) << 52) - 1)) == 0);
90 }
91 
PointerToLowMemUInt32(const void * p)92 static inline uint32_t PointerToLowMemUInt32(const void* p) {
93   uintptr_t intp = reinterpret_cast<uintptr_t>(p);
94   DCHECK_LE(intp, 0xFFFFFFFFU);
95   return intp & 0xFFFFFFFFU;
96 }
97 
NeedsEscaping(uint16_t ch)98 static inline bool NeedsEscaping(uint16_t ch) {
99   return (ch < ' ' || ch > '~');
100 }
101 
SafeAbs(T value)102 template <typename T> T SafeAbs(T value) {
103   // std::abs has undefined behavior on min limits.
104   DCHECK_NE(value, std::numeric_limits<T>::min());
105   return std::abs(value);
106 }
107 
AbsOrMin(T value)108 template <typename T> T AbsOrMin(T value) {
109   return (value == std::numeric_limits<T>::min())
110       ? value
111       : std::abs(value);
112 }
113 
114 template <typename T>
MakeUnsigned(T x)115 inline typename std::make_unsigned<T>::type MakeUnsigned(T x) {
116   return static_cast<typename std::make_unsigned<T>::type>(x);
117 }
118 
119 std::string PrintableChar(uint16_t ch);
120 
121 // Returns an ASCII string corresponding to the given UTF-8 string.
122 // Java escapes are used for non-ASCII characters.
123 std::string PrintableString(const char* utf8);
124 
125 // Tests whether 's' starts with 'prefix'.
126 bool StartsWith(const std::string& s, const char* prefix);
127 
128 // Tests whether 's' ends with 'suffix'.
129 bool EndsWith(const std::string& s, const char* suffix);
130 
131 // Used to implement PrettyClass, PrettyField, PrettyMethod, and PrettyTypeOf,
132 // one of which is probably more useful to you.
133 // Returns a human-readable equivalent of 'descriptor'. So "I" would be "int",
134 // "[[I" would be "int[][]", "[Ljava/lang/String;" would be
135 // "java.lang.String[]", and so forth.
136 std::string PrettyDescriptor(mirror::String* descriptor)
137     SHARED_REQUIRES(Locks::mutator_lock_);
138 std::string PrettyDescriptor(const char* descriptor);
139 std::string PrettyDescriptor(mirror::Class* klass)
140     SHARED_REQUIRES(Locks::mutator_lock_);
141 std::string PrettyDescriptor(Primitive::Type type);
142 
143 // Returns a human-readable signature for 'f'. Something like "a.b.C.f" or
144 // "int a.b.C.f" (depending on the value of 'with_type').
145 std::string PrettyField(ArtField* f, bool with_type = true)
146     SHARED_REQUIRES(Locks::mutator_lock_);
147 std::string PrettyField(uint32_t field_idx, const DexFile& dex_file, bool with_type = true);
148 
149 // Returns a human-readable signature for 'm'. Something like "a.b.C.m" or
150 // "a.b.C.m(II)V" (depending on the value of 'with_signature').
151 std::string PrettyMethod(ArtMethod* m, bool with_signature = true)
152     SHARED_REQUIRES(Locks::mutator_lock_);
153 std::string PrettyMethod(uint32_t method_idx, const DexFile& dex_file, bool with_signature = true);
154 
155 // Returns a human-readable form of the name of the *class* of the given object.
156 // So given an instance of java.lang.String, the output would
157 // be "java.lang.String". Given an array of int, the output would be "int[]".
158 // Given String.class, the output would be "java.lang.Class<java.lang.String>".
159 std::string PrettyTypeOf(mirror::Object* obj)
160     SHARED_REQUIRES(Locks::mutator_lock_);
161 
162 // Returns a human-readable form of the type at an index in the specified dex file.
163 // Example outputs: char[], java.lang.String.
164 std::string PrettyType(uint32_t type_idx, const DexFile& dex_file);
165 
166 // Returns a human-readable form of the name of the given class.
167 // Given String.class, the output would be "java.lang.Class<java.lang.String>".
168 std::string PrettyClass(mirror::Class* c)
169     SHARED_REQUIRES(Locks::mutator_lock_);
170 
171 // Returns a human-readable form of the name of the given class with its class loader.
172 std::string PrettyClassAndClassLoader(mirror::Class* c)
173     SHARED_REQUIRES(Locks::mutator_lock_);
174 
175 // Returns a human-readable version of the Java part of the access flags, e.g., "private static "
176 // (note the trailing whitespace).
177 std::string PrettyJavaAccessFlags(uint32_t access_flags);
178 
179 // Returns a human-readable size string such as "1MB".
180 std::string PrettySize(int64_t size_in_bytes);
181 
182 // Performs JNI name mangling as described in section 11.3 "Linking Native Methods"
183 // of the JNI spec.
184 std::string MangleForJni(const std::string& s);
185 
186 // Turn "java.lang.String" into "Ljava/lang/String;".
187 std::string DotToDescriptor(const char* class_name);
188 
189 // Turn "Ljava/lang/String;" into "java.lang.String" using the conventions of
190 // java.lang.Class.getName().
191 std::string DescriptorToDot(const char* descriptor);
192 
193 // Turn "Ljava/lang/String;" into "java/lang/String" using the opposite conventions of
194 // java.lang.Class.getName().
195 std::string DescriptorToName(const char* descriptor);
196 
197 // Tests for whether 's' is a valid class name in the three common forms:
198 bool IsValidBinaryClassName(const char* s);  // "java.lang.String"
199 bool IsValidJniClassName(const char* s);     // "java/lang/String"
200 bool IsValidDescriptor(const char* s);       // "Ljava/lang/String;"
201 
202 // Returns whether the given string is a valid field or method name,
203 // additionally allowing names that begin with '<' and end with '>'.
204 bool IsValidMemberName(const char* s);
205 
206 // Returns the JNI native function name for the non-overloaded method 'm'.
207 std::string JniShortName(ArtMethod* m)
208     SHARED_REQUIRES(Locks::mutator_lock_);
209 // Returns the JNI native function name for the overloaded method 'm'.
210 std::string JniLongName(ArtMethod* m)
211     SHARED_REQUIRES(Locks::mutator_lock_);
212 
213 bool ReadFileToString(const std::string& file_name, std::string* result);
214 bool PrintFileToLog(const std::string& file_name, LogSeverity level);
215 
216 // Splits a string using the given separator character into a vector of
217 // strings. Empty strings will be omitted.
218 void Split(const std::string& s, char separator, std::vector<std::string>* result);
219 
220 // Trims whitespace off both ends of the given string.
221 std::string Trim(const std::string& s);
222 
223 // Joins a vector of strings into a single string, using the given separator.
224 template <typename StringT> std::string Join(const std::vector<StringT>& strings, char separator);
225 
226 // Returns the calling thread's tid. (The C libraries don't expose this.)
227 pid_t GetTid();
228 
229 // Returns the given thread's name.
230 std::string GetThreadName(pid_t tid);
231 
232 // Returns details of the given thread's stack.
233 void GetThreadStack(pthread_t thread, void** stack_base, size_t* stack_size, size_t* guard_size);
234 
235 // Reads data from "/proc/self/task/${tid}/stat".
236 void GetTaskStats(pid_t tid, char* state, int* utime, int* stime, int* task_cpu);
237 
238 // Returns the name of the scheduler group for the given thread the current process, or the empty string.
239 std::string GetSchedulerGroupName(pid_t tid);
240 
241 // Sets the name of the current thread. The name may be truncated to an
242 // implementation-defined limit.
243 void SetThreadName(const char* thread_name);
244 
245 // Dumps the native stack for thread 'tid' to 'os'.
246 void DumpNativeStack(std::ostream& os,
247                      pid_t tid,
248                      BacktraceMap* map = nullptr,
249                      const char* prefix = "",
250                      ArtMethod* current_method = nullptr,
251                      void* ucontext = nullptr)
252     NO_THREAD_SAFETY_ANALYSIS;
253 
254 // Dumps the kernel stack for thread 'tid' to 'os'. Note that this is only available on linux-x86.
255 void DumpKernelStack(std::ostream& os,
256                      pid_t tid,
257                      const char* prefix = "",
258                      bool include_count = true);
259 
260 // Find $ANDROID_ROOT, /system, or abort.
261 const char* GetAndroidRoot();
262 
263 // Find $ANDROID_DATA, /data, or abort.
264 const char* GetAndroidData();
265 // Find $ANDROID_DATA, /data, or return null.
266 const char* GetAndroidDataSafe(std::string* error_msg);
267 
268 // Returns the dalvik-cache location, with subdir appended. Returns the empty string if the cache
269 // could not be found (or created).
270 std::string GetDalvikCache(const char* subdir, bool create_if_absent = true);
271 // Returns the dalvik-cache location, or dies trying. subdir will be
272 // appended to the cache location.
273 std::string GetDalvikCacheOrDie(const char* subdir, bool create_if_absent = true);
274 // Return true if we found the dalvik cache and stored it in the dalvik_cache argument.
275 // have_android_data will be set to true if we have an ANDROID_DATA that exists,
276 // dalvik_cache_exists will be true if there is a dalvik-cache directory that is present.
277 // The flag is_global_cache tells whether this cache is /data/dalvik-cache.
278 void GetDalvikCache(const char* subdir, bool create_if_absent, std::string* dalvik_cache,
279                     bool* have_android_data, bool* dalvik_cache_exists, bool* is_global_cache);
280 
281 // Returns the absolute dalvik-cache path for a DexFile or OatFile. The path returned will be
282 // rooted at cache_location.
283 bool GetDalvikCacheFilename(const char* file_location, const char* cache_location,
284                             std::string* filename, std::string* error_msg);
285 // Returns the absolute dalvik-cache path for a DexFile or OatFile, or
286 // dies trying. The path returned will be rooted at cache_location.
287 std::string GetDalvikCacheFilenameOrDie(const char* file_location,
288                                         const char* cache_location);
289 
290 // Returns the system location for an image
291 std::string GetSystemImageFilename(const char* location, InstructionSet isa);
292 
293 // Wrapper on fork/execv to run a command in a subprocess.
294 bool Exec(std::vector<std::string>& arg_vector, std::string* error_msg);
295 int ExecAndReturnCode(std::vector<std::string>& arg_vector, std::string* error_msg);
296 
297 // Returns true if the file exists.
298 bool FileExists(const std::string& filename);
299 bool FileExistsAndNotEmpty(const std::string& filename);
300 
301 class VoidFunctor {
302  public:
303   template <typename A>
operator()304   inline void operator() (A a ATTRIBUTE_UNUSED) const {
305   }
306 
307   template <typename A, typename B>
operator()308   inline void operator() (A a ATTRIBUTE_UNUSED, B b ATTRIBUTE_UNUSED) const {
309   }
310 
311   template <typename A, typename B, typename C>
operator()312   inline void operator() (A a ATTRIBUTE_UNUSED, B b ATTRIBUTE_UNUSED, C c ATTRIBUTE_UNUSED) const {
313   }
314 };
315 
316 template <typename Vector>
Push32(Vector * buf,int32_t data)317 void Push32(Vector* buf, int32_t data) {
318   static_assert(std::is_same<typename Vector::value_type, uint8_t>::value, "Invalid value type");
319   buf->push_back(data & 0xff);
320   buf->push_back((data >> 8) & 0xff);
321   buf->push_back((data >> 16) & 0xff);
322   buf->push_back((data >> 24) & 0xff);
323 }
324 
TestBitmap(size_t idx,const uint8_t * bitmap)325 inline bool TestBitmap(size_t idx, const uint8_t* bitmap) {
326   return ((bitmap[idx / kBitsPerByte] >> (idx % kBitsPerByte)) & 0x01) != 0;
327 }
328 
ValidPointerSize(size_t pointer_size)329 static inline constexpr bool ValidPointerSize(size_t pointer_size) {
330   return pointer_size == 4 || pointer_size == 8;
331 }
332 
333 void DumpMethodCFG(ArtMethod* method, std::ostream& os) SHARED_REQUIRES(Locks::mutator_lock_);
334 void DumpMethodCFG(const DexFile* dex_file, uint32_t dex_method_idx, std::ostream& os);
335 
EntryPointToCodePointer(const void * entry_point)336 static inline const void* EntryPointToCodePointer(const void* entry_point) {
337   uintptr_t code = reinterpret_cast<uintptr_t>(entry_point);
338   // TODO: Make this Thumb2 specific. It is benign on other architectures as code is always at
339   //       least 2 byte aligned.
340   code &= ~0x1;
341   return reinterpret_cast<const void*>(code);
342 }
343 
344 using UsageFn = void (*)(const char*, ...);
345 
346 template <typename T>
347 static void ParseUintOption(const StringPiece& option,
348                             const std::string& option_name,
349                             T* out,
350                             UsageFn Usage,
351                             bool is_long_option = true) {
352   std::string option_prefix = option_name + (is_long_option ? "=" : "");
353   DCHECK(option.starts_with(option_prefix)) << option << " " << option_prefix;
354   const char* value_string = option.substr(option_prefix.size()).data();
355   int64_t parsed_integer_value = 0;
356   if (!ParseInt(value_string, &parsed_integer_value)) {
357     Usage("Failed to parse %s '%s' as an integer", option_name.c_str(), value_string);
358   }
359   if (parsed_integer_value < 0) {
360     Usage("%s passed a negative value %d", option_name.c_str(), parsed_integer_value);
361   }
362   *out = dchecked_integral_cast<T>(parsed_integer_value);
363 }
364 
365 void ParseDouble(const std::string& option,
366                  char after_char,
367                  double min,
368                  double max,
369                  double* parsed_value,
370                  UsageFn Usage);
371 
372 #if defined(__BIONIC__)
373 struct Arc4RandomGenerator {
374   typedef uint32_t result_type;
minArc4RandomGenerator375   static constexpr uint32_t min() { return std::numeric_limits<uint32_t>::min(); }
maxArc4RandomGenerator376   static constexpr uint32_t max() { return std::numeric_limits<uint32_t>::max(); }
operatorArc4RandomGenerator377   uint32_t operator() () { return arc4random(); }
378 };
379 using RNG = Arc4RandomGenerator;
380 #else
381 using RNG = std::random_device;
382 #endif
383 
384 template <typename T>
GetRandomNumber(T min,T max)385 T GetRandomNumber(T min, T max) {
386   CHECK_LT(min, max);
387   std::uniform_int_distribution<T> dist(min, max);
388   RNG rng;
389   return dist(rng);
390 }
391 
392 // Return the file size in bytes or -1 if the file does not exists.
393 int64_t GetFileSizeBytes(const std::string& filename);
394 
395 // Sleep forever and never come back.
396 NO_RETURN void SleepForever();
397 
FlushInstructionCache(char * begin,char * end)398 inline void FlushInstructionCache(char* begin, char* end) {
399   // Only use __builtin___clear_cache with Clang or with GCC >= 4.3.0
400   // (__builtin___clear_cache was introduced in GCC 4.3.0).
401 #if defined(__clang__) || GCC_VERSION >= 40300
402   __builtin___clear_cache(begin, end);
403 #else
404   // Only warn on non-Intel platforms, as x86 and x86-64 do not need
405   // cache flush instructions, as long as the "code uses the same
406   // linear address for modifying and fetching the instruction". See
407   // "Intel(R) 64 and IA-32 Architectures Software Developer's Manual
408   // Volume 3A: System Programming Guide, Part 1", section 11.6
409   // "Self-Modifying Code".
410 #if !defined(__i386__) && !defined(__x86_64__)
411   UNIMPLEMENTED(WARNING) << "cache flush";
412 #endif
413 #endif
414 }
415 
416 }  // namespace art
417 
418 #endif  // ART_RUNTIME_UTILS_H_
419