ApkAssets.cpp revision 970bd8d2835b05237c4561bd6c12329e26f136b3
1/*
2 * Copyright (C) 2016 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#define ATRACE_TAG ATRACE_TAG_RESOURCES
18
19#include "androidfw/ApkAssets.h"
20
21#include <algorithm>
22
23#include "android-base/errors.h"
24#include "android-base/file.h"
25#include "android-base/logging.h"
26#include "android-base/unique_fd.h"
27#include "android-base/utf8.h"
28#include "utils/Compat.h"
29#include "utils/FileMap.h"
30#include "utils/Trace.h"
31#include "ziparchive/zip_archive.h"
32
33#include "androidfw/Asset.h"
34#include "androidfw/Idmap.h"
35#include "androidfw/ResourceTypes.h"
36#include "androidfw/Util.h"
37
38namespace android {
39
40using base::SystemErrorCodeToString;
41using base::unique_fd;
42
43static const std::string kResourcesArsc("resources.arsc");
44
45ApkAssets::ApkAssets(void* unmanaged_handle, const std::string& path)
46    : zip_handle_(unmanaged_handle, ::CloseArchive), path_(path) {
47}
48
49std::unique_ptr<const ApkAssets> ApkAssets::Load(const std::string& path, bool system) {
50  return ApkAssets::LoadImpl(path, nullptr, nullptr, system, false /*load_as_shared_library*/);
51}
52
53std::unique_ptr<const ApkAssets> ApkAssets::LoadAsSharedLibrary(const std::string& path,
54                                                                bool system) {
55  return ApkAssets::LoadImpl(path, nullptr, nullptr, system, true /*load_as_shared_library*/);
56}
57
58std::unique_ptr<const ApkAssets> ApkAssets::LoadOverlay(const std::string& idmap_path,
59                                                        bool system) {
60  std::unique_ptr<Asset> idmap_asset = CreateAssetFromFile(idmap_path);
61  if (idmap_asset == nullptr) {
62    return {};
63  }
64
65  const StringPiece idmap_data(
66      reinterpret_cast<const char*>(idmap_asset->getBuffer(true /*wordAligned*/)),
67      static_cast<size_t>(idmap_asset->getLength()));
68  std::unique_ptr<const LoadedIdmap> loaded_idmap = LoadedIdmap::Load(idmap_data);
69  if (loaded_idmap == nullptr) {
70    LOG(ERROR) << "failed to load IDMAP " << idmap_path;
71    return {};
72  }
73  return LoadImpl(loaded_idmap->OverlayApkPath(), std::move(idmap_asset), std::move(loaded_idmap),
74                  system, false /*load_as_shared_library*/);
75}
76
77std::unique_ptr<Asset> ApkAssets::CreateAssetFromFile(const std::string& path) {
78  unique_fd fd(base::utf8::open(path.c_str(), O_RDONLY | O_BINARY | O_CLOEXEC));
79  if (fd == -1) {
80    LOG(ERROR) << "Failed to open file '" << path << "': " << SystemErrorCodeToString(errno);
81    return {};
82  }
83
84  const off64_t file_len = lseek64(fd, 0, SEEK_END);
85  if (file_len < 0) {
86    LOG(ERROR) << "Failed to get size of file '" << path << "': " << SystemErrorCodeToString(errno);
87    return {};
88  }
89
90  std::unique_ptr<FileMap> file_map = util::make_unique<FileMap>();
91  if (!file_map->create(path.c_str(), fd, 0, static_cast<size_t>(file_len), true /*readOnly*/)) {
92    LOG(ERROR) << "Failed to mmap file '" << path << "': " << SystemErrorCodeToString(errno);
93    return {};
94  }
95  return Asset::createFromUncompressedMap(std::move(file_map), Asset::AccessMode::ACCESS_RANDOM);
96}
97
98std::unique_ptr<const ApkAssets> ApkAssets::LoadImpl(
99    const std::string& path, std::unique_ptr<Asset> idmap_asset,
100    std::unique_ptr<const LoadedIdmap> loaded_idmap, bool system, bool load_as_shared_library) {
101  ATRACE_CALL();
102  ::ZipArchiveHandle unmanaged_handle;
103  int32_t result = ::OpenArchive(path.c_str(), &unmanaged_handle);
104  if (result != 0) {
105    LOG(ERROR) << "Failed to open APK '" << path << "' " << ::ErrorCodeString(result);
106    return {};
107  }
108
109  // Wrap the handle in a unique_ptr so it gets automatically closed.
110  std::unique_ptr<ApkAssets> loaded_apk(new ApkAssets(unmanaged_handle, path));
111
112  // Find the resource table.
113  ::ZipString entry_name(kResourcesArsc.c_str());
114  ::ZipEntry entry;
115  result = ::FindEntry(loaded_apk->zip_handle_.get(), entry_name, &entry);
116  if (result != 0) {
117    // There is no resources.arsc, so create an empty LoadedArsc and return.
118    loaded_apk->loaded_arsc_ = LoadedArsc::CreateEmpty();
119    return std::move(loaded_apk);
120  }
121
122  if (entry.method == kCompressDeflated) {
123    LOG(WARNING) << kResourcesArsc << " in APK '" << path << "' is compressed.";
124  }
125
126  // Open the resource table via mmap unless it is compressed. This logic is taken care of by Open.
127  loaded_apk->resources_asset_ = loaded_apk->Open(kResourcesArsc, Asset::AccessMode::ACCESS_BUFFER);
128  if (loaded_apk->resources_asset_ == nullptr) {
129    LOG(ERROR) << "Failed to open '" << kResourcesArsc << "' in APK '" << path << "'.";
130    return {};
131  }
132
133  // Must retain ownership of the IDMAP Asset so that all pointers to its mmapped data remain valid.
134  loaded_apk->idmap_asset_ = std::move(idmap_asset);
135
136  const StringPiece data(
137      reinterpret_cast<const char*>(loaded_apk->resources_asset_->getBuffer(true /*wordAligned*/)),
138      loaded_apk->resources_asset_->getLength());
139  loaded_apk->loaded_arsc_ =
140      LoadedArsc::Load(data, loaded_idmap.get(), system, load_as_shared_library);
141  if (loaded_apk->loaded_arsc_ == nullptr) {
142    LOG(ERROR) << "Failed to load '" << kResourcesArsc << "' in APK '" << path << "'.";
143    return {};
144  }
145
146  // Need to force a move for mingw32.
147  return std::move(loaded_apk);
148}
149
150std::unique_ptr<Asset> ApkAssets::Open(const std::string& path, Asset::AccessMode mode) const {
151  ATRACE_CALL();
152  CHECK(zip_handle_ != nullptr);
153
154  ::ZipString name(path.c_str());
155  ::ZipEntry entry;
156  int32_t result = ::FindEntry(zip_handle_.get(), name, &entry);
157  if (result != 0) {
158    return {};
159  }
160
161  if (entry.method == kCompressDeflated) {
162    std::unique_ptr<FileMap> map = util::make_unique<FileMap>();
163    if (!map->create(path_.c_str(), ::GetFileDescriptor(zip_handle_.get()), entry.offset,
164                     entry.compressed_length, true /*readOnly*/)) {
165      LOG(ERROR) << "Failed to mmap file '" << path << "' in APK '" << path_ << "'";
166      return {};
167    }
168
169    std::unique_ptr<Asset> asset =
170        Asset::createFromCompressedMap(std::move(map), entry.uncompressed_length, mode);
171    if (asset == nullptr) {
172      LOG(ERROR) << "Failed to decompress '" << path << "'.";
173      return {};
174    }
175    return asset;
176  } else {
177    std::unique_ptr<FileMap> map = util::make_unique<FileMap>();
178    if (!map->create(path_.c_str(), ::GetFileDescriptor(zip_handle_.get()), entry.offset,
179                     entry.uncompressed_length, true /*readOnly*/)) {
180      LOG(ERROR) << "Failed to mmap file '" << path << "' in APK '" << path_ << "'";
181      return {};
182    }
183
184    std::unique_ptr<Asset> asset = Asset::createFromUncompressedMap(std::move(map), mode);
185    if (asset == nullptr) {
186      LOG(ERROR) << "Failed to mmap file '" << path << "' in APK '" << path_ << "'";
187      return {};
188    }
189    return asset;
190  }
191}
192
193bool ApkAssets::ForEachFile(const std::string& root_path,
194                            const std::function<void(const StringPiece&, FileType)>& f) const {
195  CHECK(zip_handle_ != nullptr);
196
197  std::string root_path_full = root_path;
198  if (root_path_full.back() != '/') {
199    root_path_full += '/';
200  }
201
202  ::ZipString prefix(root_path_full.c_str());
203  void* cookie;
204  if (::StartIteration(zip_handle_.get(), &cookie, &prefix, nullptr) != 0) {
205    return false;
206  }
207
208  ::ZipString name;
209  ::ZipEntry entry;
210
211  // We need to hold back directories because many paths will contain them and we want to only
212  // surface one.
213  std::set<std::string> dirs;
214
215  int32_t result;
216  while ((result = ::Next(cookie, &entry, &name)) == 0) {
217    StringPiece full_file_path(reinterpret_cast<const char*>(name.name), name.name_length);
218    StringPiece leaf_file_path = full_file_path.substr(root_path_full.size());
219    auto iter = std::find(leaf_file_path.begin(), leaf_file_path.end(), '/');
220    if (iter != leaf_file_path.end()) {
221      dirs.insert(
222          leaf_file_path.substr(0, std::distance(leaf_file_path.begin(), iter)).to_string());
223    } else if (!leaf_file_path.empty()) {
224      f(leaf_file_path, kFileTypeRegular);
225    }
226  }
227  ::EndIteration(cookie);
228
229  // Now present the unique directories.
230  for (const std::string& dir : dirs) {
231    f(dir, kFileTypeDirectory);
232  }
233
234  // -1 is end of iteration, anything else is an error.
235  return result == -1;
236}
237
238}  // namespace android
239