blob: a041816723c605df39f81054af3bcd6ecf6d7ed4 [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 Cuie3ca9982020-10-16 13:16:26 -070034#include <android-base/parseint.h>
Yabin Cuidf6333c2017-05-03 16:34:02 -070035#include <android-base/stringprintf.h>
Yabin Cuie3ca9982020-10-16 13:16:26 -070036#include <android-base/strings.h>
Yabin Cui4192f462019-01-17 15:10:51 -080037#include <build/version.h>
Yabin Cui67d3abd2015-04-16 15:26:31 -070038
Yabin Cui05400532016-03-17 21:18:53 -070039#include <7zCrc.h>
40#include <Xz.h>
41#include <XzCrc64.h>
42
Yabin Cuifaa7b922021-01-11 17:35:57 -080043namespace simpleperf {
44
Yabin Cuie3ca9982020-10-16 13:16:26 -070045using android::base::ParseInt;
46using android::base::Split;
47using android::base::StringPrintf;
48
Yabin Cuicc2e59e2015-08-21 14:23:43 -070049void OneTimeFreeAllocator::Clear() {
50 for (auto& p : v_) {
51 delete[] p;
52 }
53 v_.clear();
54 cur_ = nullptr;
55 end_ = nullptr;
56}
57
Martin Stjernholm7c27cc22018-11-28 00:46:00 +000058const char* OneTimeFreeAllocator::AllocateString(std::string_view s) {
Yabin Cuicc2e59e2015-08-21 14:23:43 -070059 size_t size = s.size() + 1;
60 if (cur_ + size > end_) {
61 size_t alloc_size = std::max(size, unit_size_);
62 char* p = new char[alloc_size];
63 v_.push_back(p);
64 cur_ = p;
65 end_ = p + alloc_size;
66 }
Evgeny Eltsin2c4fbfe2020-08-26 15:01:40 +020067 memcpy(cur_, s.data(), s.size());
68 cur_[s.size()] = '\0';
Yabin Cuicc2e59e2015-08-21 14:23:43 -070069 const char* result = cur_;
70 cur_ += size;
71 return result;
72}
73
Yabin Cui2a53ff32018-05-21 17:37:00 -070074android::base::unique_fd FileHelper::OpenReadOnly(const std::string& filename) {
Thiébaud Weksteen4848ee02020-10-23 16:06:59 +020075 int fd = TEMP_FAILURE_RETRY(open(filename.c_str(), O_RDONLY | O_BINARY));
76 return android::base::unique_fd(fd);
Yabin Cuib1a885b2016-02-14 19:18:02 -080077}
78
Yabin Cui2a53ff32018-05-21 17:37:00 -070079android::base::unique_fd FileHelper::OpenWriteOnly(const std::string& filename) {
Thiébaud Weksteen4848ee02020-10-23 16:06:59 +020080 int fd = TEMP_FAILURE_RETRY(open(filename.c_str(), O_WRONLY | O_BINARY | O_CREAT, 0644));
81 return android::base::unique_fd(fd);
Yabin Cuib1a885b2016-02-14 19:18:02 -080082}
83
Yabin Cui2a53ff32018-05-21 17:37:00 -070084std::unique_ptr<ArchiveHelper> ArchiveHelper::CreateInstance(const std::string& filename) {
85 android::base::unique_fd fd = FileHelper::OpenReadOnly(filename);
86 if (fd == -1) {
87 return nullptr;
Yabin Cuib1a885b2016-02-14 19:18:02 -080088 }
Yabin Cui2a53ff32018-05-21 17:37:00 -070089 // Simpleperf relies on ArchiveHelper to check if a file is zip file. We expect much more elf
90 // files than zip files in a process map. In order to detect invalid zip files fast, we add a
91 // check of magic number here. Note that OpenArchiveFd() detects invalid zip files in a thorough
92 // way, but it usually needs reading at least 64K file data.
Thiébaud Weksteen4848ee02020-10-23 16:06:59 +020093 static const char zip_preamble[] = {0x50, 0x4b, 0x03, 0x04};
Yabin Cui2a53ff32018-05-21 17:37:00 -070094 char buf[4];
95 if (!android::base::ReadFully(fd, buf, 4) || memcmp(buf, zip_preamble, 4) != 0) {
96 return nullptr;
Yabin Cuibe7ec662016-03-02 13:56:28 -080097 }
Yabin Cui2a53ff32018-05-21 17:37:00 -070098 if (lseek(fd, 0, SEEK_SET) == -1) {
99 return nullptr;
100 }
101 ZipArchiveHandle handle;
102 int result = OpenArchiveFd(fd.release(), filename.c_str(), &handle);
103 if (result != 0) {
104 LOG(ERROR) << "Failed to open archive " << filename << ": " << ErrorCodeString(result);
105 return nullptr;
106 }
107 return std::unique_ptr<ArchiveHelper>(new ArchiveHelper(handle, filename));
Yabin Cuibe7ec662016-03-02 13:56:28 -0800108}
109
110ArchiveHelper::~ArchiveHelper() {
Yabin Cui2a53ff32018-05-21 17:37:00 -0700111 CloseArchive(handle_);
112}
113
114bool ArchiveHelper::IterateEntries(
115 const std::function<bool(ZipEntry&, const std::string&)>& callback) {
116 void* iteration_cookie;
Elliott Hughesb389bd72019-05-07 14:57:35 -0700117 if (StartIteration(handle_, &iteration_cookie) < 0) {
Yabin Cui2a53ff32018-05-21 17:37:00 -0700118 LOG(ERROR) << "Failed to iterate " << filename_;
119 return false;
Yabin Cuibe7ec662016-03-02 13:56:28 -0800120 }
Yabin Cui2a53ff32018-05-21 17:37:00 -0700121 ZipEntry zentry;
Elliott Hughes6975eeb2019-05-22 18:59:29 -0700122 std::string zname;
Yabin Cui2a53ff32018-05-21 17:37:00 -0700123 int result;
124 while ((result = Next(iteration_cookie, &zentry, &zname)) == 0) {
Elliott Hughes6975eeb2019-05-22 18:59:29 -0700125 if (!callback(zentry, zname)) {
Yabin Cui2a53ff32018-05-21 17:37:00 -0700126 break;
127 }
128 }
129 EndIteration(iteration_cookie);
130 if (result == -2) {
131 LOG(ERROR) << "Failed to iterate " << filename_;
132 return false;
133 }
134 return true;
135}
136
137bool ArchiveHelper::FindEntry(const std::string& name, ZipEntry* entry) {
Elliott Hughes32885662019-05-03 22:37:19 -0700138 int result = ::FindEntry(handle_, name, entry);
Yabin Cui2a53ff32018-05-21 17:37:00 -0700139 if (result != 0) {
140 LOG(ERROR) << "Failed to find " << name << " in " << filename_;
141 return false;
142 }
143 return true;
144}
145
146bool ArchiveHelper::GetEntryData(ZipEntry& entry, std::vector<uint8_t>* data) {
147 data->resize(entry.uncompressed_length);
148 if (ExtractToMemory(handle_, &entry, data->data(), data->size()) != 0) {
149 LOG(ERROR) << "Failed to extract entry at " << entry.offset << " in " << filename_;
150 return false;
151 }
152 return true;
153}
154
155int ArchiveHelper::GetFd() {
156 return GetFileDescriptor(handle_);
Yabin Cuibe7ec662016-03-02 13:56:28 -0800157}
158
Yabin Cui67d3abd2015-04-16 15:26:31 -0700159void PrintIndented(size_t indent, const char* fmt, ...) {
160 va_list ap;
161 va_start(ap, fmt);
Yabin Cui9759e1b2015-04-28 15:54:13 -0700162 printf("%*s", static_cast<int>(indent * 2), "");
Yabin Cui67d3abd2015-04-16 15:26:31 -0700163 vprintf(fmt, ap);
164 va_end(ap);
165}
Yabin Cui323e9452015-04-20 18:07:17 -0700166
Yabin Cui767dd172016-06-02 21:02:43 -0700167void FprintIndented(FILE* fp, size_t indent, const char* fmt, ...) {
168 va_list ap;
169 va_start(ap, fmt);
170 fprintf(fp, "%*s", static_cast<int>(indent * 2), "");
171 vfprintf(fp, fmt, ap);
172 va_end(ap);
173}
174
Yabin Cui9759e1b2015-04-28 15:54:13 -0700175bool IsPowerOfTwo(uint64_t value) {
176 return (value != 0 && ((value & (value - 1)) == 0));
177}
178
Yabin Cui07865862016-08-22 13:39:19 -0700179std::vector<std::string> GetEntriesInDir(const std::string& dirpath) {
180 std::vector<std::string> result;
Yabin Cui7d59bb42015-05-04 20:27:57 -0700181 DIR* dir = opendir(dirpath.c_str());
182 if (dir == nullptr) {
183 PLOG(DEBUG) << "can't open dir " << dirpath;
Yabin Cui07865862016-08-22 13:39:19 -0700184 return result;
Yabin Cui7d59bb42015-05-04 20:27:57 -0700185 }
186 dirent* entry;
187 while ((entry = readdir(dir)) != nullptr) {
188 if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
189 continue;
190 }
Yabin Cui07865862016-08-22 13:39:19 -0700191 result.push_back(entry->d_name);
Yabin Cui7d59bb42015-05-04 20:27:57 -0700192 }
193 closedir(dir);
Yabin Cui07865862016-08-22 13:39:19 -0700194 return result;
195}
196
197std::vector<std::string> GetSubDirs(const std::string& dirpath) {
198 std::vector<std::string> entries = GetEntriesInDir(dirpath);
199 std::vector<std::string> result;
200 for (size_t i = 0; i < entries.size(); ++i) {
Yabin Cui1b9b1c12018-10-29 14:23:48 -0700201 if (IsDir(dirpath + OS_PATH_SEPARATOR + entries[i])) {
Yabin Cui07865862016-08-22 13:39:19 -0700202 result.push_back(std::move(entries[i]));
203 }
204 }
205 return result;
Yabin Cui7d59bb42015-05-04 20:27:57 -0700206}
Yabin Cui6afc7e12015-06-17 22:21:12 -0700207
Yabin Cuib032de72015-06-17 21:15:09 -0700208bool IsDir(const std::string& dirpath) {
209 struct stat st;
210 if (stat(dirpath.c_str(), &st) == 0) {
211 if (S_ISDIR(st.st_mode)) {
212 return true;
213 }
214 }
215 return false;
216}
217
Yabin Cui797116b2015-12-08 17:43:15 -0800218bool IsRegularFile(const std::string& filename) {
219 struct stat st;
220 if (stat(filename.c_str(), &st) == 0) {
221 if (S_ISREG(st.st_mode)) {
222 return true;
223 }
224 }
225 return false;
226}
Yabin Cuib1a885b2016-02-14 19:18:02 -0800227
228uint64_t GetFileSize(const std::string& filename) {
229 struct stat st;
230 if (stat(filename.c_str(), &st) == 0) {
231 return static_cast<uint64_t>(st.st_size);
232 }
233 return 0;
234}
Yabin Cuibe7ec662016-03-02 13:56:28 -0800235
236bool MkdirWithParents(const std::string& path) {
237 size_t prev_end = 0;
238 while (prev_end < path.size()) {
239 size_t next_end = path.find('/', prev_end + 1);
240 if (next_end == std::string::npos) {
241 break;
242 }
243 std::string dir_path = path.substr(0, next_end);
244 if (!IsDir(dir_path)) {
245#if defined(_WIN32)
246 int ret = mkdir(dir_path.c_str());
247#else
248 int ret = mkdir(dir_path.c_str(), 0755);
249#endif
250 if (ret != 0) {
251 PLOG(ERROR) << "failed to create dir " << dir_path;
252 return false;
253 }
254 }
255 prev_end = next_end;
256 }
257 return true;
258}
Yabin Cui05400532016-03-17 21:18:53 -0700259
Sen Jiangea853b12018-05-04 13:25:02 -0700260static void* xz_alloc(ISzAllocPtr, size_t size) {
Yabin Cui05400532016-03-17 21:18:53 -0700261 return malloc(size);
262}
263
Sen Jiangea853b12018-05-04 13:25:02 -0700264static void xz_free(ISzAllocPtr, void* address) {
Yabin Cui05400532016-03-17 21:18:53 -0700265 free(address);
266}
267
268bool XzDecompress(const std::string& compressed_data, std::string* decompressed_data) {
269 ISzAlloc alloc;
270 CXzUnpacker state;
271 alloc.Alloc = xz_alloc;
272 alloc.Free = xz_free;
273 XzUnpacker_Construct(&state, &alloc);
274 CrcGenerateTable();
275 Crc64GenerateTable();
276 size_t src_offset = 0;
277 size_t dst_offset = 0;
278 std::string dst(compressed_data.size(), ' ');
279
280 ECoderStatus status = CODER_STATUS_NOT_FINISHED;
281 while (status == CODER_STATUS_NOT_FINISHED) {
282 dst.resize(dst.size() * 2);
283 size_t src_remaining = compressed_data.size() - src_offset;
284 size_t dst_remaining = dst.size() - dst_offset;
285 int res = XzUnpacker_Code(&state, reinterpret_cast<Byte*>(&dst[dst_offset]), &dst_remaining,
286 reinterpret_cast<const Byte*>(&compressed_data[src_offset]),
Sen Jiangea853b12018-05-04 13:25:02 -0700287 &src_remaining, true, CODER_FINISH_ANY, &status);
Yabin Cui05400532016-03-17 21:18:53 -0700288 if (res != SZ_OK) {
289 LOG(ERROR) << "LZMA decompression failed with error " << res;
290 XzUnpacker_Free(&state);
291 return false;
292 }
293 src_offset += src_remaining;
294 dst_offset += dst_remaining;
295 }
296 XzUnpacker_Free(&state);
297 if (!XzUnpacker_IsStreamWasFinished(&state)) {
298 LOG(ERROR) << "LZMA decompresstion failed due to incomplete stream";
299 return false;
300 }
301 dst.resize(dst_offset);
302 *decompressed_data = std::move(dst);
303 return true;
304}
Yabin Cui8f680f62016-03-18 18:47:43 -0700305
Yabin Cui750b3732017-12-18 17:46:36 -0800306static std::map<std::string, android::base::LogSeverity> log_severity_map = {
Thiébaud Weksteen4848ee02020-10-23 16:06:59 +0200307 {"verbose", android::base::VERBOSE}, {"debug", android::base::DEBUG},
308 {"info", android::base::INFO}, {"warning", android::base::WARNING},
309 {"error", android::base::ERROR}, {"fatal", android::base::FATAL},
Yabin Cui750b3732017-12-18 17:46:36 -0800310};
Yabin Cui8f680f62016-03-18 18:47:43 -0700311bool GetLogSeverity(const std::string& name, android::base::LogSeverity* severity) {
Yabin Cui8f680f62016-03-18 18:47:43 -0700312 auto it = log_severity_map.find(name);
313 if (it != log_severity_map.end()) {
314 *severity = it->second;
315 return true;
316 }
317 return false;
318}
Yabin Cui56335862016-04-18 13:43:20 -0700319
Yabin Cui750b3732017-12-18 17:46:36 -0800320std::string GetLogSeverityName() {
321 android::base::LogSeverity severity = android::base::GetMinimumLogSeverity();
322 for (auto& pair : log_severity_map) {
323 if (severity == pair.second) {
324 return pair.first;
325 }
326 }
327 return "info";
328}
329
Yabin Cui56335862016-04-18 13:43:20 -0700330bool IsRoot() {
331 static int is_root = -1;
332 if (is_root == -1) {
333#if defined(__linux__)
334 is_root = (getuid() == 0) ? 1 : 0;
335#else
336 is_root = 0;
337#endif
338 }
339 return is_root == 1;
340}
Yabin Cuib4212972016-05-25 14:08:05 -0700341
Yabin Cui4f41df62016-06-01 17:29:06 -0700342size_t GetPageSize() {
343#if defined(__linux__)
344 return sysconf(_SC_PAGE_SIZE);
345#else
346 return 4096;
347#endif
348}
349
350uint64_t ConvertBytesToValue(const char* bytes, uint32_t size) {
Yabin Cuif79a0082016-11-14 11:23:14 -0800351 if (size > 8) {
352 LOG(FATAL) << "unexpected size " << size << " in ConvertBytesToValue";
Yabin Cui4f41df62016-06-01 17:29:06 -0700353 }
Yabin Cuif79a0082016-11-14 11:23:14 -0800354 uint64_t result = 0;
355 int shift = 0;
356 for (uint32_t i = 0; i < size; ++i) {
357 uint64_t tmp = static_cast<unsigned char>(bytes[i]);
358 result |= tmp << shift;
359 shift += 8;
360 }
361 return result;
Yabin Cui4f41df62016-06-01 17:29:06 -0700362}
Yabin Cui3e4c5952016-07-26 15:03:27 -0700363
364timeval SecondToTimeval(double time_in_sec) {
365 timeval tv;
366 tv.tv_sec = static_cast<time_t>(time_in_sec);
367 tv.tv_usec = static_cast<int>((time_in_sec - tv.tv_sec) * 1000000);
368 return tv;
369}
Yabin Cuidf6333c2017-05-03 16:34:02 -0700370
371constexpr int SIMPLEPERF_VERSION = 1;
372
373std::string GetSimpleperfVersion() {
Yabin Cuie3ca9982020-10-16 13:16:26 -0700374 return StringPrintf("%d.build.%s", SIMPLEPERF_VERSION, android::build::GetBuildNumber().c_str());
Yabin Cuidf6333c2017-05-03 16:34:02 -0700375}
Namhyung Kima5f1d422019-12-17 17:15:02 +0900376
Yabin Cuie3ca9982020-10-16 13:16:26 -0700377// Parse a line like: 0,1-3, 5, 7-8
378std::optional<std::set<int>> GetCpusFromString(const std::string& s) {
379 std::string str;
380 for (char c : s) {
381 if (!isspace(c)) {
382 str += c;
Namhyung Kima5f1d422019-12-17 17:15:02 +0900383 }
384 }
Yabin Cuie3ca9982020-10-16 13:16:26 -0700385 std::set<int> cpus;
386 int cpu1;
387 int cpu2;
388 for (const std::string& p : Split(str, ",")) {
389 size_t split_pos = p.find('-');
390 if (split_pos == std::string::npos) {
391 if (!ParseInt(p, &cpu1, 0)) {
392 LOG(ERROR) << "failed to parse cpu: " << p;
393 return std::nullopt;
394 }
395 cpus.insert(cpu1);
396 } else {
397 if (!ParseInt(p.substr(0, split_pos), &cpu1, 0) ||
398 !ParseInt(p.substr(split_pos + 1), &cpu2, 0) || cpu1 > cpu2) {
399 LOG(ERROR) << "failed to parse cpu: " << p;
400 return std::nullopt;
401 }
402 while (cpu1 <= cpu2) {
403 cpus.insert(cpu1++);
404 }
405 }
406 }
407 return cpus;
408}
409
410std::optional<std::set<pid_t>> GetTidsFromString(const std::string& s, bool check_if_exists) {
411 std::set<pid_t> tids;
412 for (const auto& p : Split(s, ",")) {
413 int tid;
414 if (!ParseInt(p.c_str(), &tid, 0)) {
415 LOG(ERROR) << "Invalid tid '" << p << "'";
416 return std::nullopt;
417 }
418 if (check_if_exists && !IsDir(StringPrintf("/proc/%d", tid))) {
419 LOG(ERROR) << "Non existing thread '" << tid << "'";
420 return std::nullopt;
421 }
422 tids.insert(tid);
423 }
424 return tids;
Namhyung Kima5f1d422019-12-17 17:15:02 +0900425}
Yabin Cuifaa7b922021-01-11 17:35:57 -0800426
Yabin Cui1cb85802021-11-12 17:56:57 -0800427size_t SafeStrlen(const char* s, const char* end) {
428 const char* p = s;
429 while (p < end && *p != '\0') {
430 p++;
431 }
432 return p - s;
433}
434
Yabin Cuifaa7b922021-01-11 17:35:57 -0800435} // namespace simpleperf