OSDN Git Service

Merge "Crypto performance benchmark" into nyc-dev
[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 std::map<ApkInspector::ApkOffset, std::unique_ptr<EmbeddedElf>> ApkInspector::embedded_elf_cache_;
35
36 EmbeddedElf* ApkInspector::FindElfInApkByOffset(const std::string& apk_path, uint64_t file_offset) {
37   // Already in cache?
38   ApkOffset ami(apk_path, file_offset);
39   auto it = embedded_elf_cache_.find(ami);
40   if (it != embedded_elf_cache_.end()) {
41     return it->second.get();
42   }
43   std::unique_ptr<EmbeddedElf> elf = FindElfInApkByOffsetWithoutCache(apk_path, file_offset);
44   EmbeddedElf* result = elf.get();
45   embedded_elf_cache_[ami] = std::move(elf);
46   return result;
47 }
48
49 std::unique_ptr<EmbeddedElf> ApkInspector::FindElfInApkByOffsetWithoutCache(const std::string& apk_path,
50                                                                             uint64_t file_offset) {
51   // Crack open the apk(zip) file and take a look.
52   if (!IsValidApkPath(apk_path)) {
53     return nullptr;
54   }
55   FileHelper fhelper = FileHelper::OpenReadOnly(apk_path);
56   if (!fhelper) {
57     return nullptr;
58   }
59
60   ArchiveHelper ahelper(fhelper.fd(), apk_path);
61   if (!ahelper) {
62     return nullptr;
63   }
64   ZipArchiveHandle &handle = ahelper.archive_handle();
65
66   // Iterate through the zip file. Look for a zip entry corresponding
67   // to an uncompressed blob whose range intersects with the mmap
68   // offset we're interested in.
69   void* iteration_cookie;
70   if (StartIteration(handle, &iteration_cookie, nullptr, nullptr) < 0) {
71     return nullptr;
72   }
73   ZipEntry zentry;
74   ZipString zname;
75   bool found = false;
76   int zrc;
77   while ((zrc = Next(iteration_cookie, &zentry, &zname)) == 0) {
78     if (zentry.method == kCompressStored &&
79         file_offset >= static_cast<uint64_t>(zentry.offset) &&
80         file_offset < static_cast<uint64_t>(zentry.offset + zentry.uncompressed_length)) {
81       // Found.
82       found = true;
83       break;
84     }
85   }
86   EndIteration(iteration_cookie);
87   if (!found) {
88     return nullptr;
89   }
90
91   // We found something in the zip file at the right spot. Is it an ELF?
92   if (lseek(fhelper.fd(), zentry.offset, SEEK_SET) != zentry.offset) {
93     PLOG(ERROR) << "lseek() failed in " << apk_path << " offset " << zentry.offset;
94     return nullptr;
95   }
96   std::string entry_name;
97   entry_name.resize(zname.name_length,'\0');
98   memcpy(&entry_name[0], zname.name, zname.name_length);
99   if (!IsValidElfFile(fhelper.fd())) {
100     LOG(ERROR) << "problems reading ELF from in " << apk_path << " entry '"
101                << entry_name << "'";
102     return nullptr;
103   }
104
105   // Elf found: add EmbeddedElf to vector, update cache.
106   return std::unique_ptr<EmbeddedElf>(new EmbeddedElf(apk_path, entry_name, zentry.offset,
107                                                       zentry.uncompressed_length));
108 }
109
110 std::unique_ptr<EmbeddedElf> ApkInspector::FindElfInApkByName(const std::string& apk_path,
111                                                               const std::string& elf_filename) {
112   if (!IsValidApkPath(apk_path)) {
113     return nullptr;
114   }
115   FileHelper fhelper = FileHelper::OpenReadOnly(apk_path);
116   if (!fhelper) {
117     return nullptr;
118   }
119   ArchiveHelper ahelper(fhelper.fd(), apk_path);
120   if (!ahelper) {
121     return nullptr;
122   }
123   ZipArchiveHandle& handle = ahelper.archive_handle();
124   ZipEntry zentry;
125   int32_t rc = FindEntry(handle, ZipString(elf_filename.c_str()), &zentry);
126   if (rc != 0) {
127     LOG(ERROR) << "failed to find " << elf_filename << " in " << apk_path
128         << ": " << ErrorCodeString(rc);
129     return nullptr;
130   }
131   if (zentry.method != kCompressStored || zentry.compressed_length != zentry.uncompressed_length) {
132     LOG(ERROR) << "shared library " << elf_filename << " in " << apk_path << " is compressed";
133     return nullptr;
134   }
135   return std::unique_ptr<EmbeddedElf>(new EmbeddedElf(apk_path, elf_filename, zentry.offset,
136                                                   zentry.uncompressed_length));
137 }
138
139 bool IsValidApkPath(const std::string& apk_path) {
140   static const char zip_preamble[] = {0x50, 0x4b, 0x03, 0x04 };
141   if (!IsRegularFile(apk_path)) {
142     return false;
143   }
144   std::string mode = std::string("rb") + CLOSE_ON_EXEC_MODE;
145   FILE* fp = fopen(apk_path.c_str(), mode.c_str());
146   if (fp == nullptr) {
147     return false;
148   }
149   char buf[4];
150   if (fread(buf, 4, 1, fp) != 1) {
151     fclose(fp);
152     return false;
153   }
154   fclose(fp);
155   return memcmp(buf, zip_preamble, 4) == 0;
156 }
157
158 // Refer file in apk in compliance with http://developer.android.com/reference/java/net/JarURLConnection.html.
159 std::string GetUrlInApk(const std::string& apk_path, const std::string& elf_filename) {
160   return apk_path + "!/" + elf_filename;
161 }
162
163 std::tuple<bool, std::string, std::string> SplitUrlInApk(const std::string& path) {
164   size_t pos = path.find("!/");
165   if (pos == std::string::npos) {
166     return std::make_tuple(false, "", "");
167   }
168   return std::make_tuple(true, path.substr(0, pos), path.substr(pos + 2));
169 }
170
171 bool GetBuildIdFromApkFile(const std::string& apk_path, const std::string& elf_filename,
172                            BuildId* build_id) {
173   std::unique_ptr<EmbeddedElf> ee = ApkInspector::FindElfInApkByName(apk_path, elf_filename);
174   if (ee == nullptr) {
175     return false;
176   }
177   return GetBuildIdFromEmbeddedElfFile(apk_path, ee->entry_offset(), ee->entry_size(), build_id);
178 }
179
180 bool ParseSymbolsFromApkFile(const std::string& apk_path, const std::string& elf_filename,
181                              const BuildId& expected_build_id,
182                              std::function<void(const ElfFileSymbol&)> callback) {
183   std::unique_ptr<EmbeddedElf> ee = ApkInspector::FindElfInApkByName(apk_path, elf_filename);
184   if (ee == nullptr) {
185     return false;
186   }
187   return ParseSymbolsFromEmbeddedElfFile(apk_path, ee->entry_offset(), ee->entry_size(),
188                                          expected_build_id, callback);
189 }