1 /*
2  * Copyright (C) 2014 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_ASSISTANT_H_
18 #define ART_RUNTIME_OAT_FILE_ASSISTANT_H_
19 
20 #include <cstdint>
21 #include <memory>
22 #include <sstream>
23 #include <string>
24 
25 #include "arch/instruction_set.h"
26 #include "base/scoped_flock.h"
27 #include "base/unix_file/fd_file.h"
28 #include "compiler_filter.h"
29 #include "oat_file.h"
30 #include "os.h"
31 #include "profiler.h"
32 
33 namespace art {
34 
35 namespace gc {
36 namespace space {
37 class ImageSpace;
38 }  // namespace space
39 }  // namespace gc
40 
41 // Class for assisting with oat file management.
42 //
43 // This class collects common utilities for determining the status of an oat
44 // file on the device, updating the oat file, and loading the oat file.
45 //
46 // The oat file assistant is intended to be used with dex locations not on the
47 // boot class path. See the IsInBootClassPath method for a way to check if the
48 // dex location is in the boot class path.
49 class OatFileAssistant {
50  public:
51   enum DexOptNeeded {
52     // kNoDexOptNeeded - The code for this dex location is up to date and can
53     // be used as is.
54     // Matches Java: dalvik.system.DexFile.NO_DEXOPT_NEEDED = 0
55     kNoDexOptNeeded = 0,
56 
57     // kDex2OatNeeded - In order to make the code for this dex location up to
58     // date, dex2oat must be run on the dex file.
59     // Matches Java: dalvik.system.DexFile.DEX2OAT_NEEDED = 1
60     kDex2OatNeeded = 1,
61 
62     // kPatchOatNeeded - In order to make the code for this dex location up to
63     // date, patchoat must be run on the odex file.
64     // Matches Java: dalvik.system.DexFile.PATCHOAT_NEEDED = 2
65     kPatchOatNeeded = 2,
66 
67     // kSelfPatchOatNeeded - In order to make the code for this dex location
68     // up to date, patchoat must be run on the oat file.
69     // Matches Java: dalvik.system.DexFile.SELF_PATCHOAT_NEEDED = 3
70     kSelfPatchOatNeeded = 3,
71   };
72 
73   enum OatStatus {
74     // kOatOutOfDate - An oat file is said to be out of date if the file does
75     // not exist, is out of date with respect to the dex file or boot image,
76     // or does not meet the target compilation type.
77     kOatOutOfDate,
78 
79     // kOatNeedsRelocation - An oat file is said to need relocation if the
80     // code is up to date, but not yet properly relocated for address space
81     // layout randomization (ASLR). In this case, the oat file is neither
82     // "out of date" nor "up to date".
83     kOatNeedsRelocation,
84 
85     // kOatUpToDate - An oat file is said to be up to date if it is not out of
86     // date and has been properly relocated for the purposes of ASLR.
87     kOatUpToDate,
88   };
89 
90   // Constructs an OatFileAssistant object to assist the oat file
91   // corresponding to the given dex location with the target instruction set.
92   //
93   // The dex_location must not be null and should remain available and
94   // unchanged for the duration of the lifetime of the OatFileAssistant object.
95   // Typically the dex_location is the absolute path to the original,
96   // un-optimized dex file.
97   //
98   // Note: Currently the dex_location must have an extension.
99   // TODO: Relax this restriction?
100   //
101   // The isa should be either the 32 bit or 64 bit variant for the current
102   // device. For example, on an arm device, use arm or arm64. An oat file can
103   // be loaded executable only if the ISA matches the current runtime.
104   //
105   // profile_changed should be true if the profile has recently changed
106   // for this dex location.
107   //
108   // load_executable should be true if the caller intends to try and load
109   // executable code for this dex location.
110   OatFileAssistant(const char* dex_location,
111                    const InstructionSet isa,
112                    bool profile_changed,
113                    bool load_executable);
114 
115   // Constructs an OatFileAssistant, providing an explicit target oat_location
116   // to use instead of the standard oat location.
117   OatFileAssistant(const char* dex_location,
118                    const char* oat_location,
119                    const InstructionSet isa,
120                    bool profile_changed,
121                    bool load_executable);
122 
123   ~OatFileAssistant();
124 
125   // Returns true if the dex location refers to an element of the boot class
126   // path.
127   bool IsInBootClassPath();
128 
129   // Obtains a lock on the target oat file.
130   // Only one OatFileAssistant object can hold the lock for a target oat file
131   // at a time. The Lock is released automatically when the OatFileAssistant
132   // object goes out of scope. The Lock() method must not be called if the
133   // lock has already been acquired.
134   //
135   // Returns true on success.
136   // Returns false on error, in which case error_msg will contain more
137   // information on the error.
138   //
139   // The 'error_msg' argument must not be null.
140   //
141   // This is intended to be used to avoid race conditions when multiple
142   // processes generate oat files, such as when a foreground Activity and
143   // a background Service both use DexClassLoaders pointing to the same dex
144   // file.
145   bool Lock(std::string* error_msg);
146 
147   // Return what action needs to be taken to produce up-to-date code for this
148   // dex location that is at least as good as an oat file generated with the
149   // given compiler filter.
150   DexOptNeeded GetDexOptNeeded(CompilerFilter::Filter target_compiler_filter);
151 
152   // Returns true if there is up-to-date code for this dex location,
153   // irrespective of the compiler filter of the up-to-date code.
154   bool IsUpToDate();
155 
156   // Return code used when attempting to generate updated code.
157   enum ResultOfAttemptToUpdate {
158     kUpdateFailed,        // We tried making the code up to date, but
159                           // encountered an unexpected failure.
160     kUpdateNotAttempted,  // We wanted to update the code, but determined we
161                           // should not make the attempt.
162     kUpdateSucceeded      // We successfully made the code up to date
163                           // (possibly by doing nothing).
164   };
165 
166   // Attempts to generate or relocate the oat file as needed to make it up to
167   // date with in a way that is at least as good as an oat file generated with
168   // the given compiler filter.
169   // Returns the result of attempting to update the code.
170   //
171   // If the result is not kUpdateSucceeded, the value of error_msg will be set
172   // to a string describing why there was a failure or the update was not
173   // attempted. error_msg must not be null.
174   ResultOfAttemptToUpdate MakeUpToDate(CompilerFilter::Filter target_compiler_filter,
175                                        std::string* error_msg);
176 
177   // Returns an oat file that can be used for loading dex files.
178   // Returns null if no suitable oat file was found.
179   //
180   // After this call, no other methods of the OatFileAssistant should be
181   // called, because access to the loaded oat file has been taken away from
182   // the OatFileAssistant object.
183   std::unique_ptr<OatFile> GetBestOatFile();
184 
185   // Open and returns an image space associated with the oat file.
186   gc::space::ImageSpace* OpenImageSpace(const OatFile* oat_file);
187 
188   // Loads the dex files in the given oat file for the given dex location.
189   // The oat file should be up to date for the given dex location.
190   // This loads multiple dex files in the case of multidex.
191   // Returns an empty vector if no dex files for that location could be loaded
192   // from the oat file.
193   //
194   // The caller is responsible for freeing the dex_files returned, if any. The
195   // dex_files will only remain valid as long as the oat_file is valid.
196   static std::vector<std::unique_ptr<const DexFile>> LoadDexFiles(
197       const OatFile& oat_file, const char* dex_location);
198 
199   // Returns true if there are dex files in the original dex location that can
200   // be compiled with dex2oat for this dex location.
201   // Returns false if there is no original dex file, or if the original dex
202   // file is an apk/zip without a classes.dex entry.
203   bool HasOriginalDexFiles();
204 
205   // If the dex file has been installed with a compiled oat file alongside
206   // it, the compiled oat file will have the extension .odex, and is referred
207   // to as the odex file. It is called odex for legacy reasons; the file is
208   // really an oat file. The odex file will often, but not always, have a
209   // patch delta of 0 and need to be relocated before use for the purposes of
210   // ASLR. The odex file is treated as if it were read-only.
211   // These methods return the location and status of the odex file for the dex
212   // location.
213   // Notes:
214   //  * OdexFileName may return null if the odex file name could not be
215   //    determined.
216   const std::string* OdexFileName();
217   bool OdexFileExists();
218   OatStatus OdexFileStatus();
219   bool OdexFileIsOutOfDate();
220   bool OdexFileNeedsRelocation();
221   bool OdexFileIsUpToDate();
222   // Must only be called if the associated odex file exists, i.e, if
223   // |OdexFileExists() == true|.
224   CompilerFilter::Filter OdexFileCompilerFilter();
225 
226   // When the dex files is compiled on the target device, the oat file is the
227   // result. The oat file will have been relocated to some
228   // (possibly-out-of-date) offset for ASLR.
229   // These methods return the location and status of the target oat file for
230   // the dex location.
231   //
232   // Notes:
233   //  * OatFileName may return null if the oat file name could not be
234   //    determined.
235   const std::string* OatFileName();
236   bool OatFileExists();
237   OatStatus OatFileStatus();
238   bool OatFileIsOutOfDate();
239   bool OatFileNeedsRelocation();
240   bool OatFileIsUpToDate();
241   // Must only be called if the associated oat file exists, i.e, if
242   // |OatFileExists() == true|.
243   CompilerFilter::Filter OatFileCompilerFilter();
244 
245   // Return image file name. Does not cache since it relies on the oat file.
246   std::string ArtFileName(const OatFile* oat_file) const;
247 
248   // These methods return the status for a given opened oat file with respect
249   // to the dex location.
250   OatStatus GivenOatFileStatus(const OatFile& file);
251   bool GivenOatFileIsOutOfDate(const OatFile& file);
252   bool GivenOatFileNeedsRelocation(const OatFile& file);
253   bool GivenOatFileIsUpToDate(const OatFile& file);
254 
255   // Generates the oat file by relocation from the named input file.
256   // This does not check the current status before attempting to relocate the
257   // oat file.
258   //
259   // If the result is not kUpdateSucceeded, the value of error_msg will be set
260   // to a string describing why there was a failure or the update was not
261   // attempted. error_msg must not be null.
262   ResultOfAttemptToUpdate RelocateOatFile(const std::string* input_file, std::string* error_msg);
263 
264   // Generate the oat file from the dex file using the given compiler filter.
265   // This does not check the current status before attempting to generate the
266   // oat file.
267   //
268   // If the result is not kUpdateSucceeded, the value of error_msg will be set
269   // to a string describing why there was a failure or the update was not
270   // attempted. error_msg must not be null.
271   ResultOfAttemptToUpdate GenerateOatFile(CompilerFilter::Filter filter, std::string* error_msg);
272 
273   // Executes dex2oat using the current runtime configuration overridden with
274   // the given arguments. This does not check to see if dex2oat is enabled in
275   // the runtime configuration.
276   // Returns true on success.
277   //
278   // If there is a failure, the value of error_msg will be set to a string
279   // describing why there was failure. error_msg must not be null.
280   //
281   // TODO: The OatFileAssistant probably isn't the right place to have this
282   // function.
283   static bool Dex2Oat(const std::vector<std::string>& args, std::string* error_msg);
284 
285   // Constructs the odex file name for the given dex location.
286   // Returns true on success, in which case odex_filename is set to the odex
287   // file name.
288   // Returns false on error, in which case error_msg describes the error.
289   // Neither odex_filename nor error_msg may be null.
290   static bool DexFilenameToOdexFilename(const std::string& location,
291       InstructionSet isa, std::string* odex_filename, std::string* error_msg);
292 
293   static uint32_t CalculateCombinedImageChecksum(InstructionSet isa = kRuntimeISA);
294 
295  private:
296   struct ImageInfo {
297     uint32_t oat_checksum = 0;
298     uintptr_t oat_data_begin = 0;
299     int32_t patch_delta = 0;
300     std::string location;
301   };
302 
303   // Returns the path to the dalvik cache directory.
304   // Does not check existence of the cache or try to create it.
305   // Includes the trailing slash.
306   // Returns an empty string if we can't get the dalvik cache directory path.
307   std::string DalvikCacheDirectory();
308 
309   // Returns the current image location.
310   // Returns an empty string if the image location could not be retrieved.
311   //
312   // TODO: This method should belong with an image file manager, not
313   // the oat file assistant.
314   static std::string ImageLocation();
315 
316   // Gets the dex checksum required for an up-to-date oat file.
317   // Returns dex_checksum if a required checksum was located. Returns
318   // null if the required checksum was not found.
319   // The caller shouldn't clean up or free the returned pointer.
320   // This sets the has_original_dex_files_ field to true if a checksum was
321   // found for the dex_location_ dex file.
322   const uint32_t* GetRequiredDexChecksum();
323 
324   // Returns the loaded odex file.
325   // Loads the file if needed. Returns null if the file failed to load.
326   // The caller shouldn't clean up or free the returned pointer.
327   const OatFile* GetOdexFile();
328 
329   // Returns true if the compiler filter used to generate the odex file is at
330   // least as good as the given target filter.
331   bool OdexFileCompilerFilterIsOkay(CompilerFilter::Filter target);
332 
333   // Returns true if the odex file is opened executable.
334   bool OdexFileIsExecutable();
335 
336   // Returns true if the odex file has patch info required to run patchoat.
337   bool OdexFileHasPatchInfo();
338 
339   // Clear any cached information about the odex file that depends on the
340   // contents of the file.
341   void ClearOdexFileCache();
342 
343   // Returns the loaded oat file.
344   // Loads the file if needed. Returns null if the file failed to load.
345   // The caller shouldn't clean up or free the returned pointer.
346   const OatFile* GetOatFile();
347 
348   // Returns true if the compiler filter used to generate the oat file is at
349   // least as good as the given target filter.
350   bool OatFileCompilerFilterIsOkay(CompilerFilter::Filter target);
351 
352   // Returns true if the oat file is opened executable.
353   bool OatFileIsExecutable();
354 
355   // Returns true if the oat file has patch info required to run patchoat.
356   bool OatFileHasPatchInfo();
357 
358   // Clear any cached information about the oat file that depends on the
359   // contents of the file.
360   void ClearOatFileCache();
361 
362   // Returns the loaded image info.
363   // Loads the image info if needed. Returns null if the image info failed
364   // to load.
365   // The caller shouldn't clean up or free the returned pointer.
366   const ImageInfo* GetImageInfo();
367 
368   uint32_t GetCombinedImageChecksum();
369 
370   // To implement Lock(), we lock a dummy file where the oat file would go
371   // (adding ".flock" to the target file name) and retain the lock for the
372   // remaining lifetime of the OatFileAssistant object.
373   ScopedFlock flock_;
374 
375   std::string dex_location_;
376 
377   // In a properly constructed OatFileAssistant object, isa_ should be either
378   // the 32 or 64 bit variant for the current device.
379   const InstructionSet isa_ = kNone;
380 
381   // Whether the profile has recently changed.
382   bool profile_changed_ = false;
383 
384   // Whether we will attempt to load oat files executable.
385   bool load_executable_ = false;
386 
387   // Cached value of the required dex checksum.
388   // This should be accessed only by the GetRequiredDexChecksum() method.
389   uint32_t cached_required_dex_checksum_;
390   bool required_dex_checksum_attempted_ = false;
391   bool required_dex_checksum_found_;
392   bool has_original_dex_files_;
393 
394   // Cached value of the odex file name.
395   // This should be accessed only by the OdexFileName() method.
396   bool cached_odex_file_name_attempted_ = false;
397   bool cached_odex_file_name_found_;
398   std::string cached_odex_file_name_;
399 
400   // Cached value of the loaded odex file.
401   // Use the GetOdexFile method rather than accessing this directly, unless you
402   // know the odex file isn't out of date.
403   bool odex_file_load_attempted_ = false;
404   std::unique_ptr<OatFile> cached_odex_file_;
405 
406   // Cached results for OdexFileIsOutOfDate
407   bool odex_file_is_out_of_date_attempted_ = false;
408   bool cached_odex_file_is_out_of_date_;
409 
410   // Cached results for OdexFileIsUpToDate
411   bool odex_file_is_up_to_date_attempted_ = false;
412   bool cached_odex_file_is_up_to_date_;
413 
414   // Cached value of the oat file name.
415   // This should be accessed only by the OatFileName() method.
416   bool cached_oat_file_name_attempted_ = false;
417   bool cached_oat_file_name_found_;
418   std::string cached_oat_file_name_;
419 
420   // Cached value of the loaded oat file.
421   // Use the GetOatFile method rather than accessing this directly, unless you
422   // know the oat file isn't out of date.
423   bool oat_file_load_attempted_ = false;
424   std::unique_ptr<OatFile> cached_oat_file_;
425 
426   // Cached results for OatFileIsOutOfDate
427   bool oat_file_is_out_of_date_attempted_ = false;
428   bool cached_oat_file_is_out_of_date_;
429 
430   // Cached results for OatFileIsUpToDate
431   bool oat_file_is_up_to_date_attempted_ = false;
432   bool cached_oat_file_is_up_to_date_;
433 
434   // Cached value of the image info.
435   // Use the GetImageInfo method rather than accessing these directly.
436   // TODO: The image info should probably be moved out of the oat file
437   // assistant to an image file manager.
438   bool image_info_load_attempted_ = false;
439   bool image_info_load_succeeded_ = false;
440   ImageInfo cached_image_info_;
441   uint32_t combined_image_checksum_ = 0;
442 
443   // For debugging only.
444   // If this flag is set, the oat or odex file has been released to the user
445   // of the OatFileAssistant object and the OatFileAssistant object is in a
446   // bad state and should no longer be used.
447   bool oat_file_released_ = false;
448 
449   DISALLOW_COPY_AND_ASSIGN(OatFileAssistant);
450 };
451 
452 std::ostream& operator << (std::ostream& stream, const OatFileAssistant::OatStatus status);
453 
454 }  // namespace art
455 
456 #endif  // ART_RUNTIME_OAT_FILE_ASSISTANT_H_
457