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