blob: 1dbe078e36f331d2727e0264bca7165eb7f00dbb [file] [log] [blame]
Yabin Cui67d3abd2015-04-16 15:26:31 -07001/*
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#include "utils.h"
18
Yabin Cui7d59bb42015-05-04 20:27:57 -070019#include <dirent.h>
Yabin Cui323e9452015-04-20 18:07:17 -070020#include <errno.h>
Yabin Cuib1a885b2016-02-14 19:18:02 -080021#include <fcntl.h>
Yabin Cuib4212972016-05-25 14:08:05 -070022#include <inttypes.h>
Yabin Cui67d3abd2015-04-16 15:26:31 -070023#include <stdarg.h>
24#include <stdio.h>
Yabin Cui6afc7e12015-06-17 22:21:12 -070025#include <sys/stat.h>
Yabin Cui323e9452015-04-20 18:07:17 -070026#include <unistd.h>
27
Yabin Cuicc2e59e2015-08-21 14:23:43 -070028#include <algorithm>
Yabin Cui8f680f62016-03-18 18:47:43 -070029#include <map>
Yabin Cuicc2e59e2015-08-21 14:23:43 -070030#include <string>
31
Yabin Cuib1a885b2016-02-14 19:18:02 -080032#include <android-base/file.h>
Elliott Hughes66dd09e2015-12-04 14:00:57 -080033#include <android-base/logging.h>
Yabin Cuidf6333c2017-05-03 16:34:02 -070034#include <android-base/stringprintf.h>
Yabin Cui67d3abd2015-04-16 15:26:31 -070035
Yabin Cui05400532016-03-17 21:18:53 -070036#include <7zCrc.h>
37#include <Xz.h>
38#include <XzCrc64.h>
39
Yabin Cuicc2e59e2015-08-21 14:23:43 -070040void OneTimeFreeAllocator::Clear() {
41 for (auto& p : v_) {
42 delete[] p;
43 }
44 v_.clear();
45 cur_ = nullptr;
46 end_ = nullptr;
47}
48
49const char* OneTimeFreeAllocator::AllocateString(const std::string& s) {
50 size_t size = s.size() + 1;
51 if (cur_ + size > end_) {
52 size_t alloc_size = std::max(size, unit_size_);
53 char* p = new char[alloc_size];
54 v_.push_back(p);
55 cur_ = p;
56 end_ = p + alloc_size;
57 }
58 strcpy(cur_, s.c_str());
59 const char* result = cur_;
60 cur_ += size;
61 return result;
62}
63
Yabin Cuibe7ec662016-03-02 13:56:28 -080064
65FileHelper FileHelper::OpenReadOnly(const std::string& filename) {
66 int fd = TEMP_FAILURE_RETRY(open(filename.c_str(), O_RDONLY | O_BINARY));
67 return FileHelper(fd);
Yabin Cuib1a885b2016-02-14 19:18:02 -080068}
69
Yabin Cuibe7ec662016-03-02 13:56:28 -080070FileHelper FileHelper::OpenWriteOnly(const std::string& filename) {
71 int fd = TEMP_FAILURE_RETRY(open(filename.c_str(), O_WRONLY | O_BINARY | O_CREAT, 0644));
72 return FileHelper(fd);
Yabin Cuib1a885b2016-02-14 19:18:02 -080073}
74
75FileHelper::~FileHelper() {
76 if (fd_ != -1) {
77 close(fd_);
78 }
79}
80
Yabin Cuibe7ec662016-03-02 13:56:28 -080081ArchiveHelper::ArchiveHelper(int fd, const std::string& debug_filename) : valid_(false) {
82 int rc = OpenArchiveFd(fd, "", &handle_, false);
83 if (rc == 0) {
84 valid_ = true;
85 } else {
86 LOG(ERROR) << "Failed to open archive " << debug_filename << ": " << ErrorCodeString(rc);
87 }
88}
89
90ArchiveHelper::~ArchiveHelper() {
91 if (valid_) {
92 CloseArchive(handle_);
93 }
94}
95
Yabin Cui67d3abd2015-04-16 15:26:31 -070096void PrintIndented(size_t indent, const char* fmt, ...) {
97 va_list ap;
98 va_start(ap, fmt);
Yabin Cui9759e1b2015-04-28 15:54:13 -070099 printf("%*s", static_cast<int>(indent * 2), "");
Yabin Cui67d3abd2015-04-16 15:26:31 -0700100 vprintf(fmt, ap);
101 va_end(ap);
102}
Yabin Cui323e9452015-04-20 18:07:17 -0700103
Yabin Cui767dd172016-06-02 21:02:43 -0700104void FprintIndented(FILE* fp, size_t indent, const char* fmt, ...) {
105 va_list ap;
106 va_start(ap, fmt);
107 fprintf(fp, "%*s", static_cast<int>(indent * 2), "");
108 vfprintf(fp, fmt, ap);
109 va_end(ap);
110}
111
Yabin Cui9759e1b2015-04-28 15:54:13 -0700112bool IsPowerOfTwo(uint64_t value) {
113 return (value != 0 && ((value & (value - 1)) == 0));
114}
115
Yabin Cui07865862016-08-22 13:39:19 -0700116std::vector<std::string> GetEntriesInDir(const std::string& dirpath) {
117 std::vector<std::string> result;
Yabin Cui7d59bb42015-05-04 20:27:57 -0700118 DIR* dir = opendir(dirpath.c_str());
119 if (dir == nullptr) {
120 PLOG(DEBUG) << "can't open dir " << dirpath;
Yabin Cui07865862016-08-22 13:39:19 -0700121 return result;
Yabin Cui7d59bb42015-05-04 20:27:57 -0700122 }
123 dirent* entry;
124 while ((entry = readdir(dir)) != nullptr) {
125 if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
126 continue;
127 }
Yabin Cui07865862016-08-22 13:39:19 -0700128 result.push_back(entry->d_name);
Yabin Cui7d59bb42015-05-04 20:27:57 -0700129 }
130 closedir(dir);
Yabin Cui07865862016-08-22 13:39:19 -0700131 return result;
132}
133
134std::vector<std::string> GetSubDirs(const std::string& dirpath) {
135 std::vector<std::string> entries = GetEntriesInDir(dirpath);
136 std::vector<std::string> result;
137 for (size_t i = 0; i < entries.size(); ++i) {
138 if (IsDir(dirpath + "/" + entries[i])) {
139 result.push_back(std::move(entries[i]));
140 }
141 }
142 return result;
Yabin Cui7d59bb42015-05-04 20:27:57 -0700143}
Yabin Cui6afc7e12015-06-17 22:21:12 -0700144
Yabin Cuib032de72015-06-17 21:15:09 -0700145bool IsDir(const std::string& dirpath) {
146 struct stat st;
147 if (stat(dirpath.c_str(), &st) == 0) {
148 if (S_ISDIR(st.st_mode)) {
149 return true;
150 }
151 }
152 return false;
153}
154
Yabin Cui797116b2015-12-08 17:43:15 -0800155bool IsRegularFile(const std::string& filename) {
156 struct stat st;
157 if (stat(filename.c_str(), &st) == 0) {
158 if (S_ISREG(st.st_mode)) {
159 return true;
160 }
161 }
162 return false;
163}
Yabin Cuib1a885b2016-02-14 19:18:02 -0800164
165uint64_t GetFileSize(const std::string& filename) {
166 struct stat st;
167 if (stat(filename.c_str(), &st) == 0) {
168 return static_cast<uint64_t>(st.st_size);
169 }
170 return 0;
171}
Yabin Cuibe7ec662016-03-02 13:56:28 -0800172
173bool MkdirWithParents(const std::string& path) {
174 size_t prev_end = 0;
175 while (prev_end < path.size()) {
176 size_t next_end = path.find('/', prev_end + 1);
177 if (next_end == std::string::npos) {
178 break;
179 }
180 std::string dir_path = path.substr(0, next_end);
181 if (!IsDir(dir_path)) {
182#if defined(_WIN32)
183 int ret = mkdir(dir_path.c_str());
184#else
185 int ret = mkdir(dir_path.c_str(), 0755);
186#endif
187 if (ret != 0) {
188 PLOG(ERROR) << "failed to create dir " << dir_path;
189 return false;
190 }
191 }
192 prev_end = next_end;
193 }
194 return true;
195}
Yabin Cui05400532016-03-17 21:18:53 -0700196
197static void* xz_alloc(void*, size_t size) {
198 return malloc(size);
199}
200
201static void xz_free(void*, void* address) {
202 free(address);
203}
204
205bool XzDecompress(const std::string& compressed_data, std::string* decompressed_data) {
206 ISzAlloc alloc;
207 CXzUnpacker state;
208 alloc.Alloc = xz_alloc;
209 alloc.Free = xz_free;
210 XzUnpacker_Construct(&state, &alloc);
211 CrcGenerateTable();
212 Crc64GenerateTable();
213 size_t src_offset = 0;
214 size_t dst_offset = 0;
215 std::string dst(compressed_data.size(), ' ');
216
217 ECoderStatus status = CODER_STATUS_NOT_FINISHED;
218 while (status == CODER_STATUS_NOT_FINISHED) {
219 dst.resize(dst.size() * 2);
220 size_t src_remaining = compressed_data.size() - src_offset;
221 size_t dst_remaining = dst.size() - dst_offset;
222 int res = XzUnpacker_Code(&state, reinterpret_cast<Byte*>(&dst[dst_offset]), &dst_remaining,
223 reinterpret_cast<const Byte*>(&compressed_data[src_offset]),
224 &src_remaining, CODER_FINISH_ANY, &status);
225 if (res != SZ_OK) {
226 LOG(ERROR) << "LZMA decompression failed with error " << res;
227 XzUnpacker_Free(&state);
228 return false;
229 }
230 src_offset += src_remaining;
231 dst_offset += dst_remaining;
232 }
233 XzUnpacker_Free(&state);
234 if (!XzUnpacker_IsStreamWasFinished(&state)) {
235 LOG(ERROR) << "LZMA decompresstion failed due to incomplete stream";
236 return false;
237 }
238 dst.resize(dst_offset);
239 *decompressed_data = std::move(dst);
240 return true;
241}
Yabin Cui8f680f62016-03-18 18:47:43 -0700242
243bool GetLogSeverity(const std::string& name, android::base::LogSeverity* severity) {
244 static std::map<std::string, android::base::LogSeverity> log_severity_map = {
245 {"verbose", android::base::VERBOSE},
246 {"debug", android::base::DEBUG},
Yabin Cui767dd172016-06-02 21:02:43 -0700247 {"info", android::base::INFO},
Yabin Cui8f680f62016-03-18 18:47:43 -0700248 {"warning", android::base::WARNING},
249 {"error", android::base::ERROR},
250 {"fatal", android::base::FATAL},
251 };
252 auto it = log_severity_map.find(name);
253 if (it != log_severity_map.end()) {
254 *severity = it->second;
255 return true;
256 }
257 return false;
258}
Yabin Cui56335862016-04-18 13:43:20 -0700259
260bool IsRoot() {
261 static int is_root = -1;
262 if (is_root == -1) {
263#if defined(__linux__)
264 is_root = (getuid() == 0) ? 1 : 0;
265#else
266 is_root = 0;
267#endif
268 }
269 return is_root == 1;
270}
Yabin Cuib4212972016-05-25 14:08:05 -0700271
272bool ProcessKernelSymbols(std::string& symbol_data,
Yabin Cui3e4c5952016-07-26 15:03:27 -0700273 const std::function<bool(const KernelSymbol&)>& callback) {
Yabin Cuib4212972016-05-25 14:08:05 -0700274 char* p = &symbol_data[0];
275 char* data_end = p + symbol_data.size();
276 while (p < data_end) {
277 char* line_end = strchr(p, '\n');
278 if (line_end != nullptr) {
279 *line_end = '\0';
280 }
281 size_t line_size = (line_end != nullptr) ? (line_end - p) : (data_end - p);
282 // Parse line like: ffffffffa005c4e4 d __warned.41698 [libsas]
283 char name[line_size];
284 char module[line_size];
285 strcpy(module, "");
286
287 KernelSymbol symbol;
288 int ret = sscanf(p, "%" PRIx64 " %c %s%s", &symbol.addr, &symbol.type, name, module);
289 if (line_end != nullptr) {
290 *line_end = '\n';
291 p = line_end + 1;
292 } else {
293 p = data_end;
294 }
295 if (ret >= 3) {
296 symbol.name = name;
297 size_t module_len = strlen(module);
298 if (module_len > 2 && module[0] == '[' && module[module_len - 1] == ']') {
299 module[module_len - 1] = '\0';
300 symbol.module = &module[1];
301 } else {
302 symbol.module = nullptr;
303 }
304
305 if (callback(symbol)) {
306 return true;
307 }
308 }
309 }
310 return false;
311}
Yabin Cui4f41df62016-06-01 17:29:06 -0700312
313size_t GetPageSize() {
314#if defined(__linux__)
315 return sysconf(_SC_PAGE_SIZE);
316#else
317 return 4096;
318#endif
319}
320
321uint64_t ConvertBytesToValue(const char* bytes, uint32_t size) {
Yabin Cuif79a0082016-11-14 11:23:14 -0800322 if (size > 8) {
323 LOG(FATAL) << "unexpected size " << size << " in ConvertBytesToValue";
Yabin Cui4f41df62016-06-01 17:29:06 -0700324 }
Yabin Cuif79a0082016-11-14 11:23:14 -0800325 uint64_t result = 0;
326 int shift = 0;
327 for (uint32_t i = 0; i < size; ++i) {
328 uint64_t tmp = static_cast<unsigned char>(bytes[i]);
329 result |= tmp << shift;
330 shift += 8;
331 }
332 return result;
Yabin Cui4f41df62016-06-01 17:29:06 -0700333}
Yabin Cui3e4c5952016-07-26 15:03:27 -0700334
335timeval SecondToTimeval(double time_in_sec) {
336 timeval tv;
337 tv.tv_sec = static_cast<time_t>(time_in_sec);
338 tv.tv_usec = static_cast<int>((time_in_sec - tv.tv_sec) * 1000000);
339 return tv;
340}
Yabin Cuidf6333c2017-05-03 16:34:02 -0700341
342constexpr int SIMPLEPERF_VERSION = 1;
343
344std::string GetSimpleperfVersion() {
345 return android::base::StringPrintf("%d.%s", SIMPLEPERF_VERSION, SIMPLEPERF_REVISION);
346}