OSDN Git Service

Merge "simpleperf: report symbols of native libraries in apk file." am: 88a0a38c86
[android-x86/system-extras.git] / simpleperf / read_apk.cpp
1 /*
2 **
3 ** Copyright 2016, The Android Open Source Project
4 **
5 ** Licensed under the Apache License, Version 2.0 (the "License");
6 ** you may not use this file except in compliance with the License.
7 ** You may obtain a copy of the License at
8 **
9 **     http://www.apache.org/licenses/LICENSE-2.0
10 **
11 ** Unless required by applicable law or agreed to in writing, software
12 ** distributed under the License is distributed on an "AS IS" BASIS,
13 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 ** See the License for the specific language governing permissions and
15 ** limitations under the License.
16 */
17
18 #include "read_apk.h"
19
20 #include <errno.h>
21 #include <stdio.h>
22 #include <string.h>
23 #include <sys/stat.h>
24 #include <sys/types.h>
25 #include <unistd.h>
26
27 #include <android-base/file.h>
28 #include <android-base/logging.h>
29 #include <ziparchive/zip_archive.h>
30
31 #include "read_elf.h"
32 #include "utils.h"
33
34 class ArchiveHelper {
35  public:
36   explicit ArchiveHelper(int fd, const std::string& debug_filename) : valid_(false) {
37     int rc = OpenArchiveFd(fd, "", &handle_, false);
38     if (rc == 0) {
39       valid_ = true;
40     } else {
41       LOG(ERROR) << "Failed to open archive " << debug_filename << ": " << ErrorCodeString(rc);
42     }
43   }
44   ~ArchiveHelper() {
45     if (valid_) {
46       CloseArchive(handle_);
47     }
48   }
49   bool valid() const { return valid_; }
50   ZipArchiveHandle &archive_handle() { return handle_; }
51
52  private:
53   ZipArchiveHandle handle_;
54   bool valid_;
55 };
56
57 std::map<ApkInspector::ApkOffset, std::unique_ptr<EmbeddedElf>> ApkInspector::embedded_elf_cache_;
58
59 EmbeddedElf* ApkInspector::FindElfInApkByOffset(const std::string& apk_path, off64_t file_offset) {
60   // Already in cache?
61   ApkOffset ami(apk_path, file_offset);
62   auto it = embedded_elf_cache_.find(ami);
63   if (it != embedded_elf_cache_.end()) {
64     return it->second.get();
65   }
66   std::unique_ptr<EmbeddedElf> elf = FindElfInApkByOffsetWithoutCache(apk_path, file_offset);
67   EmbeddedElf* result = elf.get();
68   embedded_elf_cache_[ami] = std::move(elf);
69   return result;
70 }
71
72 std::unique_ptr<EmbeddedElf> ApkInspector::FindElfInApkByOffsetWithoutCache(const std::string& apk_path,
73                                                                             off64_t file_offset) {
74   // Crack open the apk(zip) file and take a look.
75   if (!IsValidApkPath(apk_path)) {
76     return nullptr;
77   }
78   FileHelper fhelper(apk_path.c_str());
79   if (!fhelper) {
80     return nullptr;
81   }
82
83   ArchiveHelper ahelper(fhelper.fd(), apk_path);
84   if (!ahelper.valid()) {
85     return nullptr;
86   }
87   ZipArchiveHandle &handle = ahelper.archive_handle();
88
89   // Iterate through the zip file. Look for a zip entry corresponding
90   // to an uncompressed blob whose range intersects with the mmap
91   // offset we're interested in.
92   void* iteration_cookie;
93   if (StartIteration(handle, &iteration_cookie, nullptr, nullptr) < 0) {
94     return nullptr;
95   }
96   ZipEntry zentry;
97   ZipString zname;
98   bool found = false;
99   int zrc;
100   while ((zrc = Next(iteration_cookie, &zentry, &zname)) == 0) {
101     if (zentry.method == kCompressStored &&
102         file_offset >= zentry.offset &&
103         file_offset < zentry.offset + zentry.uncompressed_length) {
104       // Found.
105       found = true;
106       break;
107     }
108   }
109   EndIteration(iteration_cookie);
110   if (!found) {
111     return nullptr;
112   }
113
114   // We found something in the zip file at the right spot. Is it an ELF?
115   if (lseek(fhelper.fd(), zentry.offset, SEEK_SET) != zentry.offset) {
116     PLOG(ERROR) << "lseek() failed in " << apk_path << " offset " << zentry.offset;
117     return nullptr;
118   }
119   std::string entry_name;
120   entry_name.resize(zname.name_length,'\0');
121   memcpy(&entry_name[0], zname.name, zname.name_length);
122   if (!IsValidElfFile(fhelper.fd())) {
123     LOG(ERROR) << "problems reading ELF from in " << apk_path << " entry '"
124                << entry_name << "'";
125     return nullptr;
126   }
127
128   // Elf found: add EmbeddedElf to vector, update cache.
129   return std::unique_ptr<EmbeddedElf>(new EmbeddedElf(apk_path, entry_name, zentry.offset,
130                                                       zentry.uncompressed_length));
131 }
132
133 std::unique_ptr<EmbeddedElf> ApkInspector::FindElfInApkByName(const std::string& apk_path,
134                                                               const std::string& elf_filename) {
135   if (!IsValidApkPath(apk_path)) {
136     return nullptr;
137   }
138   FileHelper fhelper(apk_path.c_str());
139   if (!fhelper) {
140     return nullptr;
141   }
142   ArchiveHelper ahelper(fhelper.fd(), apk_path);
143   if (!ahelper.valid()) {
144     return nullptr;
145   }
146   ZipArchiveHandle& handle = ahelper.archive_handle();
147   ZipEntry zentry;
148   int32_t rc = FindEntry(handle, ZipString(elf_filename.c_str()), &zentry);
149   if (rc != 0) {
150     LOG(ERROR) << "failed to find " << elf_filename << " in " << apk_path
151         << ": " << ErrorCodeString(rc);
152     return nullptr;
153   }
154   if (zentry.method != kCompressStored || zentry.compressed_length != zentry.uncompressed_length) {
155     LOG(ERROR) << "shared library " << elf_filename << " in " << apk_path << " is compressed";
156     return nullptr;
157   }
158   return std::unique_ptr<EmbeddedElf>(new EmbeddedElf(apk_path, elf_filename, zentry.offset,
159                                                   zentry.uncompressed_length));
160 }
161
162 bool IsValidApkPath(const std::string& apk_path) {
163   static const char zip_preamble[] = {0x50, 0x4b, 0x03, 0x04 };
164   if (!IsRegularFile(apk_path)) {
165     return false;
166   }
167   std::string mode = std::string("rb") + CLOSE_ON_EXEC_MODE;
168   FILE* fp = fopen(apk_path.c_str(), mode.c_str());
169   if (fp == nullptr) {
170     return false;
171   }
172   char buf[4];
173   if (fread(buf, 4, 1, fp) != 1) {
174     fclose(fp);
175     return false;
176   }
177   fclose(fp);
178   return memcmp(buf, zip_preamble, 4) == 0;
179 }
180
181 // Refer file in apk in compliance with http://developer.android.com/reference/java/net/JarURLConnection.html.
182 std::string GetUrlInApk(const std::string& apk_path, const std::string& elf_filename) {
183   return apk_path + "!/" + elf_filename;
184 }
185
186 std::tuple<bool, std::string, std::string> SplitUrlInApk(const std::string& path) {
187   size_t pos = path.find("!/");
188   if (pos == std::string::npos) {
189     return std::make_tuple(false, "", "");
190   }
191   return std::make_tuple(true, path.substr(0, pos), path.substr(pos + 2));
192 }
193
194 bool GetBuildIdFromApkFile(const std::string& apk_path, const std::string& elf_filename,
195                            BuildId* build_id) {
196   std::unique_ptr<EmbeddedElf> ee = ApkInspector::FindElfInApkByName(apk_path, elf_filename);
197   if (ee == nullptr) {
198     return false;
199   }
200   return GetBuildIdFromEmbeddedElfFile(apk_path, ee->entry_offset(), ee->entry_size(), build_id);
201 }
202
203 bool ParseSymbolsFromApkFile(const std::string& apk_path, const std::string& elf_filename,
204                              const BuildId& expected_build_id,
205                              std::function<void(const ElfFileSymbol&)> callback) {
206   std::unique_ptr<EmbeddedElf> ee = ApkInspector::FindElfInApkByName(apk_path, elf_filename);
207   if (ee == nullptr) {
208     return false;
209   }
210   return ParseSymbolsFromEmbeddedElfFile(apk_path, ee->entry_offset(), ee->entry_size(),
211                                          expected_build_id, callback);
212 }