2 * Copyright (C) 2015 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
32 #include <android-base/file.h>
33 #include <android-base/logging.h>
39 void OneTimeFreeAllocator::Clear() {
48 const char* OneTimeFreeAllocator::AllocateString(const std::string& s) {
49 size_t size = s.size() + 1;
50 if (cur_ + size > end_) {
51 size_t alloc_size = std::max(size, unit_size_);
52 char* p = new char[alloc_size];
55 end_ = p + alloc_size;
57 strcpy(cur_, s.c_str());
58 const char* result = cur_;
64 FileHelper FileHelper::OpenReadOnly(const std::string& filename) {
65 int fd = TEMP_FAILURE_RETRY(open(filename.c_str(), O_RDONLY | O_BINARY));
66 return FileHelper(fd);
69 FileHelper FileHelper::OpenWriteOnly(const std::string& filename) {
70 int fd = TEMP_FAILURE_RETRY(open(filename.c_str(), O_WRONLY | O_BINARY | O_CREAT, 0644));
71 return FileHelper(fd);
74 FileHelper::~FileHelper() {
80 ArchiveHelper::ArchiveHelper(int fd, const std::string& debug_filename) : valid_(false) {
81 int rc = OpenArchiveFd(fd, "", &handle_, false);
85 LOG(ERROR) << "Failed to open archive " << debug_filename << ": " << ErrorCodeString(rc);
89 ArchiveHelper::~ArchiveHelper() {
91 CloseArchive(handle_);
95 void PrintIndented(size_t indent, const char* fmt, ...) {
98 printf("%*s", static_cast<int>(indent * 2), "");
103 void FprintIndented(FILE* fp, size_t indent, const char* fmt, ...) {
106 fprintf(fp, "%*s", static_cast<int>(indent * 2), "");
107 vfprintf(fp, fmt, ap);
111 bool IsPowerOfTwo(uint64_t value) {
112 return (value != 0 && ((value & (value - 1)) == 0));
115 std::vector<std::string> GetEntriesInDir(const std::string& dirpath) {
116 std::vector<std::string> result;
117 DIR* dir = opendir(dirpath.c_str());
118 if (dir == nullptr) {
119 PLOG(DEBUG) << "can't open dir " << dirpath;
123 while ((entry = readdir(dir)) != nullptr) {
124 if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
127 result.push_back(entry->d_name);
133 std::vector<std::string> GetSubDirs(const std::string& dirpath) {
134 std::vector<std::string> entries = GetEntriesInDir(dirpath);
135 std::vector<std::string> result;
136 for (size_t i = 0; i < entries.size(); ++i) {
137 if (IsDir(dirpath + "/" + entries[i])) {
138 result.push_back(std::move(entries[i]));
144 bool IsDir(const std::string& dirpath) {
146 if (stat(dirpath.c_str(), &st) == 0) {
147 if (S_ISDIR(st.st_mode)) {
154 bool IsRegularFile(const std::string& filename) {
156 if (stat(filename.c_str(), &st) == 0) {
157 if (S_ISREG(st.st_mode)) {
164 uint64_t GetFileSize(const std::string& filename) {
166 if (stat(filename.c_str(), &st) == 0) {
167 return static_cast<uint64_t>(st.st_size);
172 bool MkdirWithParents(const std::string& path) {
174 while (prev_end < path.size()) {
175 size_t next_end = path.find('/', prev_end + 1);
176 if (next_end == std::string::npos) {
179 std::string dir_path = path.substr(0, next_end);
180 if (!IsDir(dir_path)) {
182 int ret = mkdir(dir_path.c_str());
184 int ret = mkdir(dir_path.c_str(), 0755);
187 PLOG(ERROR) << "failed to create dir " << dir_path;
196 static void* xz_alloc(void*, size_t size) {
200 static void xz_free(void*, void* address) {
204 bool XzDecompress(const std::string& compressed_data, std::string* decompressed_data) {
207 alloc.Alloc = xz_alloc;
208 alloc.Free = xz_free;
209 XzUnpacker_Construct(&state, &alloc);
211 Crc64GenerateTable();
212 size_t src_offset = 0;
213 size_t dst_offset = 0;
214 std::string dst(compressed_data.size(), ' ');
216 ECoderStatus status = CODER_STATUS_NOT_FINISHED;
217 while (status == CODER_STATUS_NOT_FINISHED) {
218 dst.resize(dst.size() * 2);
219 size_t src_remaining = compressed_data.size() - src_offset;
220 size_t dst_remaining = dst.size() - dst_offset;
221 int res = XzUnpacker_Code(&state, reinterpret_cast<Byte*>(&dst[dst_offset]), &dst_remaining,
222 reinterpret_cast<const Byte*>(&compressed_data[src_offset]),
223 &src_remaining, CODER_FINISH_ANY, &status);
225 LOG(ERROR) << "LZMA decompression failed with error " << res;
226 XzUnpacker_Free(&state);
229 src_offset += src_remaining;
230 dst_offset += dst_remaining;
232 XzUnpacker_Free(&state);
233 if (!XzUnpacker_IsStreamWasFinished(&state)) {
234 LOG(ERROR) << "LZMA decompresstion failed due to incomplete stream";
237 dst.resize(dst_offset);
238 *decompressed_data = std::move(dst);
242 bool GetLogSeverity(const std::string& name, android::base::LogSeverity* severity) {
243 static std::map<std::string, android::base::LogSeverity> log_severity_map = {
244 {"verbose", android::base::VERBOSE},
245 {"debug", android::base::DEBUG},
246 {"info", android::base::INFO},
247 {"warning", android::base::WARNING},
248 {"error", android::base::ERROR},
249 {"fatal", android::base::FATAL},
251 auto it = log_severity_map.find(name);
252 if (it != log_severity_map.end()) {
253 *severity = it->second;
260 static int is_root = -1;
262 #if defined(__linux__)
263 is_root = (getuid() == 0) ? 1 : 0;
271 bool ProcessKernelSymbols(std::string& symbol_data,
272 const std::function<bool(const KernelSymbol&)>& callback) {
273 char* p = &symbol_data[0];
274 char* data_end = p + symbol_data.size();
275 while (p < data_end) {
276 char* line_end = strchr(p, '\n');
277 if (line_end != nullptr) {
280 size_t line_size = (line_end != nullptr) ? (line_end - p) : (data_end - p);
281 // Parse line like: ffffffffa005c4e4 d __warned.41698 [libsas]
282 char name[line_size];
283 char module[line_size];
287 int ret = sscanf(p, "%" PRIx64 " %c %s%s", &symbol.addr, &symbol.type, name, module);
288 if (line_end != nullptr) {
296 size_t module_len = strlen(module);
297 if (module_len > 2 && module[0] == '[' && module[module_len - 1] == ']') {
298 module[module_len - 1] = '\0';
299 symbol.module = &module[1];
301 symbol.module = nullptr;
304 if (callback(symbol)) {
312 size_t GetPageSize() {
313 #if defined(__linux__)
314 return sysconf(_SC_PAGE_SIZE);
320 uint64_t ConvertBytesToValue(const char* bytes, uint32_t size) {
322 LOG(FATAL) << "unexpected size " << size << " in ConvertBytesToValue";
326 for (uint32_t i = 0; i < size; ++i) {
327 uint64_t tmp = static_cast<unsigned char>(bytes[i]);
328 result |= tmp << shift;
334 timeval SecondToTimeval(double time_in_sec) {
336 tv.tv_sec = static_cast<time_t>(time_in_sec);
337 tv.tv_usec = static_cast<int>((time_in_sec - tv.tv_sec) * 1000000);