1 /*
2  * Copyright (C) 2015 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 SIMPLE_PERF_UTILS_H_
18 #define SIMPLE_PERF_UTILS_H_
19 
20 #include <stddef.h>
21 #include <stdio.h>
22 #include <time.h>
23 
24 #include <fstream>
25 #include <functional>
26 #include <optional>
27 #include <set>
28 #include <string>
29 #include <vector>
30 
31 #include <android-base/logging.h>
32 #include <android-base/macros.h>
33 #include <android-base/parseint.h>
34 #include <android-base/strings.h>
35 #include <android-base/unique_fd.h>
36 #include <ziparchive/zip_archive.h>
37 
38 namespace simpleperf {
39 
AlignDown(uint64_t value,uint64_t alignment)40 static inline uint64_t AlignDown(uint64_t value, uint64_t alignment) {
41   return value & ~(alignment - 1);
42 }
43 
Align(uint64_t value,uint64_t alignment)44 static inline uint64_t Align(uint64_t value, uint64_t alignment) {
45   return AlignDown(value + alignment - 1, alignment);
46 }
47 
48 #ifdef _WIN32
49 #define CLOSE_ON_EXEC_MODE ""
50 #define OS_PATH_SEPARATOR '\\'
51 #else
52 #define CLOSE_ON_EXEC_MODE "e"
53 #define OS_PATH_SEPARATOR '/'
54 #endif
55 
56 // OneTimeAllocator is used to allocate memory many times and free only once at the end.
57 // It reduces the cost to free each allocated memory.
58 class OneTimeFreeAllocator {
59  public:
60   explicit OneTimeFreeAllocator(size_t unit_size = 8192u)
unit_size_(unit_size)61       : unit_size_(unit_size), cur_(nullptr), end_(nullptr) {}
62 
~OneTimeFreeAllocator()63   ~OneTimeFreeAllocator() { Clear(); }
64 
65   void Clear();
66   const char* AllocateString(std::string_view s);
67 
68  private:
69   const size_t unit_size_;
70   std::vector<char*> v_;
71   char* cur_;
72   char* end_;
73 };
74 
75 class LineReader {
76  public:
LineReader(std::string_view file_path)77   explicit LineReader(std::string_view file_path) : ifs_(file_path) {}
78   // Return true if open file successfully.
Ok()79   bool Ok() const { return ifs_.good(); }
80   // If available, return next line content with new line, otherwise return nullptr.
ReadLine()81   std::string* ReadLine() { return (std::getline(ifs_, buf_)) ? &buf_ : nullptr; }
82 
83  private:
84   std::ifstream ifs_;
85   std::string buf_;
86 };
87 
88 class FileHelper {
89  public:
90   static android::base::unique_fd OpenReadOnly(const std::string& filename);
91   static android::base::unique_fd OpenWriteOnly(const std::string& filename);
92 };
93 
94 class ArchiveHelper {
95  public:
96   static std::unique_ptr<ArchiveHelper> CreateInstance(const std::string& filename);
97   ~ArchiveHelper();
98   // Iterate each entry in the zip file. Break the iteration when callback returns false.
99   bool IterateEntries(const std::function<bool(ZipEntry&, const std::string&)>& callback);
100   bool FindEntry(const std::string& name, ZipEntry* entry);
101   bool GetEntryData(ZipEntry& entry, std::vector<uint8_t>* data);
102   int GetFd();
103 
104  private:
ArchiveHelper(ZipArchiveHandle handle,const std::string & filename)105   ArchiveHelper(ZipArchiveHandle handle, const std::string& filename)
106       : handle_(handle), filename_(filename) {}
107 
108   ZipArchiveHandle handle_;
109   std::string filename_;
110 
111   DISALLOW_COPY_AND_ASSIGN(ArchiveHelper);
112 };
113 
114 template <class T>
MoveFromBinaryFormat(T & data,const char * & p)115 void MoveFromBinaryFormat(T& data, const char*& p) {
116   static_assert(std::is_standard_layout<T>::value, "not standard layout");
117   memcpy(&data, p, sizeof(T));
118   p += sizeof(T);
119 }
120 
121 template <class T>
MoveFromBinaryFormat(T & data,char * & p)122 void MoveFromBinaryFormat(T& data, char*& p) {
123   static_assert(std::is_standard_layout<T>::value, "not standard layout");
124   memcpy(&data, p, sizeof(T));
125   p += sizeof(T);
126 }
127 
128 template <class T>
MoveFromBinaryFormat(T * data_p,size_t n,const char * & p)129 void MoveFromBinaryFormat(T* data_p, size_t n, const char*& p) {
130   static_assert(std::is_standard_layout<T>::value, "not standard layout");
131   size_t size = n * sizeof(T);
132   memcpy(data_p, p, size);
133   p += size;
134 }
135 
136 template <class T>
MoveToBinaryFormat(const T & data,char * & p)137 void MoveToBinaryFormat(const T& data, char*& p) {
138   static_assert(std::is_standard_layout<T>::value, "not standard layout");
139   memcpy(p, &data, sizeof(T));
140   p += sizeof(T);
141 }
142 
143 template <class T>
MoveToBinaryFormat(const T * data_p,size_t n,char * & p)144 void MoveToBinaryFormat(const T* data_p, size_t n, char*& p) {
145   static_assert(std::is_standard_layout<T>::value, "not standard layout");
146   size_t size = n * sizeof(T);
147   memcpy(p, data_p, size);
148   p += size;
149 }
150 
151 void PrintIndented(size_t indent, const char* fmt, ...);
152 void FprintIndented(FILE* fp, size_t indent, const char* fmt, ...);
153 
154 bool IsPowerOfTwo(uint64_t value);
155 
156 std::vector<std::string> GetEntriesInDir(const std::string& dirpath);
157 std::vector<std::string> GetSubDirs(const std::string& dirpath);
158 bool IsDir(const std::string& dirpath);
159 bool IsRegularFile(const std::string& filename);
160 uint64_t GetFileSize(const std::string& filename);
161 bool MkdirWithParents(const std::string& path);
162 
163 bool XzDecompress(const std::string& compressed_data, std::string* decompressed_data);
164 
165 bool GetLogSeverity(const std::string& name, android::base::LogSeverity* severity);
166 std::string GetLogSeverityName();
167 
168 bool IsRoot();
169 
170 size_t GetPageSize();
171 
172 uint64_t ConvertBytesToValue(const char* bytes, uint32_t size);
173 
174 timeval SecondToTimeval(double time_in_sec);
175 
176 std::string GetSimpleperfVersion();
177 
178 std::optional<std::set<int>> GetCpusFromString(const std::string& s);
179 std::optional<std::set<pid_t>> GetTidsFromString(const std::string& s, bool check_if_exists);
180 
181 template <typename T>
ParseUintVector(const std::string & s)182 std::optional<std::set<T>> ParseUintVector(const std::string& s) {
183   std::set<T> result;
184   T value;
185   for (const auto& p : android::base::Split(s, ",")) {
186     if (!android::base::ParseUint(p.c_str(), &value, std::numeric_limits<T>::max())) {
187       LOG(ERROR) << "Invalid Uint '" << p << "' in " << s;
188       return std::nullopt;
189     }
190     result.insert(value);
191   }
192   return result;
193 }
194 
195 // from boost::hash_combine
196 template <typename T>
HashCombine(size_t & seed,const T & val)197 static inline void HashCombine(size_t& seed, const T& val) {
198   seed ^= std::hash<T>()(val) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
199 }
200 
201 }  // namespace simpleperf
202 
203 #endif  // SIMPLE_PERF_UTILS_H_
204