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 #ifndef ART_RUNTIME_CLASS_LOADER_CONTEXT_H_
18 #define ART_RUNTIME_CLASS_LOADER_CONTEXT_H_
19 
20 #include <string>
21 #include <vector>
22 
23 #include "arch/instruction_set.h"
24 #include "base/dchecked_vector.h"
25 #include "dex/dex_file.h"
26 #include "handle_scope.h"
27 #include "mirror/class_loader.h"
28 #include "oat_file.h"
29 #include "scoped_thread_state_change.h"
30 
31 namespace art {
32 
33 class DexFile;
34 class OatFile;
35 
36 // Utility class which holds the class loader context used during compilation/verification.
37 class ClassLoaderContext {
38  public:
39   enum class VerificationResult {
40     kVerifies,
41     kForcedToSkipChecks,
42     kMismatch,
43   };
44 
45   enum ClassLoaderType {
46     kInvalidClassLoader = 0,
47     kPathClassLoader = 1,
48     kDelegateLastClassLoader = 2,
49     kInMemoryDexClassLoader = 3
50   };
51 
52   ~ClassLoaderContext();
53 
54   // Opens requested class path files and appends them to ClassLoaderInfo::opened_dex_files.
55   // If the dex files have been stripped, the method opens them from their oat files which are added
56   // to ClassLoaderInfo::opened_oat_files. The 'classpath_dir' argument specifies the directory to
57   // use for the relative class paths.
58   // Returns true if all dex files where successfully opened.
59   // It may be called only once per ClassLoaderContext. Subsequent calls will return the same
60   // result without doing anything.
61   // If `context_fds` is an empty vector, files will be opened using the class path locations as
62   // filenames. Otherwise `context_fds` is expected to contain file descriptors to class path dex
63   // files, following the order of dex file locations in a flattened class loader context. If their
64   // number (size of `context_fds`) does not match the number of dex files, OpenDexFiles will fail.
65   //
66   // This will replace the class path locations with the locations of the opened dex files.
67   // (Note that one dex file can contain multidexes. Each multidex will be added to the classpath
68   // separately.)
69   //
70   // Note that a "false" return could mean that either an apk/jar contained no dex files or
71   // that we hit a I/O or checksum mismatch error.
72   // TODO(calin): Currently there's no easy way to tell the difference.
73   //
74   // TODO(calin): we're forced to complicate the flow in this class with a different
75   // OpenDexFiles step because the current dex2oat flow requires the dex files be opened before
76   // the class loader is created. Consider reworking the dex2oat part.
77   bool OpenDexFiles(InstructionSet isa,
78                     const std::string& classpath_dir,
79                     const std::vector<int>& context_fds = std::vector<int>());
80 
81   // Remove the specified compilation sources from all classpaths present in this context.
82   // Should only be called before the first call to OpenDexFiles().
83   bool RemoveLocationsFromClassPaths(const dchecked_vector<std::string>& compilation_sources);
84 
85   // Creates the entire class loader hierarchy according to the current context.
86   // Returns the first class loader from the chain.
87   //
88   // For example: if the context was built from the spec
89   // "ClassLoaderType1[ClasspathElem1:ClasspathElem2...];ClassLoaderType2[...]..."
90   // the method returns the class loader correponding to ClassLoader1. The parent chain will be
91   // ClassLoader1 --> ClassLoader2 --> ... --> BootClassLoader.
92   //
93   // The compilation sources are appended to the classpath of the first class loader (in the above
94   // example ClassLoader1).
95   //
96   // If the context is empty, this method only creates a single PathClassLoader with the
97   // given compilation_sources.
98   //
99   // Shared libraries found in the chain will be canonicalized based on the dex files they
100   // contain.
101   //
102   // Implementation notes:
103   //   1) the objects are not completely set up. Do not use this outside of tests and the compiler.
104   //   2) should only be called before the first call to OpenDexFiles().
105   jobject CreateClassLoader(const std::vector<const DexFile*>& compilation_sources) const;
106 
107   // Encodes the context as a string suitable to be added in oat files.
108   // (so that it can be read and verified at runtime against the actual class
109   // loader hierarchy).
110   // Should only be called if OpenDexFiles() returned true.
111   // If stored context is non-null, the stored names are overwritten by the class path from the
112   // stored context.
113   // E.g. if the context is PCL[a.dex:b.dex] this will return
114   // "PCL[a.dex*a_checksum*b.dex*a_checksum]".
115   std::string EncodeContextForOatFile(const std::string& base_dir,
116                                       ClassLoaderContext* stored_context = nullptr) const;
117 
118   // Encodes the context as a string suitable to be passed to dex2oat.
119   // This is the same as EncodeContextForOatFile but without adding the checksums
120   // and only adding each dex files once (no multidex).
121   // Should only be called if OpenDexFiles() returned true.
122   std::string EncodeContextForDex2oat(const std::string& base_dir) const;
123 
124   // Flattens the opened dex files into the given vector.
125   // Should only be called if OpenDexFiles() returned true.
126   std::vector<const DexFile*> FlattenOpenedDexFiles() const;
127 
128   // Return a colon-separated list of dex file locations from this class loader
129   // context after flattening.
130   std::string FlattenDexPaths() const;
131 
132   // Verifies that the current context is identical to the context encoded as `context_spec`.
133   // Identical means:
134   //    - the number and type of the class loaders from the chain matches
135   //    - the class loader from the same position have the same classpath
136   //      (the order and checksum of the dex files matches)
137   // This should be called after OpenDexFiles().
138   // Names are only verified if verify_names is true.
139   // Checksums are only verified if verify_checksums is true.
140   VerificationResult VerifyClassLoaderContextMatch(const std::string& context_spec,
141                                                    bool verify_names = true,
142                                                    bool verify_checksums = true) const;
143 
144   // Creates the class loader context from the given string.
145   // The format: ClassLoaderType1[ClasspathElem1:ClasspathElem2...];ClassLoaderType2[...]...
146   // ClassLoaderType is either "PCL" (PathClassLoader) or "DLC" (DelegateLastClassLoader).
147   // ClasspathElem is the path of dex/jar/apk file.
148   //
149   // The spec represents a class loader chain with the natural interpretation:
150   // ClassLoader1 has ClassLoader2 as parent which has ClassLoader3 as a parent and so on.
151   // The last class loader is assumed to have the BootClassLoader as a parent.
152   //
153   // Note that we allowed class loaders with an empty class path in order to support a custom
154   // class loader for the source dex files.
155   static std::unique_ptr<ClassLoaderContext> Create(const std::string& spec);
156 
157   // Creates a context for the given class_loader and dex_elements.
158   // The method will walk the parent chain starting from `class_loader` and add their dex files
159   // to the current class loaders chain. The `dex_elements` will be added at the end of the
160   // classpath belonging to the `class_loader` argument.
161   // The ownership of the opened dex files will be retained by the given `class_loader`.
162   // If there are errors in processing the class loader chain (e.g. unsupported elements) the
163   // method returns null.
164   static std::unique_ptr<ClassLoaderContext> CreateContextForClassLoader(jobject class_loader,
165                                                                          jobjectArray dex_elements);
166 
167   // Returns the default class loader context to be used when none is specified.
168   // This will return a context with a single and empty PathClassLoader.
169   static std::unique_ptr<ClassLoaderContext> Default();
170 
171   struct ClassLoaderInfo {
172     // The type of this class loader.
173     ClassLoaderType type;
174     // Shared libraries this context has.
175     std::vector<std::unique_ptr<ClassLoaderInfo>> shared_libraries;
176     // The list of class path elements that this loader loads.
177     // Note that this list may contain relative paths.
178     std::vector<std::string> classpath;
179     // Original opened class path (ignoring multidex).
180     std::vector<std::string> original_classpath;
181     // The list of class path elements checksums.
182     // May be empty if the checksums are not given when the context is created.
183     std::vector<uint32_t> checksums;
184     // After OpenDexFiles is called this holds the opened dex files.
185     std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
186     // After OpenDexFiles, in case some of the dex files were opened from their oat files
187     // this holds the list of opened oat files.
188     std::vector<std::unique_ptr<OatFile>> opened_oat_files;
189     // The parent class loader.
190     std::unique_ptr<ClassLoaderInfo> parent;
191 
ClassLoaderInfoClassLoaderInfo192     explicit ClassLoaderInfo(ClassLoaderType cl_type) : type(cl_type) {}
193   };
194 
195  private:
196   // Creates an empty context (with no class loaders).
197   ClassLoaderContext();
198 
199   // Get the parent of the class loader chain at depth `index`.
GetParent(size_t index)200   ClassLoaderInfo* GetParent(size_t index) const {
201     ClassLoaderInfo* result = class_loader_chain_.get();
202     while ((result != nullptr) && (index-- != 0)) {
203       result = result->parent.get();
204     }
205     return result;
206   }
207 
GetParentChainSize()208   size_t GetParentChainSize() const {
209     size_t result = 0;
210     ClassLoaderInfo* info = class_loader_chain_.get();
211     while (info != nullptr) {
212       ++result;
213       info = info->parent.get();
214     }
215     return result;
216   }
217 
218   // Constructs an empty context.
219   // `owns_the_dex_files` specifies whether or not the context will own the opened dex files
220   // present in the class loader chain. If `owns_the_dex_files` is true then OpenDexFiles cannot
221   // be called on this context (dex_files_open_attempted_ and dex_files_open_result_ will be set
222   // to true as well)
223   explicit ClassLoaderContext(bool owns_the_dex_files);
224 
225   // Reads the class loader spec in place and returns true if the spec is valid and the
226   // compilation context was constructed.
227   bool Parse(const std::string& spec, bool parse_checksums = false);
228   ClassLoaderInfo* ParseInternal(const std::string& spec, bool parse_checksums);
229 
230   // Attempts to parse a single class loader spec.
231   // Returns the ClassLoaderInfo abstraction for this spec, or null if it cannot be parsed.
232   std::unique_ptr<ClassLoaderInfo> ParseClassLoaderSpec(
233       const std::string& class_loader_spec,
234       bool parse_checksums = false);
235 
236   // CHECKs that the dex files were opened (OpenDexFiles was called and set dex_files_open_result_
237   // to true). Aborts if not. The `calling_method` is used in the log message to identify the source
238   // of the call.
239   void CheckDexFilesOpened(const std::string& calling_method) const;
240 
241   // Creates the `ClassLoaderInfo` representing`class_loader` and attach it to `this`.
242   // The dex file present in `dex_elements` array (if not null) will be added at the end of
243   // the classpath.
244   bool CreateInfoFromClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
245                                  Handle<mirror::ClassLoader> class_loader,
246                                  Handle<mirror::ObjectArray<mirror::Object>> dex_elements,
247                                  ClassLoaderInfo* child_info,
248                                  bool is_shared_library)
249     REQUIRES_SHARED(Locks::mutator_lock_);
250 
251   // Encodes the context as a string suitable to be passed to dex2oat or to be added to the
252   // oat file as the class path key.
253   // If for_dex2oat is true, the encoding adds each file once (i.e. it does not add multidex
254   // location). Otherwise, for oat files, the encoding adds all the dex files (including multidex)
255   // together with their checksums.
256   // Should only be called if OpenDexFiles() returned true.
257   std::string EncodeContext(const std::string& base_dir,
258                             bool for_dex2oat,
259                             ClassLoaderContext* stored_context) const;
260 
261   // Internal version of `EncodeContext`, which will be called recursively
262   // on the parent and shared libraries.
263   void EncodeContextInternal(const ClassLoaderInfo& info,
264                              const std::string& base_dir,
265                              bool for_dex2oat,
266                              ClassLoaderInfo* stored_info,
267                              std::ostringstream& out) const;
268 
269   bool ClassLoaderInfoMatch(const ClassLoaderInfo& info,
270                             const ClassLoaderInfo& expected_info,
271                             const std::string& context_spec,
272                             bool verify_names,
273                             bool verify_checksums) const;
274 
275   // Extracts the class loader type from the given spec.
276   // Return ClassLoaderContext::kInvalidClassLoader if the class loader type is not
277   // recognized.
278   static ClassLoaderType ExtractClassLoaderType(const std::string& class_loader_spec);
279 
280   // Returns the string representation of the class loader type.
281   // The returned format can be used when parsing a context spec.
282   static const char* GetClassLoaderTypeName(ClassLoaderType type);
283 
284   // The class loader chain.
285   std::unique_ptr<ClassLoaderInfo> class_loader_chain_;
286 
287   // Whether or not the class loader context should be ignored at runtime when loading the oat
288   // files. When true, dex2oat will use OatFile::kSpecialSharedLibrary as the classpath key in
289   // the oat file.
290   // TODO(calin): Can we get rid of this and cover all relevant use cases?
291   // (e.g. packages using prebuild system packages as shared libraries b/36480683)
292   bool special_shared_library_;
293 
294   // Whether or not OpenDexFiles() was called.
295   bool dex_files_open_attempted_;
296   // The result of the last OpenDexFiles() operation.
297   bool dex_files_open_result_;
298 
299   // Whether or not the context owns the opened dex and oat files.
300   // If true, the opened dex files will be de-allocated when the context is destructed.
301   // If false, the objects will continue to be alive.
302   // Note that for convenience the the opened dex/oat files are stored as unique pointers
303   // which will release their ownership in the destructor based on this flag.
304   const bool owns_the_dex_files_;
305 
306   friend class ClassLoaderContextTest;
307 
308   DISALLOW_COPY_AND_ASSIGN(ClassLoaderContext);
309 };
310 
311 }  // namespace art
312 #endif  // ART_RUNTIME_CLASS_LOADER_CONTEXT_H_
313