1 /*
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 
19 #include <dirent.h>
20 #include <errno.h>
21 #include <fcntl.h>
22 #include <inttypes.h>
23 #include <stdarg.h>
24 #include <stdio.h>
25 #include <sys/stat.h>
26 #include <unistd.h>
27 
28 #include <algorithm>
29 #include <map>
30 #include <string>
31 
32 #include <android-base/file.h>
33 #include <android-base/logging.h>
34 
35 #include <7zCrc.h>
36 #include <Xz.h>
37 #include <XzCrc64.h>
38 
Clear()39 void OneTimeFreeAllocator::Clear() {
40   for (auto& p : v_) {
41     delete[] p;
42   }
43   v_.clear();
44   cur_ = nullptr;
45   end_ = nullptr;
46 }
47 
AllocateString(const std::string & s)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];
53     v_.push_back(p);
54     cur_ = p;
55     end_ = p + alloc_size;
56   }
57   strcpy(cur_, s.c_str());
58   const char* result = cur_;
59   cur_ += size;
60   return result;
61 }
62 
63 
OpenReadOnly(const std::string & filename)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);
67 }
68 
OpenWriteOnly(const std::string & filename)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);
72 }
73 
~FileHelper()74 FileHelper::~FileHelper() {
75   if (fd_ != -1) {
76     close(fd_);
77   }
78 }
79 
ArchiveHelper(int fd,const std::string & debug_filename)80 ArchiveHelper::ArchiveHelper(int fd, const std::string& debug_filename) : valid_(false) {
81   int rc = OpenArchiveFd(fd, "", &handle_, false);
82   if (rc == 0) {
83     valid_ = true;
84   } else {
85     LOG(ERROR) << "Failed to open archive " << debug_filename << ": " << ErrorCodeString(rc);
86   }
87 }
88 
~ArchiveHelper()89 ArchiveHelper::~ArchiveHelper() {
90   if (valid_) {
91     CloseArchive(handle_);
92   }
93 }
94 
PrintIndented(size_t indent,const char * fmt,...)95 void PrintIndented(size_t indent, const char* fmt, ...) {
96   va_list ap;
97   va_start(ap, fmt);
98   printf("%*s", static_cast<int>(indent * 2), "");
99   vprintf(fmt, ap);
100   va_end(ap);
101 }
102 
FprintIndented(FILE * fp,size_t indent,const char * fmt,...)103 void FprintIndented(FILE* fp, size_t indent, const char* fmt, ...) {
104   va_list ap;
105   va_start(ap, fmt);
106   fprintf(fp, "%*s", static_cast<int>(indent * 2), "");
107   vfprintf(fp, fmt, ap);
108   va_end(ap);
109 }
110 
IsPowerOfTwo(uint64_t value)111 bool IsPowerOfTwo(uint64_t value) {
112   return (value != 0 && ((value & (value - 1)) == 0));
113 }
114 
GetEntriesInDir(const std::string & dirpath)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;
120     return result;
121   }
122   dirent* entry;
123   while ((entry = readdir(dir)) != nullptr) {
124     if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) {
125       continue;
126     }
127     result.push_back(entry->d_name);
128   }
129   closedir(dir);
130   return result;
131 }
132 
GetSubDirs(const std::string & dirpath)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]));
139     }
140   }
141   return result;
142 }
143 
IsDir(const std::string & dirpath)144 bool IsDir(const std::string& dirpath) {
145   struct stat st;
146   if (stat(dirpath.c_str(), &st) == 0) {
147     if (S_ISDIR(st.st_mode)) {
148       return true;
149     }
150   }
151   return false;
152 }
153 
IsRegularFile(const std::string & filename)154 bool IsRegularFile(const std::string& filename) {
155   struct stat st;
156   if (stat(filename.c_str(), &st) == 0) {
157     if (S_ISREG(st.st_mode)) {
158       return true;
159     }
160   }
161   return false;
162 }
163 
GetFileSize(const std::string & filename)164 uint64_t GetFileSize(const std::string& filename) {
165   struct stat st;
166   if (stat(filename.c_str(), &st) == 0) {
167     return static_cast<uint64_t>(st.st_size);
168   }
169   return 0;
170 }
171 
MkdirWithParents(const std::string & path)172 bool MkdirWithParents(const std::string& path) {
173   size_t prev_end = 0;
174   while (prev_end < path.size()) {
175     size_t next_end = path.find('/', prev_end + 1);
176     if (next_end == std::string::npos) {
177       break;
178     }
179     std::string dir_path = path.substr(0, next_end);
180     if (!IsDir(dir_path)) {
181 #if defined(_WIN32)
182       int ret = mkdir(dir_path.c_str());
183 #else
184       int ret = mkdir(dir_path.c_str(), 0755);
185 #endif
186       if (ret != 0) {
187         PLOG(ERROR) << "failed to create dir " << dir_path;
188         return false;
189       }
190     }
191     prev_end = next_end;
192   }
193   return true;
194 }
195 
xz_alloc(void *,size_t size)196 static void* xz_alloc(void*, size_t size) {
197   return malloc(size);
198 }
199 
xz_free(void *,void * address)200 static void xz_free(void*, void* address) {
201   free(address);
202 }
203 
XzDecompress(const std::string & compressed_data,std::string * decompressed_data)204 bool XzDecompress(const std::string& compressed_data, std::string* decompressed_data) {
205   ISzAlloc alloc;
206   CXzUnpacker state;
207   alloc.Alloc = xz_alloc;
208   alloc.Free = xz_free;
209   XzUnpacker_Construct(&state, &alloc);
210   CrcGenerateTable();
211   Crc64GenerateTable();
212   size_t src_offset = 0;
213   size_t dst_offset = 0;
214   std::string dst(compressed_data.size(), ' ');
215 
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);
224     if (res != SZ_OK) {
225       LOG(ERROR) << "LZMA decompression failed with error " << res;
226       XzUnpacker_Free(&state);
227       return false;
228     }
229     src_offset += src_remaining;
230     dst_offset += dst_remaining;
231   }
232   XzUnpacker_Free(&state);
233   if (!XzUnpacker_IsStreamWasFinished(&state)) {
234     LOG(ERROR) << "LZMA decompresstion failed due to incomplete stream";
235     return false;
236   }
237   dst.resize(dst_offset);
238   *decompressed_data = std::move(dst);
239   return true;
240 }
241 
GetLogSeverity(const std::string & name,android::base::LogSeverity * severity)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},
250   };
251   auto it = log_severity_map.find(name);
252   if (it != log_severity_map.end()) {
253     *severity = it->second;
254     return true;
255   }
256   return false;
257 }
258 
IsRoot()259 bool IsRoot() {
260   static int is_root = -1;
261   if (is_root == -1) {
262 #if defined(__linux__)
263     is_root = (getuid() == 0) ? 1 : 0;
264 #else
265     is_root = 0;
266 #endif
267   }
268   return is_root == 1;
269 }
270 
ProcessKernelSymbols(std::string & symbol_data,const std::function<bool (const KernelSymbol &)> & callback)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) {
278       *line_end = '\0';
279     }
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];
284     strcpy(module, "");
285 
286     KernelSymbol symbol;
287     int ret = sscanf(p, "%" PRIx64 " %c %s%s", &symbol.addr, &symbol.type, name, module);
288     if (line_end != nullptr) {
289       *line_end = '\n';
290       p = line_end + 1;
291     } else {
292       p = data_end;
293     }
294     if (ret >= 3) {
295       symbol.name = name;
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];
300       } else {
301         symbol.module = nullptr;
302       }
303 
304       if (callback(symbol)) {
305         return true;
306       }
307     }
308   }
309   return false;
310 }
311 
GetPageSize()312 size_t GetPageSize() {
313 #if defined(__linux__)
314   return sysconf(_SC_PAGE_SIZE);
315 #else
316   return 4096;
317 #endif
318 }
319 
ConvertBytesToValue(const char * bytes,uint32_t size)320 uint64_t ConvertBytesToValue(const char* bytes, uint32_t size) {
321   if (size > 8) {
322     LOG(FATAL) << "unexpected size " << size << " in ConvertBytesToValue";
323   }
324   uint64_t result = 0;
325   int shift = 0;
326   for (uint32_t i = 0; i < size; ++i) {
327     uint64_t tmp = static_cast<unsigned char>(bytes[i]);
328     result |= tmp << shift;
329     shift += 8;
330   }
331   return result;
332 }
333 
SecondToTimeval(double time_in_sec)334 timeval SecondToTimeval(double time_in_sec) {
335   timeval tv;
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);
338   return tv;
339 }
340