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 
32 namespace art {
33 
34 namespace gc {
35 namespace space {
36 class ImageSpace;
37 }  // namespace space
38 }  // namespace gc
39 
40 // Class for assisting with oat file management.
41 //
42 // This class collects common utilities for determining the status of an oat
43 // file on the device, updating the oat file, and loading the oat file.
44 //
45 // The oat file assistant is intended to be used with dex locations not on the
46 // boot class path. See the IsInBootClassPath method for a way to check if the
47 // dex location is in the boot class path.
48 class OatFileAssistant {
49  public:
50   // The default compile filter to use when optimizing dex file at load time if they
51   // are out of date.
52   static const CompilerFilter::Filter kDefaultCompilerFilterForDexLoading =
53       CompilerFilter::kQuicken;
54 
55   enum DexOptNeeded {
56     // No dexopt should (or can) be done to update the apk/jar.
57     // Matches Java: dalvik.system.DexFile.NO_DEXOPT_NEEDED = 0
58     kNoDexOptNeeded = 0,
59 
60     // dex2oat should be run to update the apk/jar from scratch.
61     // Matches Java: dalvik.system.DexFile.DEX2OAT_FROM_SCRATCH = 1
62     kDex2OatFromScratch = 1,
63 
64     // dex2oat should be run to update the apk/jar because the existing code
65     // is out of date with respect to the boot image.
66     // Matches Java: dalvik.system.DexFile.DEX2OAT_FOR_BOOT_IMAGE
67     kDex2OatForBootImage = 2,
68 
69     // dex2oat should be run to update the apk/jar because the existing code
70     // is out of date with respect to the target compiler filter.
71     // Matches Java: dalvik.system.DexFile.DEX2OAT_FOR_FILTER
72     kDex2OatForFilter = 3,
73 
74     // dex2oat should be run to update the apk/jar because the existing code
75     // is not relocated to match the boot image.
76     // Matches Java: dalvik.system.DexFile.DEX2OAT_FOR_RELOCATION
77     kDex2OatForRelocation = 4,
78   };
79 
80   enum OatStatus {
81     // kOatCannotOpen - The oat file cannot be opened, because it does not
82     // exist, is unreadable, or otherwise corrupted.
83     kOatCannotOpen,
84 
85     // kOatDexOutOfDate - The oat file is out of date with respect to the dex file.
86     kOatDexOutOfDate,
87 
88     // kOatBootImageOutOfDate - The oat file is up to date with respect to the
89     // dex file, but is out of date with respect to the boot image.
90     kOatBootImageOutOfDate,
91 
92     // kOatRelocationOutOfDate - The oat file is up to date with respect to
93     // the dex file and boot image, but contains compiled code that has the
94     // wrong patch delta with respect to the boot image. Patchoat should be
95     // run on the oat file to update the patch delta of the compiled code to
96     // match the boot image.
97     kOatRelocationOutOfDate,
98 
99     // kOatUpToDate - The oat file is completely up to date with respect to
100     // the dex file and boot image.
101     kOatUpToDate,
102   };
103 
104   // Constructs an OatFileAssistant object to assist the oat file
105   // corresponding to the given dex location with the target instruction set.
106   //
107   // The dex_location must not be null and should remain available and
108   // unchanged for the duration of the lifetime of the OatFileAssistant object.
109   // Typically the dex_location is the absolute path to the original,
110   // un-optimized dex file.
111   //
112   // Note: Currently the dex_location must have an extension.
113   // TODO: Relax this restriction?
114   //
115   // The isa should be either the 32 bit or 64 bit variant for the current
116   // device. For example, on an arm device, use arm or arm64. An oat file can
117   // be loaded executable only if the ISA matches the current runtime.
118   //
119   // load_executable should be true if the caller intends to try and load
120   // executable code for this dex location.
121   OatFileAssistant(const char* dex_location,
122                    const InstructionSet isa,
123                    bool load_executable);
124 
125   ~OatFileAssistant();
126 
127   // Returns true if the dex location refers to an element of the boot class
128   // path.
129   bool IsInBootClassPath();
130 
131   // Obtains a lock on the target oat file.
132   // Only one OatFileAssistant object can hold the lock for a target oat file
133   // at a time. The Lock is released automatically when the OatFileAssistant
134   // object goes out of scope. The Lock() method must not be called if the
135   // lock has already been acquired.
136   //
137   // Returns true on success.
138   // Returns false on error, in which case error_msg will contain more
139   // information on the error.
140   //
141   // The 'error_msg' argument must not be null.
142   //
143   // This is intended to be used to avoid race conditions when multiple
144   // processes generate oat files, such as when a foreground Activity and
145   // a background Service both use DexClassLoaders pointing to the same dex
146   // file.
147   bool Lock(std::string* error_msg);
148 
149   // Return what action needs to be taken to produce up-to-date code for this
150   // dex location that is at least as good as an oat file generated with the
151   // given compiler filter. profile_changed should be true to indicate the
152   // profile has recently changed for this dex location.
153   // Returns a positive status code if the status refers to the oat file in
154   // the oat location. Returns a negative status code if the status refers to
155   // the oat file in the odex location.
156   int GetDexOptNeeded(CompilerFilter::Filter target_compiler_filter, bool profile_changed = false);
157 
158   // Returns true if there is up-to-date code for this dex location,
159   // irrespective of the compiler filter of the up-to-date code.
160   bool IsUpToDate();
161 
162   // Return code used when attempting to generate updated code.
163   enum ResultOfAttemptToUpdate {
164     kUpdateFailed,        // We tried making the code up to date, but
165                           // encountered an unexpected failure.
166     kUpdateNotAttempted,  // We wanted to update the code, but determined we
167                           // should not make the attempt.
168     kUpdateSucceeded      // We successfully made the code up to date
169                           // (possibly by doing nothing).
170   };
171 
172   // Attempts to generate or relocate the oat file as needed to make it up to
173   // date based on the current runtime and compiler options.
174   // profile_changed should be true to indicate the profile has recently
175   // changed for this dex location.
176   //
177   // Returns the result of attempting to update the code.
178   //
179   // If the result is not kUpdateSucceeded, the value of error_msg will be set
180   // to a string describing why there was a failure or the update was not
181   // attempted. error_msg must not be null.
182   ResultOfAttemptToUpdate MakeUpToDate(bool profile_changed, std::string* error_msg);
183 
184   // Returns an oat file that can be used for loading dex files.
185   // Returns null if no suitable oat file was found.
186   //
187   // After this call, no other methods of the OatFileAssistant should be
188   // called, because access to the loaded oat file has been taken away from
189   // the OatFileAssistant object.
190   std::unique_ptr<OatFile> GetBestOatFile();
191 
192   // Returns a human readable description of the status of the code for the
193   // dex file. The returned description is for debugging purposes only.
194   std::string GetStatusDump();
195 
196   // Open and returns an image space associated with the oat file.
197   static std::unique_ptr<gc::space::ImageSpace> OpenImageSpace(const OatFile* oat_file);
198 
199   // Loads the dex files in the given oat file for the given dex location.
200   // The oat file should be up to date for the given dex location.
201   // This loads multiple dex files in the case of multidex.
202   // Returns an empty vector if no dex files for that location could be loaded
203   // from the oat file.
204   //
205   // The caller is responsible for freeing the dex_files returned, if any. The
206   // dex_files will only remain valid as long as the oat_file is valid.
207   static std::vector<std::unique_ptr<const DexFile>> LoadDexFiles(
208       const OatFile& oat_file, const char* dex_location);
209 
210   // Returns true if there are dex files in the original dex location that can
211   // be compiled with dex2oat for this dex location.
212   // Returns false if there is no original dex file, or if the original dex
213   // file is an apk/zip without a classes.dex entry.
214   bool HasOriginalDexFiles();
215 
216   // If the dex file has been installed with a compiled oat file alongside
217   // it, the compiled oat file will have the extension .odex, and is referred
218   // to as the odex file. It is called odex for legacy reasons; the file is
219   // really an oat file. The odex file will often, but not always, have a
220   // patch delta of 0 and need to be relocated before use for the purposes of
221   // ASLR. The odex file is treated as if it were read-only.
222   //
223   // Returns the status of the odex file for the dex location.
224   OatStatus OdexFileStatus();
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   //
230   // Returns the status of the oat file for the dex location.
231   OatStatus OatFileStatus();
232 
233   // Executes dex2oat using the current runtime configuration overridden with
234   // the given arguments. This does not check to see if dex2oat is enabled in
235   // the runtime configuration.
236   // Returns true on success.
237   //
238   // If there is a failure, the value of error_msg will be set to a string
239   // describing why there was failure. error_msg must not be null.
240   //
241   // TODO: The OatFileAssistant probably isn't the right place to have this
242   // function.
243   static bool Dex2Oat(const std::vector<std::string>& args, std::string* error_msg);
244 
245   // Constructs the odex file name for the given dex location.
246   // Returns true on success, in which case odex_filename is set to the odex
247   // file name.
248   // Returns false on error, in which case error_msg describes the error and
249   // odex_filename is not changed.
250   // Neither odex_filename nor error_msg may be null.
251   static bool DexLocationToOdexFilename(const std::string& location,
252                                         InstructionSet isa,
253                                         std::string* odex_filename,
254                                         std::string* error_msg);
255 
256   // Constructs the oat file name for the given dex location.
257   // Returns true on success, in which case oat_filename is set to the oat
258   // file name.
259   // Returns false on error, in which case error_msg describes the error and
260   // oat_filename is not changed.
261   // Neither oat_filename nor error_msg may be null.
262   static bool DexLocationToOatFilename(const std::string& location,
263                                        InstructionSet isa,
264                                        std::string* oat_filename,
265                                        std::string* error_msg);
266 
267  private:
268   struct ImageInfo {
269     uint32_t oat_checksum = 0;
270     uintptr_t oat_data_begin = 0;
271     int32_t patch_delta = 0;
272     std::string location;
273 
274     static std::unique_ptr<ImageInfo> GetRuntimeImageInfo(InstructionSet isa,
275                                                           std::string* error_msg);
276   };
277 
278   class OatFileInfo {
279    public:
280     // Initially the info is for no file in particular. It will treat the
281     // file as out of date until Reset is called with a real filename to use
282     // the cache for.
283     // Pass true for is_oat_location if the information associated with this
284     // OatFileInfo is for the oat location, as opposed to the odex location.
285     OatFileInfo(OatFileAssistant* oat_file_assistant, bool is_oat_location);
286 
287     bool IsOatLocation();
288 
289     const std::string* Filename();
290 
291     // Returns true if this oat file can be used for running code. The oat
292     // file can be used for running code as long as it is not out of date with
293     // respect to the dex code or boot image. An oat file that is out of date
294     // with respect to relocation is considered useable, because it's possible
295     // to interpret the dex code rather than run the unrelocated compiled
296     // code.
297     bool IsUseable();
298 
299     // Returns the status of this oat file.
300     OatStatus Status();
301 
302     // Return the DexOptNeeded value for this oat file with respect to the
303     // given target_compilation_filter.
304     // profile_changed should be true to indicate the profile has recently
305     // changed for this dex location.
306     DexOptNeeded GetDexOptNeeded(CompilerFilter::Filter target_compiler_filter,
307                                  bool profile_changed);
308 
309     // Returns the loaded file.
310     // Loads the file if needed. Returns null if the file failed to load.
311     // The caller shouldn't clean up or free the returned pointer.
312     const OatFile* GetFile();
313 
314     // Returns true if the file is opened executable.
315     bool IsExecutable();
316 
317     // Clear any cached information about the file that depends on the
318     // contents of the file. This does not reset the provided filename.
319     void Reset();
320 
321     // Clear any cached information and switch to getting info about the oat
322     // file with the given filename.
323     void Reset(const std::string& filename);
324 
325     // Release the loaded oat file for runtime use.
326     // Returns null if the oat file hasn't been loaded or is out of date.
327     // Ensures the returned file is not loaded executable if it has unuseable
328     // compiled code.
329     //
330     // After this call, no other methods of the OatFileInfo should be
331     // called, because access to the loaded oat file has been taken away from
332     // the OatFileInfo object.
333     std::unique_ptr<OatFile> ReleaseFileForUse();
334 
335    private:
336     // Returns true if the compiler filter used to generate the file is at
337     // least as good as the given target filter. profile_changed should be
338     // true to indicate the profile has recently changed for this dex
339     // location.
340     bool CompilerFilterIsOkay(CompilerFilter::Filter target, bool profile_changed);
341 
342     // Release the loaded oat file.
343     // Returns null if the oat file hasn't been loaded.
344     //
345     // After this call, no other methods of the OatFileInfo should be
346     // called, because access to the loaded oat file has been taken away from
347     // the OatFileInfo object.
348     std::unique_ptr<OatFile> ReleaseFile();
349 
350     OatFileAssistant* oat_file_assistant_;
351     const bool is_oat_location_;
352 
353     bool filename_provided_ = false;
354     std::string filename_;
355 
356     bool load_attempted_ = false;
357     std::unique_ptr<OatFile> file_;
358 
359     bool status_attempted_ = false;
360     OatStatus status_ = OatStatus::kOatCannotOpen;
361 
362     // For debugging only.
363     // If this flag is set, the file has been released to the user and the
364     // OatFileInfo object is in a bad state and should no longer be used.
365     bool file_released_ = false;
366   };
367 
368   // Generate the oat file for the given info from the dex file using the
369   // current runtime compiler options and the specified filter.
370   // This does not check the current status before attempting to generate the
371   // oat file.
372   //
373   // If the result is not kUpdateSucceeded, the value of error_msg will be set
374   // to a string describing why there was a failure or the update was not
375   // attempted. error_msg must not be null.
376   ResultOfAttemptToUpdate GenerateOatFileNoChecks(OatFileInfo& info,
377                                                   CompilerFilter::Filter target,
378                                                   std::string* error_msg);
379 
380   // Return info for the best oat file.
381   OatFileInfo& GetBestInfo();
382 
383   // Returns true if the dex checksums in the given vdex file are up to date
384   // with respect to the dex location. If the dex checksums are not up to
385   // date, error_msg is updated with a message describing the problem.
386   bool DexChecksumUpToDate(const VdexFile& file, std::string* error_msg);
387 
388   // Returns true if the dex checksums in the given oat file are up to date
389   // with respect to the dex location. If the dex checksums are not up to
390   // date, error_msg is updated with a message describing the problem.
391   bool DexChecksumUpToDate(const OatFile& file, std::string* error_msg);
392 
393   // Return the status for a given opened oat file with respect to the dex
394   // location.
395   OatStatus GivenOatFileStatus(const OatFile& file);
396 
397   // Returns the current image location.
398   // Returns an empty string if the image location could not be retrieved.
399   //
400   // TODO: This method should belong with an image file manager, not
401   // the oat file assistant.
402   static std::string ImageLocation();
403 
404   // Gets the dex checksums required for an up-to-date oat file.
405   // Returns cached_required_dex_checksums if the required checksums were
406   // located. Returns null if the required checksums were not found.  The
407   // caller shouldn't clean up or free the returned pointer.  This sets the
408   // has_original_dex_files_ field to true if the checksums were found for the
409   // dex_location_ dex file.
410   const std::vector<uint32_t>* GetRequiredDexChecksums();
411 
412   // Returns the loaded image info.
413   // Loads the image info if needed. Returns null if the image info failed
414   // to load.
415   // The caller shouldn't clean up or free the returned pointer.
416   const ImageInfo* GetImageInfo();
417 
418   // To implement Lock(), we lock a dummy file where the oat file would go
419   // (adding ".flock" to the target file name) and retain the lock for the
420   // remaining lifetime of the OatFileAssistant object.
421   ScopedFlock flock_;
422 
423   std::string dex_location_;
424 
425   // Whether or not the parent directory of the dex file is writable.
426   bool dex_parent_writable_ = false;
427 
428   // In a properly constructed OatFileAssistant object, isa_ should be either
429   // the 32 or 64 bit variant for the current device.
430   const InstructionSet isa_ = kNone;
431 
432   // Whether we will attempt to load oat files executable.
433   bool load_executable_ = false;
434 
435   // Cached value of the required dex checksums.
436   // This should be accessed only by the GetRequiredDexChecksums() method.
437   std::vector<uint32_t> cached_required_dex_checksums_;
438   bool required_dex_checksums_attempted_ = false;
439   bool required_dex_checksums_found_;
440   bool has_original_dex_files_;
441 
442   OatFileInfo odex_;
443   OatFileInfo oat_;
444 
445   // Cached value of the image info.
446   // Use the GetImageInfo method rather than accessing these directly.
447   // TODO: The image info should probably be moved out of the oat file
448   // assistant to an image file manager.
449   bool image_info_load_attempted_ = false;
450   std::unique_ptr<ImageInfo> cached_image_info_;
451 
452   friend class OatFileAssistantTest;
453 
454   DISALLOW_COPY_AND_ASSIGN(OatFileAssistant);
455 };
456 
457 std::ostream& operator << (std::ostream& stream, const OatFileAssistant::OatStatus status);
458 
459 }  // namespace art
460 
461 #endif  // ART_RUNTIME_OAT_FILE_ASSISTANT_H_
462