blob: 88e82dd2858711ed81a4318c9ca4fa4879402c57 [file] [log] [blame]
Calin Juravle87e2cb62017-06-13 21:48:45 -07001/*
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#ifndef ART_RUNTIME_CLASS_LOADER_CONTEXT_H_
18#define ART_RUNTIME_CLASS_LOADER_CONTEXT_H_
19
20#include <string>
21#include <vector>
Calin Juravlea63a2e92020-04-15 20:02:00 -070022#include <set>
Calin Juravle87e2cb62017-06-13 21:48:45 -070023
24#include "arch/instruction_set.h"
25#include "base/dchecked_vector.h"
Mathieu Chartieradc90862018-05-11 13:03:06 -070026#include "dex/dex_file.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070027#include "handle_scope.h"
28#include "mirror/class_loader.h"
Mathieu Chartieradc90862018-05-11 13:03:06 -070029#include "oat_file.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070030#include "scoped_thread_state_change.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070031
32namespace art {
33
34class DexFile;
35class OatFile;
36
37// Utility class which holds the class loader context used during compilation/verification.
38class ClassLoaderContext {
39 public:
Mathieu Chartieradc90862018-05-11 13:03:06 -070040 enum class VerificationResult {
41 kVerifies,
42 kForcedToSkipChecks,
43 kMismatch,
44 };
45
46 enum ClassLoaderType {
47 kInvalidClassLoader = 0,
48 kPathClassLoader = 1,
David Brazdil1a9ac532019-03-05 11:57:13 +000049 kDelegateLastClassLoader = 2,
50 kInMemoryDexClassLoader = 3
Mathieu Chartieradc90862018-05-11 13:03:06 -070051 };
52
Dan Zimmermanb682ea42019-12-23 06:59:06 -080053 // Special encoding used to denote a foreign ClassLoader was found when trying to encode class
54 // loader contexts for each classpath element in a ClassLoader. See
55 // EncodeClassPathContextsForClassLoader. Keep in sync with PackageDexUsage in the framework.
56 static constexpr const char* kUnsupportedClassLoaderContextEncoding =
57 "=UnsupportedClassLoaderContext=";
58
Calin Juravle57d0acc2017-07-11 17:41:30 -070059 ~ClassLoaderContext();
60
Calin Juravle87e2cb62017-06-13 21:48:45 -070061 // Opens requested class path files and appends them to ClassLoaderInfo::opened_dex_files.
62 // If the dex files have been stripped, the method opens them from their oat files which are added
63 // to ClassLoaderInfo::opened_oat_files. The 'classpath_dir' argument specifies the directory to
64 // use for the relative class paths.
65 // Returns true if all dex files where successfully opened.
Calin Juravlec5b215f2017-09-12 14:49:37 -070066 // It may be called only once per ClassLoaderContext. Subsequent calls will return the same
67 // result without doing anything.
David Brazdil89821862019-03-19 13:57:43 +000068 // If `context_fds` is an empty vector, files will be opened using the class path locations as
69 // filenames. Otherwise `context_fds` is expected to contain file descriptors to class path dex
70 // files, following the order of dex file locations in a flattened class loader context. If their
71 // number (size of `context_fds`) does not match the number of dex files, OpenDexFiles will fail.
Calin Juravlec5b215f2017-09-12 14:49:37 -070072 //
73 // This will replace the class path locations with the locations of the opened dex files.
74 // (Note that one dex file can contain multidexes. Each multidex will be added to the classpath
75 // separately.)
Calin Juravle87e2cb62017-06-13 21:48:45 -070076 //
Calin Juravle6e6f1b22020-12-15 19:13:19 -080077 // only_read_checksums controls whether or not we only read the dex locations and the checksums
78 // from the apk instead of fully opening the dex files.
79 //
80 // This method is not thread safe.
81 //
Calin Juravle87e2cb62017-06-13 21:48:45 -070082 // Note that a "false" return could mean that either an apk/jar contained no dex files or
83 // that we hit a I/O or checksum mismatch error.
84 // TODO(calin): Currently there's no easy way to tell the difference.
85 //
86 // TODO(calin): we're forced to complicate the flow in this class with a different
87 // OpenDexFiles step because the current dex2oat flow requires the dex files be opened before
88 // the class loader is created. Consider reworking the dex2oat part.
Calin Juravle5ff23932020-12-11 18:26:14 -080089 bool OpenDexFiles(const std::string& classpath_dir = "",
Calin Juravle6e6f1b22020-12-15 19:13:19 -080090 const std::vector<int>& context_fds = std::vector<int>(),
91 bool only_read_checksums = false);
Calin Juravle87e2cb62017-06-13 21:48:45 -070092
93 // Remove the specified compilation sources from all classpaths present in this context.
94 // Should only be called before the first call to OpenDexFiles().
95 bool RemoveLocationsFromClassPaths(const dchecked_vector<std::string>& compilation_sources);
96
97 // Creates the entire class loader hierarchy according to the current context.
Calin Juravlec79470d2017-07-12 17:37:42 -070098 // Returns the first class loader from the chain.
99 //
100 // For example: if the context was built from the spec
101 // "ClassLoaderType1[ClasspathElem1:ClasspathElem2...];ClassLoaderType2[...]..."
102 // the method returns the class loader correponding to ClassLoader1. The parent chain will be
103 // ClassLoader1 --> ClassLoader2 --> ... --> BootClassLoader.
104 //
105 // The compilation sources are appended to the classpath of the first class loader (in the above
106 // example ClassLoader1).
107 //
Calin Juravle7b0648a2017-07-07 18:40:50 -0700108 // If the context is empty, this method only creates a single PathClassLoader with the
109 // given compilation_sources.
Calin Juravlec79470d2017-07-12 17:37:42 -0700110 //
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000111 // Shared libraries found in the chain will be canonicalized based on the dex files they
112 // contain.
113 //
114 // Implementation notes:
Calin Juravlec79470d2017-07-12 17:37:42 -0700115 // 1) the objects are not completely set up. Do not use this outside of tests and the compiler.
116 // 2) should only be called before the first call to OpenDexFiles().
Calin Juravle87e2cb62017-06-13 21:48:45 -0700117 jobject CreateClassLoader(const std::vector<const DexFile*>& compilation_sources) const;
118
119 // Encodes the context as a string suitable to be added in oat files.
120 // (so that it can be read and verified at runtime against the actual class
121 // loader hierarchy).
122 // Should only be called if OpenDexFiles() returned true.
Mathieu Chartierc4440772018-04-16 14:40:56 -0700123 // If stored context is non-null, the stored names are overwritten by the class path from the
124 // stored context.
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700125 // E.g. if the context is PCL[a.dex:b.dex] this will return
126 // "PCL[a.dex*a_checksum*b.dex*a_checksum]".
Mathieu Chartierc4440772018-04-16 14:40:56 -0700127 std::string EncodeContextForOatFile(const std::string& base_dir,
128 ClassLoaderContext* stored_context = nullptr) const;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700129
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700130 // Encodes the context as a string suitable to be passed to dex2oat.
131 // This is the same as EncodeContextForOatFile but without adding the checksums
132 // and only adding each dex files once (no multidex).
133 // Should only be called if OpenDexFiles() returned true.
134 std::string EncodeContextForDex2oat(const std::string& base_dir) const;
135
Dan Zimmermanb682ea42019-12-23 06:59:06 -0800136 // Encodes the contexts for each of the classpath elements in the child-most
137 // classloader. Under the hood EncodeContextForDex2oat is used, so no checksums
138 // will be encoded.
139 // Should only be called if the dex files are opened (either via OpenDexFiles() or by creating the
140 // context from a live class loader).
141 // Notably, for each classpath element the encoded classloader context will contain only the
142 // elements that appear before it in the containing classloader. E.g. if `this` contains
143 // (from child to parent):
144 //
145 // PathClassLoader { multidex.apk!classes.dex, multidex.apk!classes2.dex, foo.dex, bar.dex } ->
146 // PathClassLoader { baz.dex } -> BootClassLoader
147 //
148 // then the return value will look like:
149 //
150 // `{ "multidex.apk": "PCL[];PCL[baz.dex]",
151 // "foo.dex" : "PCL[multidex.apk];PCL[baz.dex]",
152 // "bar.dex" : "PCL[multidex.apk:foo.dex];PCL[baz.dex]" }`
153 std::map<std::string, std::string> EncodeClassPathContexts(const std::string& base_dir) const;
154
Calin Juravle87e2cb62017-06-13 21:48:45 -0700155 // Flattens the opened dex files into the given vector.
156 // Should only be called if OpenDexFiles() returned true.
157 std::vector<const DexFile*> FlattenOpenedDexFiles() const;
158
David Brazdil89821862019-03-19 13:57:43 +0000159 // Return a colon-separated list of dex file locations from this class loader
160 // context after flattening.
161 std::string FlattenDexPaths() const;
162
Calin Juravle3f918642017-07-11 19:04:20 -0700163 // Verifies that the current context is identical to the context encoded as `context_spec`.
164 // Identical means:
165 // - the number and type of the class loaders from the chain matches
166 // - the class loader from the same position have the same classpath
167 // (the order and checksum of the dex files matches)
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800168 // This should be called after OpenDexFiles() with only_read_checksums=true. There's no
169 // need to fully open the dex files if the only thing that needs to be done is to verify
170 // the context.
171 //
Mathieu Chartierf5abfc42018-03-23 21:51:54 -0700172 // Names are only verified if verify_names is true.
173 // Checksums are only verified if verify_checksums is true.
Mathieu Chartieradc90862018-05-11 13:03:06 -0700174 VerificationResult VerifyClassLoaderContextMatch(const std::string& context_spec,
David Brazdil89821862019-03-19 13:57:43 +0000175 bool verify_names = true,
176 bool verify_checksums = true) const;
Calin Juravle3f918642017-07-11 19:04:20 -0700177
Calin Juravleb495e7f2020-04-06 19:29:45 -0700178 // Checks if any of the given dex files is already loaded in the current class loader context.
Calin Juravlea63a2e92020-04-15 20:02:00 -0700179 // It only checks the first class loader.
Calin Juravleb495e7f2020-04-06 19:29:45 -0700180 // Returns the list of duplicate dex files (empty if there are no duplicates).
Calin Juravlea63a2e92020-04-15 20:02:00 -0700181 std::set<const DexFile*> CheckForDuplicateDexFiles(
Calin Juravleb495e7f2020-04-06 19:29:45 -0700182 const std::vector<const DexFile*>& dex_files);
183
Calin Juravle87e2cb62017-06-13 21:48:45 -0700184 // Creates the class loader context from the given string.
185 // The format: ClassLoaderType1[ClasspathElem1:ClasspathElem2...];ClassLoaderType2[...]...
186 // ClassLoaderType is either "PCL" (PathClassLoader) or "DLC" (DelegateLastClassLoader).
187 // ClasspathElem is the path of dex/jar/apk file.
Calin Juravlec79470d2017-07-12 17:37:42 -0700188 //
189 // The spec represents a class loader chain with the natural interpretation:
190 // ClassLoader1 has ClassLoader2 as parent which has ClassLoader3 as a parent and so on.
191 // The last class loader is assumed to have the BootClassLoader as a parent.
192 //
Calin Juravle87e2cb62017-06-13 21:48:45 -0700193 // Note that we allowed class loaders with an empty class path in order to support a custom
194 // class loader for the source dex files.
195 static std::unique_ptr<ClassLoaderContext> Create(const std::string& spec);
196
Calin Juravle57d0acc2017-07-11 17:41:30 -0700197 // Creates a context for the given class_loader and dex_elements.
198 // The method will walk the parent chain starting from `class_loader` and add their dex files
199 // to the current class loaders chain. The `dex_elements` will be added at the end of the
200 // classpath belonging to the `class_loader` argument.
201 // The ownership of the opened dex files will be retained by the given `class_loader`.
202 // If there are errors in processing the class loader chain (e.g. unsupported elements) the
203 // method returns null.
204 static std::unique_ptr<ClassLoaderContext> CreateContextForClassLoader(jobject class_loader,
205 jobjectArray dex_elements);
206
Calin Juravle19915892017-08-03 17:10:36 +0000207 // Returns the default class loader context to be used when none is specified.
208 // This will return a context with a single and empty PathClassLoader.
209 static std::unique_ptr<ClassLoaderContext> Default();
210
Dan Zimmermanb682ea42019-12-23 06:59:06 -0800211 // Encodes the contexts for each of the classpath elements in `class_loader`. See
212 // ClassLoaderContext::EncodeClassPathContexts for more information about the return value.
213 //
214 // If `class_loader` does not derive from BaseDexClassLoader then an empty map is returned.
215 // Otherwise if a foreign ClassLoader is found in the class loader chain then the results values
216 // will all be ClassLoaderContext::kUnsupportedClassLoaderContextEncoding.
217 static std::map<std::string, std::string> EncodeClassPathContextsForClassLoader(
218 jobject class_loader);
219
Dan Zimmermanc9fa7702020-01-31 13:35:12 -0800220 // Returns whether `encoded_class_loader_context` is a valid encoded ClassLoaderContext or
221 // EncodedUnsupportedClassLoaderContext.
222 static bool IsValidEncoding(const std::string& possible_encoded_class_loader_context);
223
Calin Juravle87e2cb62017-06-13 21:48:45 -0700224 struct ClassLoaderInfo {
225 // The type of this class loader.
226 ClassLoaderType type;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000227 // Shared libraries this context has.
228 std::vector<std::unique_ptr<ClassLoaderInfo>> shared_libraries;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700229 // The list of class path elements that this loader loads.
230 // Note that this list may contain relative paths.
231 std::vector<std::string> classpath;
Mathieu Chartierc4440772018-04-16 14:40:56 -0700232 // Original opened class path (ignoring multidex).
233 std::vector<std::string> original_classpath;
Calin Juravle7b0648a2017-07-07 18:40:50 -0700234 // The list of class path elements checksums.
235 // May be empty if the checksums are not given when the context is created.
236 std::vector<uint32_t> checksums;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700237 // After OpenDexFiles is called this holds the opened dex files.
238 std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
239 // After OpenDexFiles, in case some of the dex files were opened from their oat files
240 // this holds the list of opened oat files.
241 std::vector<std::unique_ptr<OatFile>> opened_oat_files;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000242 // The parent class loader.
243 std::unique_ptr<ClassLoaderInfo> parent;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700244
245 explicit ClassLoaderInfo(ClassLoaderType cl_type) : type(cl_type) {}
246 };
247
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000248 private:
Calin Juravle19915892017-08-03 17:10:36 +0000249 // Creates an empty context (with no class loaders).
250 ClassLoaderContext();
251
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000252 // Get the parent of the class loader chain at depth `index`.
253 ClassLoaderInfo* GetParent(size_t index) const {
254 ClassLoaderInfo* result = class_loader_chain_.get();
255 while ((result != nullptr) && (index-- != 0)) {
256 result = result->parent.get();
257 }
258 return result;
259 }
260
261 size_t GetParentChainSize() const {
262 size_t result = 0;
263 ClassLoaderInfo* info = class_loader_chain_.get();
264 while (info != nullptr) {
265 ++result;
266 info = info->parent.get();
267 }
268 return result;
269 }
270
Calin Juravle57d0acc2017-07-11 17:41:30 -0700271 // Constructs an empty context.
272 // `owns_the_dex_files` specifies whether or not the context will own the opened dex files
273 // present in the class loader chain. If `owns_the_dex_files` is true then OpenDexFiles cannot
274 // be called on this context (dex_files_open_attempted_ and dex_files_open_result_ will be set
275 // to true as well)
276 explicit ClassLoaderContext(bool owns_the_dex_files);
277
Calin Juravle87e2cb62017-06-13 21:48:45 -0700278 // Reads the class loader spec in place and returns true if the spec is valid and the
279 // compilation context was constructed.
Calin Juravle7b0648a2017-07-07 18:40:50 -0700280 bool Parse(const std::string& spec, bool parse_checksums = false);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000281 ClassLoaderInfo* ParseInternal(const std::string& spec, bool parse_checksums);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700282
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000283 // Attempts to parse a single class loader spec.
284 // Returns the ClassLoaderInfo abstraction for this spec, or null if it cannot be parsed.
285 std::unique_ptr<ClassLoaderInfo> ParseClassLoaderSpec(
286 const std::string& class_loader_spec,
287 bool parse_checksums = false);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700288
Calin Juravle57d0acc2017-07-11 17:41:30 -0700289 // CHECKs that the dex files were opened (OpenDexFiles was called and set dex_files_open_result_
290 // to true). Aborts if not. The `calling_method` is used in the log message to identify the source
291 // of the call.
292 void CheckDexFilesOpened(const std::string& calling_method) const;
293
Nicolas Geoffraye1672732018-11-30 01:09:49 +0000294 // Creates the `ClassLoaderInfo` representing`class_loader` and attach it to `this`.
Calin Juravle57d0acc2017-07-11 17:41:30 -0700295 // The dex file present in `dex_elements` array (if not null) will be added at the end of
296 // the classpath.
Nicolas Geoffraye1672732018-11-30 01:09:49 +0000297 bool CreateInfoFromClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
298 Handle<mirror::ClassLoader> class_loader,
299 Handle<mirror::ObjectArray<mirror::Object>> dex_elements,
300 ClassLoaderInfo* child_info,
301 bool is_shared_library)
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700302 REQUIRES_SHARED(Locks::mutator_lock_);
303
304 // Encodes the context as a string suitable to be passed to dex2oat or to be added to the
305 // oat file as the class path key.
306 // If for_dex2oat is true, the encoding adds each file once (i.e. it does not add multidex
307 // location). Otherwise, for oat files, the encoding adds all the dex files (including multidex)
308 // together with their checksums.
309 // Should only be called if OpenDexFiles() returned true.
Mathieu Chartierc4440772018-04-16 14:40:56 -0700310 std::string EncodeContext(const std::string& base_dir,
311 bool for_dex2oat,
312 ClassLoaderContext* stored_context) const;
Calin Juravle57d0acc2017-07-11 17:41:30 -0700313
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000314 // Internal version of `EncodeContext`, which will be called recursively
315 // on the parent and shared libraries.
316 void EncodeContextInternal(const ClassLoaderInfo& info,
317 const std::string& base_dir,
318 bool for_dex2oat,
319 ClassLoaderInfo* stored_info,
320 std::ostringstream& out) const;
321
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800322 // Encodes e.g. PCL[foo.dex:bar.dex]
323 void EncodeClassPath(const std::string& base_dir,
324 const std::vector<std::string>& dex_locations,
325 const std::vector<uint32_t>& checksums,
326 ClassLoaderType type,
327 std::ostringstream& out) const;
328
329 // Encodes the shared libraries classloaders and the parent classloader if
330 // either are present in info, e.g. {PCL[foo.dex]#PCL[bar.dex]};PCL[baz.dex]
331 void EncodeSharedLibAndParent(const ClassLoaderInfo& info,
332 const std::string& base_dir,
333 bool for_dex2oat,
334 ClassLoaderInfo* stored_info,
335 std::ostringstream& out) const;
336
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000337 bool ClassLoaderInfoMatch(const ClassLoaderInfo& info,
338 const ClassLoaderInfo& expected_info,
339 const std::string& context_spec,
340 bool verify_names,
341 bool verify_checksums) const;
342
Calin Juravle87e2cb62017-06-13 21:48:45 -0700343 // Extracts the class loader type from the given spec.
344 // Return ClassLoaderContext::kInvalidClassLoader if the class loader type is not
345 // recognized.
346 static ClassLoaderType ExtractClassLoaderType(const std::string& class_loader_spec);
347
348 // Returns the string representation of the class loader type.
349 // The returned format can be used when parsing a context spec.
350 static const char* GetClassLoaderTypeName(ClassLoaderType type);
351
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800352 // Encodes the state of processing the dex files associated with the context.
353 enum ContextDexFilesState {
354 // The dex files are not opened.
355 kDexFilesNotOpened = 1,
356 // The dex checksums/locations were read from the apk/dex but the dex files were not opened.
357 kDexFilesChecksumsRead = 2,
358 // The dex files are opened (either because we called OpenDexFiles, or we used a class loader
359 // to create the context). This implies kDexFilesChecksumsRead.
360 kDexFilesOpened = 3,
361 // We failed to open the dex files or read the checksums.
362 kDexFilesOpenFailed = 4
363 };
364
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000365 // The class loader chain.
366 std::unique_ptr<ClassLoaderInfo> class_loader_chain_;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700367
368 // Whether or not the class loader context should be ignored at runtime when loading the oat
369 // files. When true, dex2oat will use OatFile::kSpecialSharedLibrary as the classpath key in
370 // the oat file.
371 // TODO(calin): Can we get rid of this and cover all relevant use cases?
372 // (e.g. packages using prebuild system packages as shared libraries b/36480683)
373 bool special_shared_library_;
374
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800375 // The opening state of the dex files.
376 ContextDexFilesState dex_files_state_;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700377
Calin Juravle57d0acc2017-07-11 17:41:30 -0700378 // Whether or not the context owns the opened dex and oat files.
379 // If true, the opened dex files will be de-allocated when the context is destructed.
380 // If false, the objects will continue to be alive.
381 // Note that for convenience the the opened dex/oat files are stored as unique pointers
382 // which will release their ownership in the destructor based on this flag.
383 const bool owns_the_dex_files_;
384
Calin Juravle87e2cb62017-06-13 21:48:45 -0700385 friend class ClassLoaderContextTest;
386
387 DISALLOW_COPY_AND_ASSIGN(ClassLoaderContext);
388};
389
390} // namespace art
391#endif // ART_RUNTIME_CLASS_LOADER_CONTEXT_H_