• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2017 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 "dex_file_loader.h"
18 
19 #include <sys/stat.h>
20 
21 #include <memory>
22 #include <optional>
23 
24 #include "android-base/stringprintf.h"
25 #include "base/bit_utils.h"
26 #include "base/file_magic.h"
27 #include "base/mem_map.h"
28 #include "base/os.h"
29 #include "base/stl_util.h"
30 #include "base/systrace.h"
31 #include "base/unix_file/fd_file.h"
32 #include "base/zip_archive.h"
33 #include "compact_dex_file.h"
34 #include "dex_file.h"
35 #include "dex_file_verifier.h"
36 #include "standard_dex_file.h"
37 
38 namespace art {
39 
40 #if defined(STATIC_LIB)
41 #define DEXFILE_SCOPED_TRACE(name)
42 #else
43 #define DEXFILE_SCOPED_TRACE(name) ScopedTrace trace(name)
44 #endif
45 
46 namespace {
47 
48 // Technically we do not have a limitation with respect to the number of dex files that can be in a
49 // multidex APK. However, it's bad practice, as each dex file requires its own tables for symbols
50 // (types, classes, methods, ...) and dex caches. So warn the user that we open a zip with what
51 // seems an excessive number.
52 static constexpr size_t kWarnOnManyDexFilesThreshold = 100;
53 
54 using android::base::StringPrintf;
55 
56 class VectorContainer : public DexFileContainer {
57  public:
VectorContainer(std::vector<uint8_t> && vector)58   explicit VectorContainer(std::vector<uint8_t>&& vector) : vector_(std::move(vector)) { }
~VectorContainer()59   ~VectorContainer() override { }
60 
IsReadOnly() const61   bool IsReadOnly() const override { return true; }
62 
EnableWrite()63   bool EnableWrite() override { return true; }
64 
DisableWrite()65   bool DisableWrite() override { return false; }
66 
Begin() const67   const uint8_t* Begin() const override { return vector_.data(); }
68 
End() const69   const uint8_t* End() const override { return vector_.data() + vector_.size(); }
70 
71  private:
72   std::vector<uint8_t> vector_;
73   DISALLOW_COPY_AND_ASSIGN(VectorContainer);
74 };
75 
76 class MemMapContainer : public DexFileContainer {
77  public:
MemMapContainer(MemMap && mem_map,bool is_file_map=false)78   explicit MemMapContainer(MemMap&& mem_map, bool is_file_map = false)
79       : mem_map_(std::move(mem_map)), is_file_map_(is_file_map) {}
80 
GetPermissions() const81   int GetPermissions() const {
82     if (!mem_map_.IsValid()) {
83       return 0;
84     } else {
85       return mem_map_.GetProtect();
86     }
87   }
88 
IsReadOnly() const89   bool IsReadOnly() const override { return GetPermissions() == PROT_READ; }
90 
EnableWrite()91   bool EnableWrite() override {
92     if (!IsReadOnly()) {
93       // We can already write to the container.
94       // This method may be called multiple times by tests if DexFiles share container.
95       return true;
96     }
97     if (!mem_map_.IsValid()) {
98       return false;
99     } else {
100       return mem_map_.Protect(PROT_READ | PROT_WRITE);
101     }
102   }
103 
DisableWrite()104   bool DisableWrite() override {
105     CHECK(!IsReadOnly());
106     if (!mem_map_.IsValid()) {
107       return false;
108     } else {
109       return mem_map_.Protect(PROT_READ);
110     }
111   }
112 
Begin() const113   const uint8_t* Begin() const override { return mem_map_.Begin(); }
114 
End() const115   const uint8_t* End() const override { return mem_map_.End(); }
116 
IsFileMap() const117   bool IsFileMap() const override { return is_file_map_; }
118 
119  protected:
120   MemMap mem_map_;
121   bool is_file_map_;
122   DISALLOW_COPY_AND_ASSIGN(MemMapContainer);
123 };
124 
125 }  // namespace
126 
127 const File DexFileLoader::kInvalidFile;
128 
IsMagicValid(uint32_t magic)129 bool DexFileLoader::IsMagicValid(uint32_t magic) {
130   return IsMagicValid(reinterpret_cast<uint8_t*>(&magic));
131 }
132 
IsMagicValid(const uint8_t * magic)133 bool DexFileLoader::IsMagicValid(const uint8_t* magic) {
134   return StandardDexFile::IsMagicValid(magic) ||
135       CompactDexFile::IsMagicValid(magic);
136 }
137 
IsVersionAndMagicValid(const uint8_t * magic)138 bool DexFileLoader::IsVersionAndMagicValid(const uint8_t* magic) {
139   if (StandardDexFile::IsMagicValid(magic)) {
140     return StandardDexFile::IsVersionValid(magic);
141   }
142   if (CompactDexFile::IsMagicValid(magic)) {
143     return CompactDexFile::IsVersionValid(magic);
144   }
145   return false;
146 }
147 
IsMultiDexLocation(std::string_view location)148 bool DexFileLoader::IsMultiDexLocation(std::string_view location) {
149   return location.find(kMultiDexSeparator) != std::string_view::npos;
150 }
151 
GetMultiDexClassesDexName(size_t index)152 std::string DexFileLoader::GetMultiDexClassesDexName(size_t index) {
153   return (index == 0) ? "classes.dex" : StringPrintf("classes%zu.dex", index + 1);
154 }
155 
GetMultiDexLocation(size_t index,const char * dex_location)156 std::string DexFileLoader::GetMultiDexLocation(size_t index, const char* dex_location) {
157   DCHECK(!IsMultiDexLocation(dex_location));
158   if (index == 0) {
159     return dex_location;
160   }
161   return StringPrintf("%s%cclasses%zu.dex", dex_location, kMultiDexSeparator, index + 1);
162 }
163 
GetMultiDexChecksum(std::optional<uint32_t> * checksum,std::string * error_msg,bool * only_contains_uncompressed_dex)164 bool DexFileLoader::GetMultiDexChecksum(std::optional<uint32_t>* checksum,
165                                         std::string* error_msg,
166                                         bool* only_contains_uncompressed_dex) {
167   CHECK(checksum != nullptr);
168   checksum->reset();  // Return nullopt for an empty zip archive.
169 
170   uint32_t magic;
171   if (!InitAndReadMagic(/*header_offset=*/0, &magic, error_msg)) {
172     return false;
173   }
174 
175   if (IsZipMagic(magic)) {
176     std::unique_ptr<ZipArchive> zip_archive(
177         file_->IsValid() ?
178             ZipArchive::OpenFromOwnedFd(file_->Fd(), location_.c_str(), error_msg) :
179             ZipArchive::OpenFromMemory(
180                 root_container_->Begin(), root_container_->Size(), location_.c_str(), error_msg));
181     if (zip_archive.get() == nullptr) {
182       DCHECK(!error_msg->empty());
183       return false;
184     }
185     if (only_contains_uncompressed_dex != nullptr) {
186       *only_contains_uncompressed_dex = true;
187     }
188     for (size_t i = 0;; ++i) {
189       std::string name = GetMultiDexClassesDexName(i);
190       std::unique_ptr<ZipEntry> zip_entry(zip_archive->Find(name.c_str(), error_msg));
191       if (zip_entry == nullptr) {
192         break;
193       }
194       if (only_contains_uncompressed_dex != nullptr) {
195         if (!(zip_entry->IsUncompressed() && zip_entry->IsAlignedTo(alignof(DexFile::Header)))) {
196           *only_contains_uncompressed_dex = false;
197         }
198       }
199       *checksum = checksum->value_or(kEmptyMultiDexChecksum) ^ zip_entry->GetCrc32();
200     }
201     return true;
202   }
203   if (!MapRootContainer(error_msg)) {
204     return false;
205   }
206   const uint8_t* begin = root_container_->Begin();
207   const uint8_t* end = root_container_->End();
208   for (const uint8_t* ptr = begin; ptr < end;) {
209     const auto* header = reinterpret_cast<const DexFile::Header*>(ptr);
210     size_t size = dchecked_integral_cast<size_t>(end - ptr);
211     if (size < sizeof(*header) || !IsMagicValid(ptr)) {
212       *error_msg = StringPrintf("Invalid dex header: '%s'", filename_.c_str());
213       return false;
214     }
215     if (size < header->file_size_) {
216       *error_msg = StringPrintf("Truncated dex file: '%s'", filename_.c_str());
217       return false;
218     }
219     *checksum = checksum->value_or(kEmptyMultiDexChecksum) ^ header->checksum_;
220     ptr += header->file_size_;
221   }
222   return true;
223 }
224 
GetDexCanonicalLocation(const char * dex_location)225 std::string DexFileLoader::GetDexCanonicalLocation(const char* dex_location) {
226   CHECK_NE(dex_location, static_cast<const char*>(nullptr));
227   std::string base_location = GetBaseLocation(dex_location);
228   const char* suffix = dex_location + base_location.size();
229   DCHECK(suffix[0] == 0 || suffix[0] == kMultiDexSeparator);
230 #ifdef _WIN32
231   // Warning: No symbolic link processing here.
232   PLOG(WARNING) << "realpath is unsupported on Windows.";
233 #else
234   // Warning: Bionic implementation of realpath() allocates > 12KB on the stack.
235   // Do not run this code on a small stack, e.g. in signal handler.
236   UniqueCPtr<const char[]> path(realpath(base_location.c_str(), nullptr));
237   if (path != nullptr && path.get() != base_location) {
238     return std::string(path.get()) + suffix;
239   }
240 #endif
241   if (suffix[0] == 0) {
242     return base_location;
243   } else {
244     return dex_location;
245   }
246 }
247 
248 // All of the implementations here should be independent of the runtime.
249 
DexFileLoader(const uint8_t * base,size_t size,const std::string & location)250 DexFileLoader::DexFileLoader(const uint8_t* base, size_t size, const std::string& location)
251     : DexFileLoader(std::make_shared<MemoryDexFileContainer>(base, base + size), location) {}
252 
DexFileLoader(std::vector<uint8_t> && memory,const std::string & location)253 DexFileLoader::DexFileLoader(std::vector<uint8_t>&& memory, const std::string& location)
254     : DexFileLoader(std::make_shared<VectorContainer>(std::move(memory)), location) {}
255 
DexFileLoader(MemMap && mem_map,const std::string & location)256 DexFileLoader::DexFileLoader(MemMap&& mem_map, const std::string& location)
257     : DexFileLoader(std::make_shared<MemMapContainer>(std::move(mem_map)), location) {}
258 
OpenOne(size_t header_offset,uint32_t location_checksum,const OatDexFile * oat_dex_file,bool verify,bool verify_checksum,std::string * error_msg)259 std::unique_ptr<const DexFile> DexFileLoader::OpenOne(size_t header_offset,
260                                                       uint32_t location_checksum,
261                                                       const OatDexFile* oat_dex_file,
262                                                       bool verify,
263                                                       bool verify_checksum,
264                                                       std::string* error_msg) {
265   DEXFILE_SCOPED_TRACE(std::string("Open dex file ") + location_);
266 
267   uint32_t magic;
268   if (!InitAndReadMagic(header_offset, &magic, error_msg) || !MapRootContainer(error_msg)) {
269     DCHECK(!error_msg->empty());
270     return {};
271   }
272   DCHECK(root_container_ != nullptr);
273   DCHECK_LE(header_offset, root_container_->Size());
274   std::unique_ptr<const DexFile> dex_file = OpenCommon(root_container_,
275                                                        root_container_->Begin() + header_offset,
276                                                        root_container_->Size() - header_offset,
277                                                        location_,
278                                                        location_checksum,
279                                                        oat_dex_file,
280                                                        verify,
281                                                        verify_checksum,
282                                                        error_msg,
283                                                        nullptr);
284   return dex_file;
285 }
286 
InitAndReadMagic(size_t header_offset,uint32_t * magic,std::string * error_msg)287 bool DexFileLoader::InitAndReadMagic(size_t header_offset,
288                                      uint32_t* magic,
289                                      std::string* error_msg) {
290   if (root_container_ != nullptr) {
291     if (root_container_->Size() < header_offset ||
292         root_container_->Size() - header_offset < sizeof(uint32_t)) {
293       *error_msg = StringPrintf("Unable to open '%s' : Size is too small", location_.c_str());
294       return false;
295     }
296     *magic = *reinterpret_cast<const uint32_t*>(root_container_->Begin() + header_offset);
297   } else {
298     // Open the file if we have not been given the file-descriptor directly before.
299     if (!file_->IsValid()) {
300       CHECK(!filename_.empty());
301       owned_file_ = File(filename_, O_RDONLY, /* check_usage= */ false);
302       if (!owned_file_->IsValid()) {
303         *error_msg = StringPrintf("Unable to open '%s' : %s", filename_.c_str(), strerror(errno));
304         return false;
305       }
306       file_ = &owned_file_.value();
307     }
308     CHECK_EQ(header_offset, 0u);  // We always expect to read from the start of physical file.
309     if (!ReadMagicAndReset(file_->Fd(), magic, error_msg)) {
310       return false;
311     }
312   }
313   return true;
314 }
315 
MapRootContainer(std::string * error_msg)316 bool DexFileLoader::MapRootContainer(std::string* error_msg) {
317   if (root_container_ != nullptr) {
318     return true;
319   }
320 
321   CHECK(MemMap::IsInitialized());
322   CHECK(file_->IsValid());
323   struct stat sbuf;
324   memset(&sbuf, 0, sizeof(sbuf));
325   if (fstat(file_->Fd(), &sbuf) == -1) {
326     *error_msg = StringPrintf("DexFile: fstat '%s' failed: %s", filename_.c_str(), strerror(errno));
327     return false;
328   }
329   if (S_ISDIR(sbuf.st_mode)) {
330     *error_msg = StringPrintf("Attempt to mmap directory '%s'", filename_.c_str());
331     return false;
332   }
333   MemMap map = MemMap::MapFile(sbuf.st_size,
334                                PROT_READ,
335                                MAP_PRIVATE,
336                                file_->Fd(),
337                                0,
338                                /*low_4gb=*/false,
339                                filename_.c_str(),
340                                error_msg);
341   if (!map.IsValid()) {
342     DCHECK(!error_msg->empty());
343     return false;
344   }
345   root_container_ = std::make_shared<MemMapContainer>(std::move(map), /*is_file_map=*/true);
346   return true;
347 }
348 
Open(bool verify,bool verify_checksum,bool allow_no_dex_files,DexFileLoaderErrorCode * error_code,std::string * error_msg,std::vector<std::unique_ptr<const DexFile>> * dex_files)349 bool DexFileLoader::Open(bool verify,
350                          bool verify_checksum,
351                          bool allow_no_dex_files,
352                          DexFileLoaderErrorCode* error_code,
353                          std::string* error_msg,
354                          std::vector<std::unique_ptr<const DexFile>>* dex_files) {
355   DEXFILE_SCOPED_TRACE(std::string("Open dex file ") + location_);
356 
357   DCHECK(dex_files != nullptr) << "DexFile::Open: out-param is nullptr";
358 
359   uint32_t magic;
360   if (!InitAndReadMagic(/*header_offset=*/0, &magic, error_msg)) {
361     return false;
362   }
363 
364   if (IsZipMagic(magic)) {
365     std::unique_ptr<ZipArchive> zip_archive(
366         file_->IsValid() ?
367             ZipArchive::OpenFromOwnedFd(file_->Fd(), location_.c_str(), error_msg) :
368             ZipArchive::OpenFromMemory(
369                 root_container_->Begin(), root_container_->Size(), location_.c_str(), error_msg));
370     if (zip_archive.get() == nullptr) {
371       DCHECK(!error_msg->empty());
372       return false;
373     }
374     size_t multidex_count = 0;
375     for (size_t i = 0;; ++i) {
376       std::string name = GetMultiDexClassesDexName(i);
377       bool ok = OpenFromZipEntry(*zip_archive,
378                                  name.c_str(),
379                                  location_,
380                                  verify,
381                                  verify_checksum,
382                                  &multidex_count,
383                                  error_code,
384                                  error_msg,
385                                  dex_files);
386       if (!ok) {
387         // We keep opening consecutive dex entries as long as we can (until entry is not found).
388         if (*error_code == DexFileLoaderErrorCode::kEntryNotFound) {
389           // Success if we loaded at least one entry, or if empty zip is explicitly allowed.
390           return i > 0 || allow_no_dex_files;
391         }
392         return false;
393       }
394       if (i == kWarnOnManyDexFilesThreshold) {
395         LOG(WARNING) << location_ << " has in excess of " << kWarnOnManyDexFilesThreshold
396                      << " dex files. Please consider coalescing and shrinking the number to "
397                         " avoid runtime overhead.";
398       }
399     }
400   }
401   if (IsMagicValid(magic)) {
402     if (!MapRootContainer(error_msg)) {
403       return false;
404     }
405     DCHECK(root_container_ != nullptr);
406     size_t header_offset = 0;
407     for (size_t i = 0;; i++) {
408       std::string multidex_location = GetMultiDexLocation(i, location_.c_str());
409       std::unique_ptr<const DexFile> dex_file =
410           OpenCommon(root_container_,
411                      root_container_->Begin() + header_offset,
412                      root_container_->Size() - header_offset,
413                      multidex_location,
414                      /*location_checksum*/ {},  // Use default checksum from dex header.
415                      /*oat_dex_file=*/nullptr,
416                      verify,
417                      verify_checksum,
418                      error_msg,
419                      error_code);
420       if (dex_file == nullptr) {
421         return false;
422       }
423       dex_files->push_back(std::move(dex_file));
424       size_t file_size = dex_files->back()->GetHeader().file_size_;
425       CHECK_LE(file_size, root_container_->Size() - header_offset);
426       header_offset += file_size;
427       if (dex_files->back()->IsDexContainerLastEntry()) {
428         break;
429       }
430     }
431     return true;
432   }
433   *error_msg = StringPrintf("Expected valid zip or dex file");
434   return false;
435 }
436 
OpenCommon(std::shared_ptr<DexFileContainer> container,const uint8_t * base,size_t app_compat_size,const std::string & location,std::optional<uint32_t> location_checksum,const OatDexFile * oat_dex_file,bool verify,bool verify_checksum,std::string * error_msg,DexFileLoaderErrorCode * error_code)437 std::unique_ptr<DexFile> DexFileLoader::OpenCommon(std::shared_ptr<DexFileContainer> container,
438                                                    const uint8_t* base,
439                                                    size_t app_compat_size,
440                                                    const std::string& location,
441                                                    std::optional<uint32_t> location_checksum,
442                                                    const OatDexFile* oat_dex_file,
443                                                    bool verify,
444                                                    bool verify_checksum,
445                                                    std::string* error_msg,
446                                                    DexFileLoaderErrorCode* error_code) {
447   if (container == nullptr) {
448     // We should never pass null here, but use reasonable default for app compat anyway.
449     container = std::make_shared<MemoryDexFileContainer>(base, app_compat_size);
450   }
451   CHECK_GE(base, container->Begin());
452   CHECK_LE(base, container->End());
453   const size_t size = container->End() - base;
454   if (error_code != nullptr) {
455     *error_code = DexFileLoaderErrorCode::kDexFileError;
456   }
457   std::unique_ptr<DexFile> dex_file;
458   auto header = reinterpret_cast<const DexFile::Header*>(base);
459   if (size >= sizeof(StandardDexFile::Header) && StandardDexFile::IsMagicValid(base)) {
460     uint32_t checksum = location_checksum.value_or(header->checksum_);
461     dex_file.reset(new StandardDexFile(base, location, checksum, oat_dex_file, container));
462   } else if (size >= sizeof(CompactDexFile::Header) && CompactDexFile::IsMagicValid(base)) {
463     uint32_t checksum = location_checksum.value_or(header->checksum_);
464     dex_file.reset(new CompactDexFile(base, location, checksum, oat_dex_file, container));
465   } else {
466     *error_msg = StringPrintf("Invalid or truncated dex file '%s'", location.c_str());
467   }
468   if (dex_file == nullptr) {
469     *error_msg =
470         StringPrintf("Failed to open dex file '%s': %s", location.c_str(), error_msg->c_str());
471     return nullptr;
472   }
473   if (!dex_file->Init(error_msg)) {
474     dex_file.reset();
475     return nullptr;
476   }
477   // NB: Dex verifier does not understand the compact dex format.
478   if (verify && !dex_file->IsCompactDexFile()) {
479     DEXFILE_SCOPED_TRACE(std::string("Verify dex file ") + location);
480     if (!dex::Verify(dex_file.get(), location.c_str(), verify_checksum, error_msg)) {
481       if (error_code != nullptr) {
482         *error_code = DexFileLoaderErrorCode::kVerifyError;
483       }
484       return nullptr;
485     }
486   }
487   if (error_code != nullptr) {
488     *error_code = DexFileLoaderErrorCode::kNoError;
489   }
490   return dex_file;
491 }
492 
OpenFromZipEntry(const ZipArchive & zip_archive,const char * entry_name,const std::string & location,bool verify,bool verify_checksum,size_t * multidex_count,DexFileLoaderErrorCode * error_code,std::string * error_msg,std::vector<std::unique_ptr<const DexFile>> * dex_files) const493 bool DexFileLoader::OpenFromZipEntry(const ZipArchive& zip_archive,
494                                      const char* entry_name,
495                                      const std::string& location,
496                                      bool verify,
497                                      bool verify_checksum,
498                                      size_t* multidex_count,
499                                      DexFileLoaderErrorCode* error_code,
500                                      std::string* error_msg,
501                                      std::vector<std::unique_ptr<const DexFile>>* dex_files) const {
502   CHECK(!location.empty());
503   std::unique_ptr<ZipEntry> zip_entry(zip_archive.Find(entry_name, error_msg));
504   if (zip_entry == nullptr) {
505     *error_code = DexFileLoaderErrorCode::kEntryNotFound;
506     return false;
507   }
508   if (zip_entry->GetUncompressedLength() == 0) {
509     *error_msg = StringPrintf("Dex file '%s' has zero length", location.c_str());
510     *error_code = DexFileLoaderErrorCode::kDexFileError;
511     return false;
512   }
513 
514   CHECK(MemMap::IsInitialized());
515   MemMap map;
516   bool is_file_map = false;
517   if (file_->IsValid() && zip_entry->IsUncompressed()) {
518     if (!zip_entry->IsAlignedTo(alignof(DexFile::Header))) {
519       // Do not mmap unaligned ZIP entries because
520       // doing so would fail dex verification which requires 4 byte alignment.
521       LOG(WARNING) << "Can't mmap dex file " << location << "!" << entry_name << " directly; "
522                    << "please zipalign to " << alignof(DexFile::Header) << " bytes. "
523                    << "Falling back to extracting file.";
524     } else {
525       // Map uncompressed files within zip as file-backed to avoid a dirty copy.
526       map = zip_entry->MapDirectlyFromFile(location.c_str(), /*out*/ error_msg);
527       if (!map.IsValid()) {
528         LOG(WARNING) << "Can't mmap dex file " << location << "!" << entry_name << " directly; "
529                      << "is your ZIP file corrupted? Falling back to extraction.";
530         // Try again with Extraction which still has a chance of recovery.
531       }
532       is_file_map = true;
533     }
534   }
535   if (!map.IsValid()) {
536     DEXFILE_SCOPED_TRACE(std::string("Extract dex file ") + location);
537 
538     // Default path for compressed ZIP entries,
539     // and fallback for stored ZIP entries.
540     map = zip_entry->ExtractToMemMap(location.c_str(), entry_name, error_msg);
541   }
542   if (!map.IsValid()) {
543     *error_msg = StringPrintf("Failed to extract '%s' from '%s': %s", entry_name, location.c_str(),
544                               error_msg->c_str());
545     *error_code = DexFileLoaderErrorCode::kExtractToMemoryError;
546     return false;
547   }
548   auto container = std::make_shared<MemMapContainer>(std::move(map), is_file_map);
549   container->SetIsZip();
550   if (!container->DisableWrite()) {
551     *error_msg = StringPrintf("Failed to make dex file '%s' read only", location.c_str());
552     *error_code = DexFileLoaderErrorCode::kMakeReadOnlyError;
553     return false;
554   }
555 
556   size_t header_offset = 0;
557   for (size_t i = 0;; i++) {
558     std::string multidex_location = GetMultiDexLocation(*multidex_count, location.c_str());
559     ++(*multidex_count);
560     uint32_t multidex_checksum = zip_entry->GetCrc32() + i;
561     std::unique_ptr<const DexFile> dex_file = OpenCommon(container,
562                                                          container->Begin() + header_offset,
563                                                          container->Size() - header_offset,
564                                                          multidex_location,
565                                                          multidex_checksum,
566                                                          /*oat_dex_file=*/nullptr,
567                                                          verify,
568                                                          verify_checksum,
569                                                          error_msg,
570                                                          error_code);
571     if (dex_file == nullptr) {
572       return false;
573     }
574     if (dex_file->IsCompactDexFile()) {
575       *error_msg = StringPrintf("Can not open compact dex file from zip '%s'", location.c_str());
576       return false;
577     }
578     CHECK(dex_file->IsReadOnly()) << multidex_location;
579     dex_files->push_back(std::move(dex_file));
580     size_t file_size = dex_files->back()->GetHeader().file_size_;
581     CHECK_LE(file_size, container->Size() - header_offset);
582     header_offset += file_size;
583     if (dex_files->back()->IsDexContainerLastEntry()) {
584       break;
585     }
586   }
587   return true;
588 }
589 
Open(const uint8_t * base,size_t size,const std::string & location,uint32_t location_checksum,const OatDexFile * oat_dex_file,bool verify,bool verify_checksum,std::string * error_msg,std::unique_ptr<DexFileContainer> container) const590 std::unique_ptr<const DexFile> DexFileLoader::Open(
591     const uint8_t* base,
592     size_t size,
593     const std::string& location,
594     uint32_t location_checksum,
595     const OatDexFile* oat_dex_file,
596     bool verify,
597     bool verify_checksum,
598     std::string* error_msg,
599     std::unique_ptr<DexFileContainer> container) const {
600   return OpenCommon(base,
601                     size,
602                     /*data_base=*/nullptr,
603                     /*data_size=*/0,
604                     location,
605                     location_checksum,
606                     oat_dex_file,
607                     verify,
608                     verify_checksum,
609                     error_msg,
610                     std::move(container),
611                     /*verify_result=*/nullptr);
612 }
613 
OpenCommon(const uint8_t * base,size_t size,const uint8_t * data_base,size_t data_size,const std::string & location,uint32_t location_checksum,const OatDexFile * oat_dex_file,bool verify,bool verify_checksum,std::string * error_msg,std::unique_ptr<DexFileContainer> old_container,VerifyResult * verify_result)614 std::unique_ptr<DexFile> DexFileLoader::OpenCommon(const uint8_t* base,
615                                                    size_t size,
616                                                    const uint8_t* data_base,
617                                                    size_t data_size,
618                                                    const std::string& location,
619                                                    uint32_t location_checksum,
620                                                    const OatDexFile* oat_dex_file,
621                                                    bool verify,
622                                                    bool verify_checksum,
623                                                    std::string* error_msg,
624                                                    std::unique_ptr<DexFileContainer> old_container,
625                                                    VerifyResult* verify_result) {
626   CHECK(data_base == base || data_base == nullptr);
627   CHECK(data_size == size || data_size == 0);
628   CHECK(verify_result == nullptr);
629 
630   // The provided container probably does implent the new API.
631   // We don't use it, but let's at least call its destructor.
632   struct NewContainer : public MemoryDexFileContainer {
633     using MemoryDexFileContainer::MemoryDexFileContainer;  // ctor.
634     std::unique_ptr<DexFileContainer> old_container_ = nullptr;
635   };
636   auto new_container = std::make_shared<NewContainer>(base, size);
637   new_container->old_container_ = std::move(old_container);
638 
639   return OpenCommon(std::move(new_container),
640                     base,
641                     size,
642                     location,
643                     location_checksum,
644                     oat_dex_file,
645                     verify,
646                     verify_checksum,
647                     error_msg,
648                     /*error_code=*/nullptr);
649 }
650 
651 }  // namespace art
652