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/logging.h"
24#include "utils/FileMap.h"
25#include "utils/Trace.h"
26#include "ziparchive/zip_archive.h"
27
28#include "androidfw/Asset.h"
29#include "androidfw/Util.h"
30
31namespace android {
32
33std::unique_ptr<const ApkAssets> ApkAssets::Load(const std::string& path, bool system) {
34  return ApkAssets::LoadImpl(path, system, false /*load_as_shared_library*/);
35}
36
37std::unique_ptr<const ApkAssets> ApkAssets::LoadAsSharedLibrary(const std::string& path,
38                                                                bool system) {
39  return ApkAssets::LoadImpl(path, system, true /*load_as_shared_library*/);
40}
41
42std::unique_ptr<const ApkAssets> ApkAssets::LoadImpl(const std::string& path, bool system,
43                                                     bool load_as_shared_library) {
44  ATRACE_CALL();
45  ::ZipArchiveHandle unmanaged_handle;
46  int32_t result = ::OpenArchive(path.c_str(), &unmanaged_handle);
47  if (result != 0) {
48    LOG(ERROR) << ::ErrorCodeString(result);
49    return {};
50  }
51
52  // Wrap the handle in a unique_ptr so it gets automatically closed.
53  std::unique_ptr<ApkAssets> loaded_apk(new ApkAssets());
54  loaded_apk->zip_handle_.reset(unmanaged_handle);
55
56  ::ZipString entry_name("resources.arsc");
57  ::ZipEntry entry;
58  result = ::FindEntry(loaded_apk->zip_handle_.get(), entry_name, &entry);
59  if (result != 0) {
60    LOG(ERROR) << ::ErrorCodeString(result);
61    return {};
62  }
63
64  if (entry.method == kCompressDeflated) {
65    LOG(WARNING) << "resources.arsc is compressed.";
66  }
67
68  loaded_apk->path_ = path;
69  loaded_apk->resources_asset_ =
70      loaded_apk->Open("resources.arsc", Asset::AccessMode::ACCESS_BUFFER);
71  if (loaded_apk->resources_asset_ == nullptr) {
72    return {};
73  }
74
75  loaded_apk->loaded_arsc_ =
76      LoadedArsc::Load(loaded_apk->resources_asset_->getBuffer(true /*wordAligned*/),
77                       loaded_apk->resources_asset_->getLength(), system, load_as_shared_library);
78  if (loaded_apk->loaded_arsc_ == nullptr) {
79    return {};
80  }
81
82  // Need to force a move for mingw32.
83  return std::move(loaded_apk);
84}
85
86std::unique_ptr<Asset> ApkAssets::Open(const std::string& path, Asset::AccessMode mode) const {
87  ATRACE_CALL();
88  CHECK(zip_handle_ != nullptr);
89
90  ::ZipString name(path.c_str());
91  ::ZipEntry entry;
92  int32_t result = ::FindEntry(zip_handle_.get(), name, &entry);
93  if (result != 0) {
94    LOG(ERROR) << "No entry '" << path << "' found in APK '" << path_ << "'";
95    return {};
96  }
97
98  if (entry.method == kCompressDeflated) {
99    std::unique_ptr<FileMap> map = util::make_unique<FileMap>();
100    if (!map->create(path_.c_str(), ::GetFileDescriptor(zip_handle_.get()), entry.offset,
101                     entry.compressed_length, true /*readOnly*/)) {
102      LOG(ERROR) << "Failed to mmap file '" << path << "' in APK '" << path_ << "'";
103      return {};
104    }
105
106    std::unique_ptr<Asset> asset =
107        Asset::createFromCompressedMap(std::move(map), entry.uncompressed_length, mode);
108    if (asset == nullptr) {
109      LOG(ERROR) << "Failed to decompress '" << path << "'.";
110      return {};
111    }
112    return asset;
113  } else {
114    std::unique_ptr<FileMap> map = util::make_unique<FileMap>();
115    if (!map->create(path_.c_str(), ::GetFileDescriptor(zip_handle_.get()), entry.offset,
116                     entry.uncompressed_length, true /*readOnly*/)) {
117      LOG(ERROR) << "Failed to mmap file '" << path << "' in APK '" << path_ << "'";
118      return {};
119    }
120
121    std::unique_ptr<Asset> asset = Asset::createFromUncompressedMap(std::move(map), mode);
122    if (asset == nullptr) {
123      LOG(ERROR) << "Failed to mmap file '" << path << "' in APK '" << path_ << "'";
124      return {};
125    }
126    return asset;
127  }
128}
129
130bool ApkAssets::ForEachFile(const std::string& root_path,
131                            const std::function<void(const StringPiece&, FileType)>& f) const {
132  CHECK(zip_handle_ != nullptr);
133
134  std::string root_path_full = root_path;
135  if (root_path_full.back() != '/') {
136    root_path_full += '/';
137  }
138
139  ::ZipString prefix(root_path_full.c_str());
140  void* cookie;
141  if (::StartIteration(zip_handle_.get(), &cookie, &prefix, nullptr) != 0) {
142    return false;
143  }
144
145  ::ZipString name;
146  ::ZipEntry entry;
147
148  // We need to hold back directories because many paths will contain them and we want to only
149  // surface one.
150  std::set<std::string> dirs;
151
152  int32_t result;
153  while ((result = ::Next(cookie, &entry, &name)) == 0) {
154    StringPiece full_file_path(reinterpret_cast<const char*>(name.name), name.name_length);
155    StringPiece leaf_file_path = full_file_path.substr(root_path_full.size());
156    auto iter = std::find(leaf_file_path.begin(), leaf_file_path.end(), '/');
157    if (iter != leaf_file_path.end()) {
158      dirs.insert(
159          leaf_file_path.substr(0, std::distance(leaf_file_path.begin(), iter)).to_string());
160    } else if (!leaf_file_path.empty()) {
161      f(leaf_file_path, kFileTypeRegular);
162    }
163  }
164  ::EndIteration(cookie);
165
166  // Now present the unique directories.
167  for (const std::string& dir : dirs) {
168    f(dir, kFileTypeDirectory);
169  }
170
171  // -1 is end of iteration, anything else is an error.
172  return result == -1;
173}
174
175}  // namespace android
176