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
40 static constexpr size_t kKilobyte = 1024;
41 static constexpr size_t kMegabyte = 1024 * kKilobyte;
42 static constexpr uint64_t kGigabyte = 1024 * kMegabyte;
43
AlignDown(uint64_t value,uint64_t alignment)44 static inline uint64_t AlignDown(uint64_t value, uint64_t alignment) {
45 return value & ~(alignment - 1);
46 }
47
Align(uint64_t value,uint64_t alignment)48 static inline uint64_t Align(uint64_t value, uint64_t alignment) {
49 return AlignDown(value + alignment - 1, alignment);
50 }
51
52 #ifdef _WIN32
53 #define CLOSE_ON_EXEC_MODE ""
54 #define OS_PATH_SEPARATOR '\\'
55 #else
56 #define CLOSE_ON_EXEC_MODE "e"
57 #define OS_PATH_SEPARATOR '/'
58 #endif
59
60 // OneTimeAllocator is used to allocate memory many times and free only once at the end.
61 // It reduces the cost to free each allocated memory.
62 class OneTimeFreeAllocator {
63 public:
64 explicit OneTimeFreeAllocator(size_t unit_size = 8192u)
unit_size_(unit_size)65 : unit_size_(unit_size), cur_(nullptr), end_(nullptr) {}
66
~OneTimeFreeAllocator()67 ~OneTimeFreeAllocator() { Clear(); }
68
69 void Clear();
70 const char* AllocateString(std::string_view s);
71
72 private:
73 const size_t unit_size_;
74 std::vector<char*> v_;
75 char* cur_;
76 char* end_;
77 };
78
79 class LineReader {
80 public:
LineReader(std::string_view file_path)81 explicit LineReader(std::string_view file_path) : ifs_(file_path) {}
82 // Return true if open file successfully.
Ok()83 bool Ok() const { return ifs_.good(); }
84 // If available, return next line content with new line, otherwise return nullptr.
ReadLine()85 std::string* ReadLine() { return (std::getline(ifs_, buf_)) ? &buf_ : nullptr; }
86
87 private:
88 std::ifstream ifs_;
89 std::string buf_;
90 };
91
92 class FileHelper {
93 public:
94 static android::base::unique_fd OpenReadOnly(const std::string& filename);
95 static android::base::unique_fd OpenWriteOnly(const std::string& filename);
96 };
97
98 class ArchiveHelper {
99 public:
100 static std::unique_ptr<ArchiveHelper> CreateInstance(const std::string& filename);
101 ~ArchiveHelper();
102 // Iterate each entry in the zip file. Break the iteration when callback returns false.
103 bool IterateEntries(const std::function<bool(ZipEntry&, const std::string&)>& callback);
104 bool FindEntry(const std::string& name, ZipEntry* entry);
105 bool GetEntryData(ZipEntry& entry, std::vector<uint8_t>* data);
106 int GetFd();
107
108 private:
ArchiveHelper(ZipArchiveHandle handle,const std::string & filename)109 ArchiveHelper(ZipArchiveHandle handle, const std::string& filename)
110 : handle_(handle), filename_(filename) {}
111
112 ZipArchiveHandle handle_;
113 std::string filename_;
114
115 DISALLOW_COPY_AND_ASSIGN(ArchiveHelper);
116 };
117
118 template <class T>
MoveFromBinaryFormat(T & data,const char * & p)119 void MoveFromBinaryFormat(T& data, const char*& p) {
120 static_assert(std::is_standard_layout<T>::value, "not standard layout");
121 memcpy(&data, p, sizeof(T));
122 p += sizeof(T);
123 }
124
125 template <class T>
MoveFromBinaryFormat(T & data,char * & p)126 void MoveFromBinaryFormat(T& data, char*& p) {
127 static_assert(std::is_standard_layout<T>::value, "not standard layout");
128 memcpy(&data, p, sizeof(T));
129 p += sizeof(T);
130 }
131
132 template <class T>
MoveFromBinaryFormat(T * data_p,size_t n,const char * & p)133 void MoveFromBinaryFormat(T* data_p, size_t n, const char*& p) {
134 static_assert(std::is_standard_layout<T>::value, "not standard layout");
135 size_t size = n * sizeof(T);
136 memcpy(data_p, p, size);
137 p += size;
138 }
139
140 template <class T>
MoveToBinaryFormat(const T & data,char * & p)141 void MoveToBinaryFormat(const T& data, char*& p) {
142 static_assert(std::is_standard_layout<T>::value, "not standard layout");
143 memcpy(p, &data, sizeof(T));
144 p += sizeof(T);
145 }
146
147 template <class T>
MoveToBinaryFormat(const T * data_p,size_t n,char * & p)148 void MoveToBinaryFormat(const T* data_p, size_t n, char*& p) {
149 static_assert(std::is_standard_layout<T>::value, "not standard layout");
150 size_t size = n * sizeof(T);
151 memcpy(p, data_p, size);
152 p += size;
153 }
154
155 // Read info from binary data.
156 struct BinaryReader {
157 public:
BinaryReaderBinaryReader158 BinaryReader(const char* head, size_t size) : head(head), end(head + size), error(false) {}
159
LeftSizeBinaryReader160 size_t LeftSize() const { return end - head; }
161
CheckLeftSizeBinaryReader162 bool CheckLeftSize(size_t size) {
163 if (UNLIKELY(error)) {
164 return false;
165 }
166 if (UNLIKELY(LeftSize() < size)) {
167 error = true;
168 return false;
169 }
170 return true;
171 }
172
MoveBinaryReader173 void Move(size_t size) {
174 if (CheckLeftSize(size)) {
175 head += size;
176 }
177 }
178
179 template <class T>
ReadBinaryReader180 void Read(T& data) {
181 static_assert(std::is_standard_layout<T>::value, "not standard layout");
182 if (UNLIKELY(error)) {
183 return;
184 }
185 if (UNLIKELY(LeftSize() < sizeof(T))) {
186 error = true;
187 } else {
188 memcpy(&data, head, sizeof(T));
189 head += sizeof(T);
190 }
191 }
192
193 template <class T>
ReadBinaryReader194 void Read(T* data_p, size_t n) {
195 static_assert(std::is_standard_layout<T>::value, "not standard layout");
196 if (UNLIKELY(error)) {
197 return;
198 }
199 size_t size;
200 if (UNLIKELY(__builtin_mul_overflow(n, sizeof(T), &size) || LeftSize() < size)) {
201 error = true;
202 } else {
203 memcpy(data_p, head, size);
204 head += size;
205 }
206 }
207
208 // Read a string ending with '\0'.
ReadStringBinaryReader209 std::string ReadString() {
210 if (UNLIKELY(error)) {
211 return "";
212 }
213 std::string result;
214 while (head < end && *head != '\0') {
215 result.push_back(*head++);
216 }
217 if (LIKELY(head < end && *head == '\0')) {
218 head++;
219 return result;
220 }
221 error = true;
222 return "";
223 }
224
225 const char* head;
226 const char* end;
227 bool error;
228 };
229
230 void PrintIndented(size_t indent, const char* fmt, ...);
231 void FprintIndented(FILE* fp, size_t indent, const char* fmt, ...);
232
233 bool IsPowerOfTwo(uint64_t value);
234
235 std::vector<std::string> GetEntriesInDir(const std::string& dirpath);
236 std::vector<std::string> GetSubDirs(const std::string& dirpath);
237 bool IsDir(const std::string& dirpath);
238 bool IsRegularFile(const std::string& filename);
239 uint64_t GetFileSize(const std::string& filename);
240 bool MkdirWithParents(const std::string& path);
241
242 bool XzDecompress(const std::string& compressed_data, std::string* decompressed_data);
243
244 bool GetLogSeverity(const std::string& name, android::base::LogSeverity* severity);
245 std::string GetLogSeverityName();
246
247 bool IsRoot();
248
249 size_t GetPageSize();
250
251 uint64_t ConvertBytesToValue(const char* bytes, uint32_t size);
252
253 timeval SecondToTimeval(double time_in_sec);
254
255 std::string GetSimpleperfVersion();
256
257 std::optional<std::set<int>> GetCpusFromString(const std::string& s);
258 std::optional<std::set<pid_t>> GetTidsFromString(const std::string& s, bool check_if_exists);
259 std::optional<std::set<pid_t>> GetPidsFromStrings(const std::vector<std::string>& strs,
260 bool check_if_exists,
261 bool support_progress_name_regex);
262
263 template <typename T>
ParseUintVector(const std::string & s)264 std::optional<std::set<T>> ParseUintVector(const std::string& s) {
265 std::set<T> result;
266 T value;
267 for (const auto& p : android::base::Split(s, ",")) {
268 if (!android::base::ParseUint(p.c_str(), &value, std::numeric_limits<T>::max())) {
269 LOG(ERROR) << "Invalid Uint '" << p << "' in " << s;
270 return std::nullopt;
271 }
272 result.insert(value);
273 }
274 return result;
275 }
276
277 // from boost::hash_combine
278 template <typename T>
HashCombine(size_t & seed,const T & val)279 static inline void HashCombine(size_t& seed, const T& val) {
280 seed ^= std::hash<T>()(val) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
281 }
282
283 size_t SafeStrlen(const char* s, const char* end);
284
285 struct OverflowResult {
286 bool overflow = false;
287 uint64_t value = 0;
288 };
289
290 OverflowResult SafeAdd(uint64_t a, uint64_t b);
291 void OverflowSafeAdd(uint64_t& dest, uint64_t add);
292
293 } // namespace simpleperf
294
295 #endif // SIMPLE_PERF_UTILS_H_
296