1 // Copyright 2022 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef BASE_ANDROID_THREAD_INSTRUCTION_COUNT_H_ 6 #define BASE_ANDROID_THREAD_INSTRUCTION_COUNT_H_ 7 8 #include <stdint.h> 9 10 #include "base/base_export.h" 11 12 namespace base { 13 namespace android { 14 15 // Represents the number of instructions that were retired between two samples 16 // of a thread's performance counters. 17 class BASE_EXPORT ThreadInstructionDelta { 18 public: ThreadInstructionDelta()19 constexpr ThreadInstructionDelta() : delta_(0) {} ThreadInstructionDelta(int64_t delta)20 explicit constexpr ThreadInstructionDelta(int64_t delta) : delta_(delta) {} 21 ToInternalValue()22 constexpr int64_t ToInternalValue() const { return delta_; } 23 24 private: 25 int64_t delta_; 26 }; 27 28 // Helper class for reading the current count of instructions retired for the 29 // current thread via ThreadInstructionCount::Now(). Does *not* count 30 // instructions retired while running in the kernel. 31 // 32 // Limitations: 33 // * Crashes when used in sandboxed process 34 // * Works on a userdebug build of Android 12, kernel 4.19. May require extra 35 // effort to allow on later Android releases and kernel versions. 36 class BASE_EXPORT ThreadInstructionCount { 37 public: 38 // Returns true if the platform supports hardware retired instruction 39 // counters. May crash in sandboxed processes. 40 static bool IsSupported(); 41 42 // Returns the number of retired instructions relative to some epoch count, 43 // or 0 if getting the current instruction count failed / is disabled. 44 static ThreadInstructionCount Now(); 45 46 explicit constexpr ThreadInstructionCount(uint64_t value = 0) value_(value)47 : value_(value) {} 48 49 constexpr ThreadInstructionDelta operator-( 50 ThreadInstructionCount other) const { 51 return ThreadInstructionDelta(static_cast<int64_t>(value_ - other.value_)); 52 } 53 ToInternalValue()54 constexpr uint64_t ToInternalValue() const { return value_; } 55 56 private: 57 uint64_t value_; 58 }; 59 60 } // namespace android 61 } // namespace base 62 63 #endif // BASE_ANDROID_THREAD_INSTRUCTION_COUNT_H_ 64