1 /*
2 * Copyright (c) Huawei Technologies Co., Ltd. 2021. All rights reserved.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #ifndef HIPERF_UTILITIES_H_
16 #define HIPERF_UTILITIES_H_
17
18 // for security function
19 #include <securec.h>
20
21 #include <algorithm>
22 #include <cctype>
23 #include <cinttypes>
24 #include <cstdio>
25 #include <fstream>
26 #include <iomanip>
27 #include <iostream>
28 #include <sstream>
29 #include <string>
30 #include <vector>
31 #include <unordered_set>
32
33 #include <dirent.h>
34 #include <fcntl.h>
35 #include <file_ex.h>
36 #include <stddef.h>
37 #include <sys/stat.h>
38 #include <unique_fd.h>
39 #include <unistd.h>
40 #if !is_mingw
41 #include <gtest/gtest_prod.h>
42 #include <sys/syscall.h>
43 #endif
44 #include <linux/types.h>
45
46 #include "debug_logger.h"
47 #include "noncopyable.h"
48
49 // data and value
50 /*
51 long long always 64 only in ILP64, int is 64 otherwise int is always 32
52 */
53 using s8 = __s8;
54 using u8 = __u8;
55 using s16 = __s16;
56 using u16 = __u16;
57 using s32 = __s32;
58 using u32 = __u32;
59 using s64 = __s64;
60 using u64 = __u64;
61
62 constexpr const int NUMBER_FORMAT_HEX_BASE = 16;
63 constexpr const int BYTE_PRINT_WIDTH = 2;
64 constexpr const int UINT64_PRINT_WIDTH = BYTE_PRINT_WIDTH * 8;
65 constexpr const int BITS_OF_BYTE = 8;
66 constexpr const int BITS_OF_TWO_BYTE = 2 * BITS_OF_BYTE;
67 constexpr const int BITS_OF_FOUR_BYTE = 4 * BITS_OF_BYTE;
68 constexpr const int FULL_PERCENTAGE = 100;
69 constexpr const int FULL_PERCENTAGE_NUM_LEN = 5; // 100.00
70 constexpr const int FULL_PERCENTAGE_DIFF_NUM_LEN = 6; // +100.00
71 constexpr const int FULL_PERCENTAGE_LEN = 6; // 100.00%
72 constexpr const int FULL_PERCENTAGE_DIFF_LEN = 7; // +100.00%
73 constexpr const int THOUSANDS = 1000;
74 constexpr const int HUNDREDS = 100;
75 constexpr const int DEFAULT_STRING_BUF_SIZE = 4096;
76 constexpr const int FIVE_THOUSANDS = 5000;
77 #if !is_mingw
78 #ifndef O_BINARY
79 #define O_BINARY 0
80 #endif
81 #endif
82
83 constexpr const double MS_DUARTION =
84 static_cast<double>(std::chrono::milliseconds::duration::period::den);
85
86 constexpr uint64_t KILO = 1024;
87
88 namespace OHOS {
89 namespace Developtools {
90 namespace NativeDaemon {
91 namespace {
92 const std::string EMPTY_STRING = "";
93 constexpr int32_t STRING_POOL_SIZE = 4000;
94 }
95
96 // string function
97 class StringViewMemoryHold {
98 public:
HoldStringView(const std::string & view)99 const char *HoldStringView(const std::string& view)
100 {
101 pthread_spin_lock(&spin_lock_);
102 const char* str = stringSet_.emplace(view).first->data();
103 pthread_spin_unlock(&spin_lock_);
104 return str;
105 };
106
GetInstance()107 static StringViewMemoryHold& GetInstance()
108 {
109 static StringViewMemoryHold s;
110 return s;
111 }
112
Clear()113 void Clear()
114 {
115 pthread_spin_lock(&spin_lock_);
116 stringSet_.clear();
117 pthread_spin_unlock(&spin_lock_);
118 }
119
120 private:
StringViewMemoryHold()121 StringViewMemoryHold()
122 {
123 pthread_spin_init(&spin_lock_, PTHREAD_PROCESS_PRIVATE);
124 }
~StringViewMemoryHold()125 ~StringViewMemoryHold()
126 {
127 pthread_spin_destroy(&spin_lock_);
128 }
129 std::unordered_set<std::string> stringSet_{STRING_POOL_SIZE};
130 pthread_spinlock_t spin_lock_;
131 };
132
133 std::string StringReplace(std::string source, const std::string &from, const std::string &to);
134
135 template<class T>
VectorToString(const std::vector<T> & items)136 std::string VectorToString(const std::vector<T> &items)
137 {
138 if constexpr (std::is_same<T, std::vector<std::string>>::value) {
139 std::vector<std::string> stringItems;
140 for (auto item : items) {
141 stringItems.push_back("[" + VectorToString(item) + "]");
142 }
143 return VectorToString(stringItems);
144 } else {
145 std::string itemsString;
146 const std::string split = ",";
147 for (auto& item : items) {
148 if (!itemsString.empty())
149 itemsString.append(split);
150 if constexpr (std::is_same<T, std::string>::value) {
151 itemsString.append(item);
152 } else {
153 itemsString.append(std::to_string(item));
154 }
155 }
156 if (itemsString.empty())
157 itemsString.append("<empty>");
158 return itemsString;
159 }
160 }
161
162 std::string BufferToHexString(const std::vector<unsigned char> &vec);
163 std::string BufferToHexString(const unsigned char buf[], size_t size);
164 void HexDump(const uint8_t *buf, size_t size, size_t max_size = 0);
165
166 std::string &StringTrim(std::string &s);
167
168 std::vector<std::string> StringSplit(std::string source, std::string split = ",");
169
170 size_t SubStringCount(const std::string &source, const std::string &sub);
171
172 bool StringStartsWith(const std::string &string, const std::string &with);
173
174 bool StringEndsWith(const std::string &string, const std::string &with);
175
176 bool IsSameCommand(std::string cmdLine, std::string cmdName);
177
178 std::vector<pid_t> GetSubthreadIDs(const pid_t pid);
179
180 bool IsDigits(const std::string &str);
181
182 bool IsHexDigits(const std::string &str);
183
184 constexpr const int COMPRESS_READ_BUF_SIZE = 4096;
185 // compress specified dataFile into gzip file
186 bool CompressFile(const std::string &dataFile, const std::string &destFile);
187 // uncompress specified gzip file into dataFile
188 bool UncompressFile(const std::string &gzipFile, const std::string &dataFile);
189
190 template<typename... VA>
StringPrintf(const char * stringFormat,VA...args)191 std::string StringPrintf(const char *stringFormat, VA... args)
192 {
193 // check howmany bytes we need
194 char bytes[DEFAULT_STRING_BUF_SIZE];
195 bytes[DEFAULT_STRING_BUF_SIZE - 1] = '\0';
196
197 if (stringFormat == nullptr) {
198 return EMPTY_STRING;
199 }
200
201 // print it to bytes
202 if (snprintf_s(bytes, sizeof(bytes), DEFAULT_STRING_BUF_SIZE - 1, stringFormat, args...) < 0) {
203 return EMPTY_STRING;
204 }
205
206 // make a string return
207 return std::string(bytes);
208 }
209
210 // path check
211 std::vector<std::string> GetEntriesInDir(const std::string &basePath);
212
213 std::vector<std::string> GetSubDirs(const std::string &basePath);
214
215 bool IsDir(const std::string &path);
216
217 bool IsPath(const std::string &fileName);
218
219 #if is_mingw
220 const char PATH_SEPARATOR = '\\';
221 #else
222 const char PATH_SEPARATOR = '/';
223 #endif
224 const std::string PATH_SEPARATOR_STR = std::string(1, PATH_SEPARATOR);
225
226 std::string PlatformPathConvert(const std::string &path);
227
228 // attribute
229 #define PACKED __attribute__((packed))
230
231 // data align
232
233 // some time u will meet signal 7 (SIGBUS), code 1 (BUS_ADRALN) in 32 or 64 arch cpu
234 #define HIPERF_BUF_ALIGN alignas(64)
235
236 uint32_t RoundUp(uint32_t x, const int align);
237
238 // data convert funcion
239 template<class T>
240 std::string ToHex(const T &source, int size = sizeof(T), bool perfix = false)
241 {
242 std::stringstream ss;
243 if (perfix) {
244 ss << "0x";
245 }
246 ss << std::hex << std::setw(BYTE_PRINT_WIDTH * size) << std::setfill('0') << (uint64_t)source;
247 return ss.str();
248 }
249
250 // data move and copy
251 template<class S, class T>
252 size_t inline CopyFromBufferAndMove(S *&buffer, T *dest, size_t size = 0)
253 {
254 if (size == 0) {
255 size = sizeof(T);
256 }
257 if (memcpy_s(dest, size, buffer, size) != EOK) {
258 return size;
259 }
260 buffer = buffer + size;
261 return size;
262 }
263
264 // file read write
265 bool ReadIntFromProcFile(const std::string &path, int &value);
266 bool WriteIntToProcFile(const std::string &path, int value);
267 std::string ReadFileToString(const std::string &fileName);
268 bool ReadFileToString(const std::string &fileName, std::string &content, size_t fileSize = 0);
269 bool WriteStringToFile(const std::string &fileName, const std::string &value);
270
271 // stdout
272 class StdoutRecord {
273 public:
~StdoutRecord()274 ~StdoutRecord()
275 {
276 Stop(); // stdout need restore
277 }
278 StdoutRecord(const std::string &tempFile = EMPTY_STRING,
279 const std::string &mode = EMPTY_STRING);
280
281 bool Start();
282 std::string Stop();
283
284 private:
285 OHOS::UniqueFd stdoutFile_; // back and restore stdout
286 std::FILE *recordFile_ = nullptr; // save the output
287 bool stop_ = true;
288 std::string content_ = EMPTY_STRING;
289 };
290
291 // misc
292 template<class T>
Percentage(const T & a,const T & b)293 float Percentage(const T &a, const T &b)
294 {
295 return static_cast<float>(a) / static_cast<float>(b) * FULL_PERCENTAGE;
296 }
297
298 bool IsRoot();
299 bool PowerOfTwo(int n);
300
301 #define INDENT_ONE_LEVEL (indent + 1)
302 #define INDENT_TWO_LEVEL (indent + 2)
303
304 #define PrintIndent(indent, format, ...) \
305 if (indent >= 0) { \
306 printf("%*s" format, (indent)*2, "", ##__VA_ARGS__); \
307 } else { \
308 HLOGV("%s" format, "", ##__VA_ARGS__); \
309 }
310
311 #ifndef MMAP_FAILED
312 #define MMAP_FAILED (reinterpret_cast<void *>(-1))
313 #endif
314 #ifndef MAP_FAILED
315 #define MAP_FAILED MMAP_FAILED
316 #endif
317 int32_t GetProcessPid(const std::string& processName);
318 } // namespace NativeDaemon
319 } // namespace Developtools
320 } // namespace OHOS
321
322 // this will also used for libunwind head (out of namespace)
323 #if is_mingw
324 #define HAVE_MMAP 1
325 #define MAP_PRIVATE 0x02
326 #define PROT_NONE 0
327 #define PROT_READ 1
328 #define PROT_WRITE 2
329 #define PROT_EXEC 4
330 void *mmap(void *addr, size_t length, int prot, int flags, int fd, size_t offset);
331 int munmap(void *addr, size_t);
332 #endif
333
334 #endif
335