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