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