class_loader_context.cc revision 095c6c96236476b605b3ac672f6d2b8c151e9479
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 "class_loader_context.h"
18
19#include <stdlib.h>
20
21#include "android-base/file.h"
22#include "art_field-inl.h"
23#include "base/dchecked_vector.h"
24#include "base/stl_util.h"
25#include "class_linker.h"
26#include "class_loader_utils.h"
27#include "dex_file.h"
28#include "dex_file_loader.h"
29#include "handle_scope-inl.h"
30#include "jni_internal.h"
31#include "oat_file_assistant.h"
32#include "obj_ptr-inl.h"
33#include "runtime.h"
34#include "scoped_thread_state_change-inl.h"
35#include "thread.h"
36#include "well_known_classes.h"
37
38namespace art {
39
40static constexpr char kPathClassLoaderString[] = "PCL";
41static constexpr char kDelegateLastClassLoaderString[] = "DLC";
42static constexpr char kClassLoaderOpeningMark = '[';
43static constexpr char kClassLoaderClosingMark = ']';
44static constexpr char kClassLoaderSeparator = ';';
45static constexpr char kClasspathSeparator = ':';
46static constexpr char kDexFileChecksumSeparator = '*';
47
48ClassLoaderContext::ClassLoaderContext()
49    : special_shared_library_(false),
50      dex_files_open_attempted_(false),
51      dex_files_open_result_(false),
52      owns_the_dex_files_(true) {}
53
54ClassLoaderContext::ClassLoaderContext(bool owns_the_dex_files)
55    : special_shared_library_(false),
56      dex_files_open_attempted_(true),
57      dex_files_open_result_(true),
58      owns_the_dex_files_(owns_the_dex_files) {}
59
60ClassLoaderContext::~ClassLoaderContext() {
61  if (!owns_the_dex_files_) {
62    // If the context does not own the dex/oat files release the unique pointers to
63    // make sure we do not de-allocate them.
64    for (ClassLoaderInfo& info : class_loader_chain_) {
65      for (std::unique_ptr<OatFile>& oat_file : info.opened_oat_files) {
66        oat_file.release();
67      }
68      for (std::unique_ptr<const DexFile>& dex_file : info.opened_dex_files) {
69        dex_file.release();
70      }
71    }
72  }
73}
74
75std::unique_ptr<ClassLoaderContext> ClassLoaderContext::Default() {
76  return Create("");
77}
78
79std::unique_ptr<ClassLoaderContext> ClassLoaderContext::Create(const std::string& spec) {
80  std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext());
81  if (result->Parse(spec)) {
82    return result;
83  } else {
84    return nullptr;
85  }
86}
87
88// The expected format is: "ClassLoaderType1[ClasspathElem1*Checksum1:ClasspathElem2*Checksum2...]".
89// The checksum part of the format is expected only if parse_cheksums is true.
90bool ClassLoaderContext::ParseClassLoaderSpec(const std::string& class_loader_spec,
91                                              ClassLoaderType class_loader_type,
92                                              bool parse_checksums) {
93  const char* class_loader_type_str = GetClassLoaderTypeName(class_loader_type);
94  size_t type_str_size = strlen(class_loader_type_str);
95
96  CHECK_EQ(0, class_loader_spec.compare(0, type_str_size, class_loader_type_str));
97
98  // Check the opening and closing markers.
99  if (class_loader_spec[type_str_size] != kClassLoaderOpeningMark) {
100    return false;
101  }
102  if (class_loader_spec[class_loader_spec.length() - 1] != kClassLoaderClosingMark) {
103    return false;
104  }
105
106  // At this point we know the format is ok; continue and extract the classpath.
107  // Note that class loaders with an empty class path are allowed.
108  std::string classpath = class_loader_spec.substr(type_str_size + 1,
109                                                   class_loader_spec.length() - type_str_size - 2);
110
111  class_loader_chain_.push_back(ClassLoaderInfo(class_loader_type));
112
113  if (!parse_checksums) {
114    Split(classpath, kClasspathSeparator, &class_loader_chain_.back().classpath);
115  } else {
116    std::vector<std::string> classpath_elements;
117    Split(classpath, kClasspathSeparator, &classpath_elements);
118    for (const std::string& element : classpath_elements) {
119      std::vector<std::string> dex_file_with_checksum;
120      Split(element, kDexFileChecksumSeparator, &dex_file_with_checksum);
121      if (dex_file_with_checksum.size() != 2) {
122        return false;
123      }
124      uint32_t checksum = 0;
125      if (!ParseInt(dex_file_with_checksum[1].c_str(), &checksum)) {
126        return false;
127      }
128      class_loader_chain_.back().classpath.push_back(dex_file_with_checksum[0]);
129      class_loader_chain_.back().checksums.push_back(checksum);
130    }
131  }
132
133  return true;
134}
135
136// Extracts the class loader type from the given spec.
137// Return ClassLoaderContext::kInvalidClassLoader if the class loader type is not
138// recognized.
139ClassLoaderContext::ClassLoaderType
140ClassLoaderContext::ExtractClassLoaderType(const std::string& class_loader_spec) {
141  const ClassLoaderType kValidTypes[] = {kPathClassLoader, kDelegateLastClassLoader};
142  for (const ClassLoaderType& type : kValidTypes) {
143    const char* type_str = GetClassLoaderTypeName(type);
144    if (class_loader_spec.compare(0, strlen(type_str), type_str) == 0) {
145      return type;
146    }
147  }
148  return kInvalidClassLoader;
149}
150
151// The format: ClassLoaderType1[ClasspathElem1:ClasspathElem2...];ClassLoaderType2[...]...
152// ClassLoaderType is either "PCL" (PathClassLoader) or "DLC" (DelegateLastClassLoader).
153// ClasspathElem is the path of dex/jar/apk file.
154bool ClassLoaderContext::Parse(const std::string& spec, bool parse_checksums) {
155  if (spec.empty()) {
156    // By default we load the dex files in a PathClassLoader.
157    // So an empty spec is equivalent to an empty PathClassLoader (this happens when running
158    // tests)
159    class_loader_chain_.push_back(ClassLoaderInfo(kPathClassLoader));
160    return true;
161  }
162
163  // Stop early if we detect the special shared library, which may be passed as the classpath
164  // for dex2oat when we want to skip the shared libraries check.
165  if (spec == OatFile::kSpecialSharedLibrary) {
166    LOG(INFO) << "The ClassLoaderContext is a special shared library.";
167    special_shared_library_ = true;
168    return true;
169  }
170
171  std::vector<std::string> class_loaders;
172  Split(spec, kClassLoaderSeparator, &class_loaders);
173
174  for (const std::string& class_loader : class_loaders) {
175    ClassLoaderType type = ExtractClassLoaderType(class_loader);
176    if (type == kInvalidClassLoader) {
177      LOG(ERROR) << "Invalid class loader type: " << class_loader;
178      return false;
179    }
180    if (!ParseClassLoaderSpec(class_loader, type, parse_checksums)) {
181      LOG(ERROR) << "Invalid class loader spec: " << class_loader;
182      return false;
183    }
184  }
185  return true;
186}
187
188// Opens requested class path files and appends them to opened_dex_files. If the dex files have
189// been stripped, this opens them from their oat files (which get added to opened_oat_files).
190bool ClassLoaderContext::OpenDexFiles(InstructionSet isa, const std::string& classpath_dir) {
191  if (dex_files_open_attempted_) {
192    // Do not attempt to re-open the files if we already tried.
193    return dex_files_open_result_;
194  }
195
196  dex_files_open_attempted_ = true;
197  // Assume we can open all dex files. If not, we will set this to false as we go.
198  dex_files_open_result_ = true;
199
200  if (special_shared_library_) {
201    // Nothing to open if the context is a special shared library.
202    return true;
203  }
204
205  // Note that we try to open all dex files even if some fail.
206  // We may get resource-only apks which we cannot load.
207  // TODO(calin): Refine the dex opening interface to be able to tell if an archive contains
208  // no dex files. So that we can distinguish the real failures...
209  for (ClassLoaderInfo& info : class_loader_chain_) {
210    size_t opened_dex_files_index = info.opened_dex_files.size();
211    for (const std::string& cp_elem : info.classpath) {
212      // If path is relative, append it to the provided base directory.
213      std::string raw_location = cp_elem;
214      if (raw_location[0] != '/' && !classpath_dir.empty()) {
215        raw_location = classpath_dir + '/' + raw_location;
216      }
217
218      std::string location;  // the real location of the class path element.
219
220      if (!android::base::Realpath(raw_location, &location)) {
221        // If we can't get the realpath of the location there might be something wrong with the
222        // classpath (maybe the file was deleted).
223        // Do not continue in this case and return false.
224        PLOG(WARNING) << "Could not get the realpath of dex location " << raw_location;
225        return false;
226      }
227
228      std::string error_msg;
229      // When opening the dex files from the context we expect their checksum to match their
230      // contents. So pass true to verify_checksum.
231      if (!DexFileLoader::Open(location.c_str(),
232                               location.c_str(),
233                               /*verify*/ true,
234                               /*verify_checksum*/ true,
235                               &error_msg,
236                               &info.opened_dex_files)) {
237        // If we fail to open the dex file because it's been stripped, try to open the dex file
238        // from its corresponding oat file.
239        // This could happen when we need to recompile a pre-build whose dex code has been stripped.
240        // (for example, if the pre-build is only quicken and we want to re-compile it
241        // speed-profile).
242        // TODO(calin): Use the vdex directly instead of going through the oat file.
243        OatFileAssistant oat_file_assistant(location.c_str(), isa, false);
244        std::unique_ptr<OatFile> oat_file(oat_file_assistant.GetBestOatFile());
245        std::vector<std::unique_ptr<const DexFile>> oat_dex_files;
246        if (oat_file != nullptr &&
247            OatFileAssistant::LoadDexFiles(*oat_file, location, &oat_dex_files)) {
248          info.opened_oat_files.push_back(std::move(oat_file));
249          info.opened_dex_files.insert(info.opened_dex_files.end(),
250                                       std::make_move_iterator(oat_dex_files.begin()),
251                                       std::make_move_iterator(oat_dex_files.end()));
252        } else {
253          LOG(WARNING) << "Could not open dex files from location: " << location;
254          dex_files_open_result_ = false;
255        }
256      }
257    }
258
259    // We finished opening the dex files from the classpath.
260    // Now update the classpath and the checksum with the locations of the dex files.
261    //
262    // We do this because initially the classpath contains the paths of the dex files; and
263    // some of them might be multi-dexes. So in order to have a consistent view we replace all the
264    // file paths with the actual dex locations being loaded.
265    // This will allow the context to VerifyClassLoaderContextMatch which expects or multidex
266    // location in the class paths.
267    // Note that this will also remove the paths that could not be opened.
268    info.classpath.clear();
269    info.checksums.clear();
270    for (size_t k = opened_dex_files_index; k < info.opened_dex_files.size(); k++) {
271      std::unique_ptr<const DexFile>& dex = info.opened_dex_files[k];
272      info.classpath.push_back(dex->GetLocation());
273      info.checksums.push_back(dex->GetLocationChecksum());
274    }
275  }
276
277  return dex_files_open_result_;
278}
279
280bool ClassLoaderContext::RemoveLocationsFromClassPaths(
281    const dchecked_vector<std::string>& locations) {
282  CHECK(!dex_files_open_attempted_)
283      << "RemoveLocationsFromClasspaths cannot be call after OpenDexFiles";
284
285  std::set<std::string> canonical_locations;
286  for (const std::string& location : locations) {
287    canonical_locations.insert(DexFileLoader::GetDexCanonicalLocation(location.c_str()));
288  }
289  bool removed_locations = false;
290  for (ClassLoaderInfo& info : class_loader_chain_) {
291    size_t initial_size = info.classpath.size();
292    auto kept_it = std::remove_if(
293        info.classpath.begin(),
294        info.classpath.end(),
295        [canonical_locations](const std::string& location) {
296            return ContainsElement(canonical_locations,
297                                   DexFileLoader::GetDexCanonicalLocation(location.c_str()));
298        });
299    info.classpath.erase(kept_it, info.classpath.end());
300    if (initial_size != info.classpath.size()) {
301      removed_locations = true;
302    }
303  }
304  return removed_locations;
305}
306
307std::string ClassLoaderContext::EncodeContextForDex2oat(const std::string& base_dir) const {
308  return EncodeContext(base_dir, /*for_dex2oat*/ true);
309}
310
311std::string ClassLoaderContext::EncodeContextForOatFile(const std::string& base_dir) const {
312  return EncodeContext(base_dir, /*for_dex2oat*/ false);
313}
314
315std::string ClassLoaderContext::EncodeContext(const std::string& base_dir,
316                                              bool for_dex2oat) const {
317  CheckDexFilesOpened("EncodeContextForOatFile");
318  if (special_shared_library_) {
319    return OatFile::kSpecialSharedLibrary;
320  }
321
322  std::ostringstream out;
323  if (class_loader_chain_.empty()) {
324    // We can get in this situation if the context was created with a class path containing the
325    // source dex files which were later removed (happens during run-tests).
326    out << GetClassLoaderTypeName(kPathClassLoader)
327        << kClassLoaderOpeningMark
328        << kClassLoaderClosingMark;
329    return out.str();
330  }
331
332  for (size_t i = 0; i < class_loader_chain_.size(); i++) {
333    const ClassLoaderInfo& info = class_loader_chain_[i];
334    if (i > 0) {
335      out << kClassLoaderSeparator;
336    }
337    out << GetClassLoaderTypeName(info.type);
338    out << kClassLoaderOpeningMark;
339    std::set<std::string> seen_locations;
340    for (size_t k = 0; k < info.opened_dex_files.size(); k++) {
341      const std::unique_ptr<const DexFile>& dex_file = info.opened_dex_files[k];
342      if (for_dex2oat) {
343        // dex2oat only needs the base location. It cannot accept multidex locations.
344        // So ensure we only add each file once.
345        bool new_insert = seen_locations.insert(
346            DexFileLoader::GetBaseLocation(dex_file->GetLocation())).second;
347        if (!new_insert) {
348          continue;
349        }
350      }
351      const std::string& location = dex_file->GetLocation();
352      if (k > 0) {
353        out << kClasspathSeparator;
354      }
355      // Find paths that were relative and convert them back from absolute.
356      if (!base_dir.empty() && location.substr(0, base_dir.length()) == base_dir) {
357        out << location.substr(base_dir.length() + 1).c_str();
358      } else {
359        out << dex_file->GetLocation().c_str();
360      }
361      // dex2oat does not need the checksums.
362      if (!for_dex2oat) {
363        out << kDexFileChecksumSeparator;
364        out << dex_file->GetLocationChecksum();
365      }
366    }
367    out << kClassLoaderClosingMark;
368  }
369  return out.str();
370}
371
372jobject ClassLoaderContext::CreateClassLoader(
373    const std::vector<const DexFile*>& compilation_sources) const {
374  CheckDexFilesOpened("CreateClassLoader");
375
376  Thread* self = Thread::Current();
377  ScopedObjectAccess soa(self);
378
379  ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
380
381  if (class_loader_chain_.empty()) {
382    return class_linker->CreatePathClassLoader(self, compilation_sources);
383  }
384
385  // Create the class loaders starting from the top most parent (the one on the last position
386  // in the chain) but omit the first class loader which will contain the compilation_sources and
387  // needs special handling.
388  jobject current_parent = nullptr;  // the starting parent is the BootClassLoader.
389  for (size_t i = class_loader_chain_.size() - 1; i > 0; i--) {
390    std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(
391        class_loader_chain_[i].opened_dex_files);
392    current_parent = class_linker->CreateWellKnownClassLoader(
393        self,
394        class_path_files,
395        GetClassLoaderClass(class_loader_chain_[i].type),
396        current_parent);
397  }
398
399  // We set up all the parents. Move on to create the first class loader.
400  // Its classpath comes first, followed by compilation sources. This ensures that whenever
401  // we need to resolve classes from it the classpath elements come first.
402
403  std::vector<const DexFile*> first_class_loader_classpath = MakeNonOwningPointerVector(
404      class_loader_chain_[0].opened_dex_files);
405  first_class_loader_classpath.insert(first_class_loader_classpath.end(),
406                                    compilation_sources.begin(),
407                                    compilation_sources.end());
408
409  return class_linker->CreateWellKnownClassLoader(
410      self,
411      first_class_loader_classpath,
412      GetClassLoaderClass(class_loader_chain_[0].type),
413      current_parent);
414}
415
416std::vector<const DexFile*> ClassLoaderContext::FlattenOpenedDexFiles() const {
417  CheckDexFilesOpened("FlattenOpenedDexFiles");
418
419  std::vector<const DexFile*> result;
420  for (const ClassLoaderInfo& info : class_loader_chain_) {
421    for (const std::unique_ptr<const DexFile>& dex_file : info.opened_dex_files) {
422      result.push_back(dex_file.get());
423    }
424  }
425  return result;
426}
427
428const char* ClassLoaderContext::GetClassLoaderTypeName(ClassLoaderType type) {
429  switch (type) {
430    case kPathClassLoader: return kPathClassLoaderString;
431    case kDelegateLastClassLoader: return kDelegateLastClassLoaderString;
432    default:
433      LOG(FATAL) << "Invalid class loader type " << type;
434      UNREACHABLE();
435  }
436}
437
438void ClassLoaderContext::CheckDexFilesOpened(const std::string& calling_method) const {
439  CHECK(dex_files_open_attempted_)
440      << "Dex files were not successfully opened before the call to " << calling_method
441      << "attempt=" << dex_files_open_attempted_ << ", result=" << dex_files_open_result_;
442}
443
444// Collects the dex files from the give Java dex_file object. Only the dex files with
445// at least 1 class are collected. If a null java_dex_file is passed this method does nothing.
446static bool CollectDexFilesFromJavaDexFile(ObjPtr<mirror::Object> java_dex_file,
447                                           ArtField* const cookie_field,
448                                           std::vector<const DexFile*>* out_dex_files)
449      REQUIRES_SHARED(Locks::mutator_lock_) {
450  if (java_dex_file == nullptr) {
451    return true;
452  }
453  // On the Java side, the dex files are stored in the cookie field.
454  mirror::LongArray* long_array = cookie_field->GetObject(java_dex_file)->AsLongArray();
455  if (long_array == nullptr) {
456    // This should never happen so log a warning.
457    LOG(ERROR) << "Unexpected null cookie";
458    return false;
459  }
460  int32_t long_array_size = long_array->GetLength();
461  // Index 0 from the long array stores the oat file. The dex files start at index 1.
462  for (int32_t j = 1; j < long_array_size; ++j) {
463    const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
464        long_array->GetWithoutChecks(j)));
465    if (cp_dex_file != nullptr && cp_dex_file->NumClassDefs() > 0) {
466      // TODO(calin): It's unclear why the dex files with no classes are skipped here and when
467      // cp_dex_file can be null.
468      out_dex_files->push_back(cp_dex_file);
469    }
470  }
471  return true;
472}
473
474// Collects all the dex files loaded by the given class loader.
475// Returns true for success or false if an unexpected state is discovered (e.g. a null dex cookie,
476// a null list of dex elements or a null dex element).
477static bool CollectDexFilesFromSupportedClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
478                                                    Handle<mirror::ClassLoader> class_loader,
479                                                    std::vector<const DexFile*>* out_dex_files)
480      REQUIRES_SHARED(Locks::mutator_lock_) {
481  CHECK(IsPathOrDexClassLoader(soa, class_loader) || IsDelegateLastClassLoader(soa, class_loader));
482
483  // All supported class loaders inherit from BaseDexClassLoader.
484  // We need to get the DexPathList and loop through it.
485  ArtField* const cookie_field =
486      jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
487  ArtField* const dex_file_field =
488      jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
489  ObjPtr<mirror::Object> dex_path_list =
490      jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList)->
491          GetObject(class_loader.Get());
492  CHECK(cookie_field != nullptr);
493  CHECK(dex_file_field != nullptr);
494  if (dex_path_list == nullptr) {
495    // This may be null if the current class loader is under construction and it does not
496    // have its fields setup yet.
497    return true;
498  }
499  // DexPathList has an array dexElements of Elements[] which each contain a dex file.
500  ObjPtr<mirror::Object> dex_elements_obj =
501      jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
502          GetObject(dex_path_list);
503  // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
504  // at the mCookie which is a DexFile vector.
505  if (dex_elements_obj == nullptr) {
506    // TODO(calin): It's unclear if we should just assert here. For now be prepared for the worse
507    // and assume we have no elements.
508    return true;
509  } else {
510    StackHandleScope<1> hs(soa.Self());
511    Handle<mirror::ObjectArray<mirror::Object>> dex_elements(
512        hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>()));
513    for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
514      mirror::Object* element = dex_elements->GetWithoutChecks(i);
515      if (element == nullptr) {
516        // Should never happen, log an error and break.
517        // TODO(calin): It's unclear if we should just assert here.
518        // This code was propagated to oat_file_manager from the class linker where it would
519        // throw a NPE. For now, return false which will mark this class loader as unsupported.
520        LOG(ERROR) << "Unexpected null in the dex element list";
521        return false;
522      }
523      ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
524      if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
525        return false;
526      }
527    }
528  }
529
530  return true;
531}
532
533static bool GetDexFilesFromDexElementsArray(
534    ScopedObjectAccessAlreadyRunnable& soa,
535    Handle<mirror::ObjectArray<mirror::Object>> dex_elements,
536    std::vector<const DexFile*>* out_dex_files) REQUIRES_SHARED(Locks::mutator_lock_) {
537  DCHECK(dex_elements != nullptr);
538
539  ArtField* const cookie_field =
540      jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
541  ArtField* const dex_file_field =
542      jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
543  ObjPtr<mirror::Class> const element_class = soa.Decode<mirror::Class>(
544      WellKnownClasses::dalvik_system_DexPathList__Element);
545  ObjPtr<mirror::Class> const dexfile_class = soa.Decode<mirror::Class>(
546      WellKnownClasses::dalvik_system_DexFile);
547
548  for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
549    mirror::Object* element = dex_elements->GetWithoutChecks(i);
550    // We can hit a null element here because this is invoked with a partially filled dex_elements
551    // array from DexPathList. DexPathList will open each dex sequentially, each time passing the
552    // list of dex files which were opened before.
553    if (element == nullptr) {
554      continue;
555    }
556
557    // We support this being dalvik.system.DexPathList$Element and dalvik.system.DexFile.
558    // TODO(calin): Code caried over oat_file_manager: supporting both classes seem to be
559    // a historical glitch. All the java code opens dex files using an array of Elements.
560    ObjPtr<mirror::Object> dex_file;
561    if (element_class == element->GetClass()) {
562      dex_file = dex_file_field->GetObject(element);
563    } else if (dexfile_class == element->GetClass()) {
564      dex_file = element;
565    } else {
566      LOG(ERROR) << "Unsupported element in dex_elements: "
567                 << mirror::Class::PrettyClass(element->GetClass());
568      return false;
569    }
570
571    if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
572      return false;
573    }
574  }
575  return true;
576}
577
578// Adds the `class_loader` info to the `context`.
579// The dex file present in `dex_elements` array (if not null) will be added at the end of
580// the classpath.
581// This method is recursive (w.r.t. the class loader parent) and will stop once it reaches the
582// BootClassLoader. Note that the class loader chain is expected to be short.
583bool ClassLoaderContext::AddInfoToContextFromClassLoader(
584      ScopedObjectAccessAlreadyRunnable& soa,
585      Handle<mirror::ClassLoader> class_loader,
586      Handle<mirror::ObjectArray<mirror::Object>> dex_elements)
587    REQUIRES_SHARED(Locks::mutator_lock_) {
588  if (ClassLinker::IsBootClassLoader(soa, class_loader.Get())) {
589    // Nothing to do for the boot class loader as we don't add its dex files to the context.
590    return true;
591  }
592
593  ClassLoaderContext::ClassLoaderType type;
594  if (IsPathOrDexClassLoader(soa, class_loader)) {
595    type = kPathClassLoader;
596  } else if (IsDelegateLastClassLoader(soa, class_loader)) {
597    type = kDelegateLastClassLoader;
598  } else {
599    LOG(WARNING) << "Unsupported class loader";
600    return false;
601  }
602
603  // Inspect the class loader for its dex files.
604  std::vector<const DexFile*> dex_files_loaded;
605  CollectDexFilesFromSupportedClassLoader(soa, class_loader, &dex_files_loaded);
606
607  // If we have a dex_elements array extract its dex elements now.
608  // This is used in two situations:
609  //   1) when a new ClassLoader is created DexPathList will open each dex file sequentially
610  //      passing the list of already open dex files each time. This ensures that we see the
611  //      correct context even if the ClassLoader under construction is not fully build.
612  //   2) when apk splits are loaded on the fly, the framework will load their dex files by
613  //      appending them to the current class loader. When the new code paths are loaded in
614  //      BaseDexClassLoader, the paths already present in the class loader will be passed
615  //      in the dex_elements array.
616  if (dex_elements != nullptr) {
617    GetDexFilesFromDexElementsArray(soa, dex_elements, &dex_files_loaded);
618  }
619
620  class_loader_chain_.push_back(ClassLoaderContext::ClassLoaderInfo(type));
621  ClassLoaderInfo& info = class_loader_chain_.back();
622  for (const DexFile* dex_file : dex_files_loaded) {
623    info.classpath.push_back(dex_file->GetLocation());
624    info.checksums.push_back(dex_file->GetLocationChecksum());
625    info.opened_dex_files.emplace_back(dex_file);
626  }
627
628  // We created the ClassLoaderInfo for the current loader. Move on to its parent.
629
630  StackHandleScope<1> hs(Thread::Current());
631  Handle<mirror::ClassLoader> parent = hs.NewHandle(class_loader->GetParent());
632
633  // Note that dex_elements array is null here. The elements are considered to be part of the
634  // current class loader and are not passed to the parents.
635  ScopedNullHandle<mirror::ObjectArray<mirror::Object>> null_dex_elements;
636  return AddInfoToContextFromClassLoader(soa, parent, null_dex_elements);
637}
638
639std::unique_ptr<ClassLoaderContext> ClassLoaderContext::CreateContextForClassLoader(
640    jobject class_loader,
641    jobjectArray dex_elements) {
642  CHECK(class_loader != nullptr);
643
644  ScopedObjectAccess soa(Thread::Current());
645  StackHandleScope<2> hs(soa.Self());
646  Handle<mirror::ClassLoader> h_class_loader =
647      hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader));
648  Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements =
649      hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements));
650
651  std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext(/*owns_the_dex_files*/ false));
652  if (result->AddInfoToContextFromClassLoader(soa, h_class_loader, h_dex_elements)) {
653    return result;
654  } else {
655    return nullptr;
656  }
657}
658
659static bool IsAbsoluteLocation(const std::string& location) {
660  return !location.empty() && location[0] == '/';
661}
662
663bool ClassLoaderContext::VerifyClassLoaderContextMatch(const std::string& context_spec) const {
664  DCHECK(dex_files_open_attempted_);
665  DCHECK(dex_files_open_result_);
666
667  ClassLoaderContext expected_context;
668  if (!expected_context.Parse(context_spec, /*parse_checksums*/ true)) {
669    LOG(WARNING) << "Invalid class loader context: " << context_spec;
670    return false;
671  }
672
673  // Special shared library contexts always match. They essentially instruct the runtime
674  // to ignore the class path check because the oat file is known to be loaded in different
675  // contexts. OatFileManager will further verify if the oat file can be loaded based on the
676  // collision check.
677  if (special_shared_library_ || expected_context.special_shared_library_) {
678    return true;
679  }
680
681  if (expected_context.class_loader_chain_.size() != class_loader_chain_.size()) {
682    LOG(WARNING) << "ClassLoaderContext size mismatch. expected="
683        << expected_context.class_loader_chain_.size()
684        << ", actual=" << class_loader_chain_.size()
685        << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
686    return false;
687  }
688
689  for (size_t i = 0; i < class_loader_chain_.size(); i++) {
690    const ClassLoaderInfo& info = class_loader_chain_[i];
691    const ClassLoaderInfo& expected_info = expected_context.class_loader_chain_[i];
692    if (info.type != expected_info.type) {
693      LOG(WARNING) << "ClassLoaderContext type mismatch for position " << i
694          << ". expected=" << GetClassLoaderTypeName(expected_info.type)
695          << ", found=" << GetClassLoaderTypeName(info.type)
696          << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
697      return false;
698    }
699    if (info.classpath.size() != expected_info.classpath.size()) {
700      LOG(WARNING) << "ClassLoaderContext classpath size mismatch for position " << i
701            << ". expected=" << expected_info.classpath.size()
702            << ", found=" << info.classpath.size()
703            << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
704      return false;
705    }
706
707    DCHECK_EQ(info.classpath.size(), info.checksums.size());
708    DCHECK_EQ(expected_info.classpath.size(), expected_info.checksums.size());
709
710    for (size_t k = 0; k < info.classpath.size(); k++) {
711      // Compute the dex location that must be compared.
712      // We shouldn't do a naive comparison `info.classpath[k] == expected_info.classpath[k]`
713      // because even if they refer to the same file, one could be encoded as a relative location
714      // and the other as an absolute one.
715      bool is_dex_name_absolute = IsAbsoluteLocation(info.classpath[k]);
716      bool is_expected_dex_name_absolute = IsAbsoluteLocation(expected_info.classpath[k]);
717      std::string dex_name;
718      std::string expected_dex_name;
719
720      if (is_dex_name_absolute == is_expected_dex_name_absolute) {
721        // If both locations are absolute or relative then compare them as they are.
722        // This is usually the case for: shared libraries and secondary dex files.
723        dex_name = info.classpath[k];
724        expected_dex_name = expected_info.classpath[k];
725      } else if (is_dex_name_absolute) {
726        // The runtime name is absolute but the compiled name (the expected one) is relative.
727        // This is the case for split apks which depend on base or on other splits.
728        dex_name = info.classpath[k];
729        expected_dex_name = OatFile::ResolveRelativeEncodedDexLocation(
730            info.classpath[k].c_str(), expected_info.classpath[k]);
731      } else {
732        // The runtime name is relative but the compiled name is absolute.
733        // There is no expected use case that would end up here as dex files are always loaded
734        // with their absolute location. However, be tolerant and do the best effort (in case
735        // there are unexpected new use case...).
736        DCHECK(is_expected_dex_name_absolute);
737        dex_name = OatFile::ResolveRelativeEncodedDexLocation(
738            expected_info.classpath[k].c_str(), info.classpath[k]);
739        expected_dex_name = expected_info.classpath[k];
740      }
741
742      // Compare the locations.
743      if (dex_name != expected_dex_name) {
744        LOG(WARNING) << "ClassLoaderContext classpath element mismatch for position " << i
745            << ". expected=" << expected_info.classpath[k]
746            << ", found=" << info.classpath[k]
747            << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
748        return false;
749      }
750
751      // Compare the checksums.
752      if (info.checksums[k] != expected_info.checksums[k]) {
753        LOG(WARNING) << "ClassLoaderContext classpath element checksum mismatch for position " << i
754                     << ". expected=" << expected_info.checksums[k]
755                     << ", found=" << info.checksums[k]
756                     << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
757        return false;
758      }
759    }
760  }
761  return true;
762}
763
764jclass ClassLoaderContext::GetClassLoaderClass(ClassLoaderType type) {
765  switch (type) {
766    case kPathClassLoader: return WellKnownClasses::dalvik_system_PathClassLoader;
767    case kDelegateLastClassLoader: return WellKnownClasses::dalvik_system_DelegateLastClassLoader;
768    case kInvalidClassLoader: break;  // will fail after the switch.
769  }
770  LOG(FATAL) << "Invalid class loader type " << type;
771  UNREACHABLE();
772}
773
774}  // namespace art
775
776