1 /*
2  * Copyright (C) 2015 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_OAT_FILE_MANAGER_H_
18 #define ART_RUNTIME_OAT_FILE_MANAGER_H_
19 
20 #include <memory>
21 #include <set>
22 #include <string>
23 #include <unordered_map>
24 #include <vector>
25 
26 #include "base/locks.h"
27 #include "base/macros.h"
28 #include "jni.h"
29 
30 namespace art {
31 
32 namespace gc {
33 namespace space {
34 class ImageSpace;
35 }  // namespace space
36 }  // namespace gc
37 
38 class ClassLoaderContext;
39 class DexFile;
40 class MemMap;
41 class OatFile;
42 class ThreadPool;
43 
44 // Class for dealing with oat file management.
45 //
46 // This class knows about all the loaded oat files and provides utility functions. The oat file
47 // pointers returned from functions are always valid.
48 class OatFileManager {
49  public:
50   OatFileManager();
51   ~OatFileManager();
52 
53   // Add an oat file to the internal accounting, std::aborts if there already exists an oat file
54   // with the same base address. Returns the oat file pointer from oat_file.
55   const OatFile* RegisterOatFile(std::unique_ptr<const OatFile> oat_file)
56       REQUIRES(!Locks::oat_file_manager_lock_);
57 
58   void UnRegisterAndDeleteOatFile(const OatFile* oat_file)
59       REQUIRES(!Locks::oat_file_manager_lock_);
60 
61   // Find the first opened oat file with the same location, returns null if there are none.
62   const OatFile* FindOpenedOatFileFromOatLocation(const std::string& oat_location) const
63       REQUIRES(!Locks::oat_file_manager_lock_);
64 
65   // Find the oat file which contains a dex files with the given dex base location,
66   // returns null if there are none.
67   const OatFile* FindOpenedOatFileFromDexLocation(const std::string& dex_base_location) const
68       REQUIRES(!Locks::oat_file_manager_lock_);
69 
70   // Returns the boot image oat files.
71   std::vector<const OatFile*> GetBootOatFiles() const;
72 
73   // Returns the first non-image oat file in the class path.
74   const OatFile* GetPrimaryOatFile() const REQUIRES(!Locks::oat_file_manager_lock_);
75 
76   // Returns the oat files for the images, registers the oat files.
77   // Takes ownership of the imagespace's underlying oat files.
78   std::vector<const OatFile*> RegisterImageOatFiles(
79       const std::vector<gc::space::ImageSpace*>& spaces)
80       REQUIRES(!Locks::oat_file_manager_lock_);
81 
82   // Finds or creates the oat file holding dex_location. Then loads and returns
83   // all corresponding dex files (there may be more than one dex file loaded
84   // in the case of multidex).
85   // This may return the original, unquickened dex files if the oat file could
86   // not be generated.
87   //
88   // Returns an empty vector if the dex files could not be loaded. In this
89   // case, there will be at least one error message returned describing why no
90   // dex files could not be loaded. The 'error_msgs' argument must not be
91   // null, regardless of whether there is an error or not.
92   //
93   // This method should not be called with the mutator_lock_ held, because it
94   // could end up starving GC if we need to generate or relocate any oat
95   // files.
96   std::vector<std::unique_ptr<const DexFile>> OpenDexFilesFromOat(
97       const char* dex_location,
98       jobject class_loader,
99       jobjectArray dex_elements,
100       /*out*/ const OatFile** out_oat_file,
101       /*out*/ std::vector<std::string>* error_msgs)
102       REQUIRES(!Locks::oat_file_manager_lock_, !Locks::mutator_lock_);
103 
104   // Opens dex files provided in `dex_mem_maps` and attempts to find an anonymous
105   // vdex file created during a previous load attempt. If found, will initialize
106   // an instance of OatFile to back the DexFiles and preverify them using the
107   // vdex's VerifierDeps.
108   //
109   // Returns an empty vector if the dex files could not be loaded. In this
110   // case, there will be at least one error message returned describing why no
111   // dex files could not be loaded. The 'error_msgs' argument must not be
112   // null, regardless of whether there is an error or not.
113   std::vector<std::unique_ptr<const DexFile>> OpenDexFilesFromOat(
114       std::vector<MemMap>&& dex_mem_maps,
115       jobject class_loader,
116       jobjectArray dex_elements,
117       /*out*/ const OatFile** out_oat_file,
118       /*out*/ std::vector<std::string>* error_msgs)
119       REQUIRES(!Locks::oat_file_manager_lock_, !Locks::mutator_lock_);
120 
121   void DumpForSigQuit(std::ostream& os);
122 
123   void SetOnlyUseSystemOatFiles();
124 
125   // Spawn a background thread which verifies all classes in the given dex files.
126   void RunBackgroundVerification(const std::vector<const DexFile*>& dex_files,
127                                  jobject class_loader,
128                                  const char* class_loader_context);
129 
130   // Wait for thread pool workers to be created. This is used during shutdown as
131   // threads are not allowed to attach while runtime is in shutdown lock.
132   void WaitForWorkersToBeCreated();
133 
134   // If allocated, delete a thread pool of background verification threads.
135   void DeleteThreadPool();
136 
137   // Wait for all background verification tasks to finish. This is only used by tests.
138   void WaitForBackgroundVerificationTasks();
139 
140   // Maximum number of anonymous vdex files kept in the process' data folder.
141   static constexpr size_t kAnonymousVdexCacheSize = 8u;
142 
143  private:
144   enum class CheckCollisionResult {
145     kSkippedUnsupportedClassLoader,
146     kSkippedClassLoaderContextSharedLibrary,
147     kSkippedVerificationDisabled,
148     kNoCollisions,
149     kPerformedHasCollisions,
150     kClassLoaderContextMatches
151   };
152 
153   std::vector<std::unique_ptr<const DexFile>> OpenDexFilesFromOat_Impl(
154       std::vector<MemMap>&& dex_mem_maps,
155       jobject class_loader,
156       jobjectArray dex_elements,
157       /*out*/ const OatFile** out_oat_file,
158       /*out*/ std::vector<std::string>* error_msgs)
159       REQUIRES(!Locks::oat_file_manager_lock_, !Locks::mutator_lock_);
160 
161   // Check that the class loader context of the given oat file matches the given context.
162   // This will perform a check that all class loaders in the chain have the same type and
163   // classpath.
164   // If the context is null (which means the initial class loader was null or unsupported)
165   // this returns kSkippedUnsupportedClassLoader.
166   // If the context does not validate the method will check for duplicate class definitions of
167   // the given oat file against the oat files (either from the class loaders if possible or all
168   // non-boot oat files otherwise).
169   // Return kPerformedHasCollisions if there are any class definition collisions in the oat_file.
170   CheckCollisionResult CheckCollision(const OatFile* oat_file,
171                                       const ClassLoaderContext* context,
172                                       /*out*/ std::string* error_msg) const
173       REQUIRES(!Locks::oat_file_manager_lock_);
174 
175   const OatFile* FindOpenedOatFileFromOatLocationLocked(const std::string& oat_location) const
176       REQUIRES(Locks::oat_file_manager_lock_);
177 
178   // Return true if we should accept the oat file.
179   bool AcceptOatFile(CheckCollisionResult result) const;
180 
181   // Return true if we should attempt to load the app image.
182   bool ShouldLoadAppImage(CheckCollisionResult check_collision_result,
183                           const OatFile* source_oat_file,
184                           ClassLoaderContext* context,
185                           std::string* error_msg);
186 
187   std::set<std::unique_ptr<const OatFile>> oat_files_ GUARDED_BY(Locks::oat_file_manager_lock_);
188 
189   // Only use the compiled code in an OAT file when the file is on /system. If the OAT file
190   // is not on /system, don't load it "executable".
191   bool only_use_system_oat_files_;
192 
193   // Single-thread pool used to run the verifier in the background.
194   std::unique_ptr<ThreadPool> verification_thread_pool_;
195 
196   DISALLOW_COPY_AND_ASSIGN(OatFileManager);
197 };
198 
199 }  // namespace art
200 
201 #endif  // ART_RUNTIME_OAT_FILE_MANAGER_H_
202