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/os.h"
27 #include "base/scoped_flock.h"
28 #include "base/unix_file/fd_file.h"
29 #include "compiler_filter.h"
30 #include "class_loader_context.h"
31 #include "oat_file.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     // No dexopt should (or can) be done to update the apk/jar.
53     // Matches Java: dalvik.system.DexFile.NO_DEXOPT_NEEDED = 0
54     kNoDexOptNeeded = 0,
55 
56     // dex2oat should be run to update the apk/jar from scratch.
57     // Matches Java: dalvik.system.DexFile.DEX2OAT_FROM_SCRATCH = 1
58     kDex2OatFromScratch = 1,
59 
60     // dex2oat should be run to update the apk/jar because the existing code
61     // is out of date with respect to the boot image.
62     // Matches Java: dalvik.system.DexFile.DEX2OAT_FOR_BOOT_IMAGE
63     kDex2OatForBootImage = 2,
64 
65     // dex2oat should be run to update the apk/jar because the existing code
66     // is out of date with respect to the target compiler filter.
67     // Matches Java: dalvik.system.DexFile.DEX2OAT_FOR_FILTER
68     kDex2OatForFilter = 3,
69   };
70 
71   enum OatStatus {
72     // kOatCannotOpen - The oat file cannot be opened, because it does not
73     // exist, is unreadable, or otherwise corrupted.
74     kOatCannotOpen,
75 
76     // kOatDexOutOfDate - The oat file is out of date with respect to the dex file.
77     kOatDexOutOfDate,
78 
79     // kOatBootImageOutOfDate - The oat file is up to date with respect to the
80     // dex file, but is out of date with respect to the boot image.
81     kOatBootImageOutOfDate,
82 
83     // kOatUpToDate - The oat file is completely up to date with respect to
84     // the dex file and boot image.
85     kOatUpToDate,
86   };
87 
88   // Constructs an OatFileAssistant object to assist the oat file
89   // corresponding to the given dex location with the target instruction set.
90   //
91   // The dex_location must not be null and should remain available and
92   // unchanged for the duration of the lifetime of the OatFileAssistant object.
93   // Typically the dex_location is the absolute path to the original,
94   // un-optimized dex file.
95   //
96   // Note: Currently the dex_location must have an extension.
97   // TODO: Relax this restriction?
98   //
99   // The isa should be either the 32 bit or 64 bit variant for the current
100   // device. For example, on an arm device, use arm or arm64. An oat file can
101   // be loaded executable only if the ISA matches the current runtime.
102   //
103   // load_executable should be true if the caller intends to try and load
104   // executable code for this dex location.
105   //
106   // only_load_system_executable should be true if the caller intends to have
107   // only oat files from /system loaded executable.
108   OatFileAssistant(const char* dex_location,
109                    const InstructionSet isa,
110                    bool load_executable,
111                    bool only_load_system_executable = false);
112 
113   // Similar to this(const char*, const InstructionSet, bool), however, if a valid zip_fd is
114   // provided, vdex, oat, and zip files will be read from vdex_fd, oat_fd and zip_fd respectively.
115   // Otherwise, dex_location will be used to construct necessary filenames.
116   OatFileAssistant(const char* dex_location,
117                    const InstructionSet isa,
118                    bool load_executable,
119                    bool only_load_system_executable,
120                    int vdex_fd,
121                    int oat_fd,
122                    int zip_fd);
123 
124   // Returns true if the dex location refers to an element of the boot class
125   // path.
126   bool IsInBootClassPath();
127 
128   // Return what action needs to be taken to produce up-to-date code for this
129   // dex location. If "downgrade" is set to false, it verifies if the current
130   // compiler filter is at least as good as an oat file generated with the
131   // given compiler filter otherwise, if its set to true, it checks whether
132   // the oat file generated with the target filter will be downgraded as
133   // compared to the current state. For example, if the current compiler filter is
134   // quicken, and target filter is verify, it will recommend to dexopt, while
135   // if the target filter is speed profile, it will recommend to keep it in its
136   // current state.
137   // profile_changed should be true to indicate the profile has recently changed
138   // for this dex location.
139   // If the purpose of the dexopt is to downgrade the compiler filter,
140   // set downgrade to true.
141   // Returns a positive status code if the status refers to the oat file in
142   // the oat location. Returns a negative status code if the status refers to
143   // the oat file in the odex location.
144   int GetDexOptNeeded(CompilerFilter::Filter target_compiler_filter,
145                       ClassLoaderContext* context,
146                       const std::vector<int>& context_fds,
147                       bool profile_changed = false,
148                       bool downgrade = false);
149 
150   // Returns true if there is up-to-date code for this dex location,
151   // irrespective of the compiler filter of the up-to-date code.
152   bool IsUpToDate();
153 
154   // Returns an oat file that can be used for loading dex files.
155   // Returns null if no suitable oat file was found.
156   //
157   // After this call, no other methods of the OatFileAssistant should be
158   // called, because access to the loaded oat file has been taken away from
159   // the OatFileAssistant object.
160   std::unique_ptr<OatFile> GetBestOatFile();
161 
162   // Returns a human readable description of the status of the code for the
163   // dex file. The returned description is for debugging purposes only.
164   std::string GetStatusDump();
165 
166   // Computes the optimization status of the given dex file. The result is
167   // returned via the two output parameters.
168   //   - out_compilation_filter: the level of optimizations (compiler filter)
169   //   - out_compilation_reason: the optimization reason. The reason might
170   //        be "unknown" if the compiler artifacts were not annotated during optimizations.
171   //
172   // This method will try to mimic the runtime effect of loading the dex file.
173   // For example, if there is no usable oat file, the compiler filter will be set
174   // to "run-from-apk".
175   static void GetOptimizationStatus(const std::string& filename,
176                                     InstructionSet isa,
177                                     std::string* out_compilation_filter,
178                                     std::string* out_compilation_reason);
179 
180   // Open and returns an image space associated with the oat file.
181   static std::unique_ptr<gc::space::ImageSpace> OpenImageSpace(const OatFile* oat_file);
182 
183   // Loads the dex files in the given oat file for the given dex location.
184   // The oat file should be up to date for the given dex location.
185   // This loads multiple dex files in the case of multidex.
186   // Returns an empty vector if no dex files for that location could be loaded
187   // from the oat file.
188   //
189   // The caller is responsible for freeing the dex_files returned, if any. The
190   // dex_files will only remain valid as long as the oat_file is valid.
191   static std::vector<std::unique_ptr<const DexFile>> LoadDexFiles(
192       const OatFile& oat_file, const char* dex_location);
193 
194   // Same as `std::vector<std::unique_ptr<const DexFile>> LoadDexFiles(...)` with the difference:
195   //   - puts the dex files in the given vector
196   //   - returns whether or not all dex files were successfully opened
197   static bool LoadDexFiles(const OatFile& oat_file,
198                            const std::string& dex_location,
199                            std::vector<std::unique_ptr<const DexFile>>* out_dex_files);
200 
201   // Returns whether this is an apk/zip wit a classes.dex entry.
202   bool HasDexFiles();
203 
204   // If the dex file has been installed with a compiled oat file alongside
205   // it, the compiled oat file will have the extension .odex, and is referred
206   // to as the odex file. It is called odex for legacy reasons; the file is
207   // really an oat file. The odex file will often, but not always, have a
208   // patch delta of 0 and need to be relocated before use for the purposes of
209   // ASLR. The odex file is treated as if it were read-only.
210   //
211   // Returns the status of the odex file for the dex location.
212   OatStatus OdexFileStatus();
213 
214   // When the dex files is compiled on the target device, the oat file is the
215   // result. The oat file will have been relocated to some
216   // (possibly-out-of-date) offset for ASLR.
217   //
218   // Returns the status of the oat file for the dex location.
219   OatStatus OatFileStatus();
220 
221   // Constructs the odex file name for the given dex location.
222   // Returns true on success, in which case odex_filename is set to the odex
223   // file name.
224   // Returns false on error, in which case error_msg describes the error and
225   // odex_filename is not changed.
226   // Neither odex_filename nor error_msg may be null.
227   static bool DexLocationToOdexFilename(const std::string& location,
228                                         InstructionSet isa,
229                                         std::string* odex_filename,
230                                         std::string* error_msg);
231 
232   // Constructs the oat file name for the given dex location.
233   // Returns true on success, in which case oat_filename is set to the oat
234   // file name.
235   // Returns false on error, in which case error_msg describes the error and
236   // oat_filename is not changed.
237   // Neither oat_filename nor error_msg may be null.
238   static bool DexLocationToOatFilename(const std::string& location,
239                                        InstructionSet isa,
240                                        std::string* oat_filename,
241                                        std::string* error_msg);
242 
243   // Computes the location checksum, dex location and vdex filename by combining
244   // the checksums of the individual dex files. If the data directory of the process
245   // is known, creates an absolute path in that directory and tries to infer path
246   // of a corresponding vdex file. Otherwise only creates a basename dex_location
247   // from the combined checksums. Returns true if all out-arguments have been set.
248   static bool AnonymousDexVdexLocation(const std::vector<const DexFile::Header*>& dex_headers,
249                                        InstructionSet isa,
250                                        /* out */ uint32_t* location_checksum,
251                                        /* out */ std::string* dex_location,
252                                        /* out */ std::string* vdex_filename);
253 
254   // Returns true if a filename (given as basename) is a name of a vdex for
255   // anonymous dex file(s) created by AnonymousDexVdexLocation.
256   static bool IsAnonymousVdexBasename(const std::string& basename);
257 
258  private:
259   class OatFileInfo {
260    public:
261     // Initially the info is for no file in particular. It will treat the
262     // file as out of date until Reset is called with a real filename to use
263     // the cache for.
264     // Pass true for is_oat_location if the information associated with this
265     // OatFileInfo is for the oat location, as opposed to the odex location.
266     OatFileInfo(OatFileAssistant* oat_file_assistant, bool is_oat_location);
267 
268     bool IsOatLocation();
269 
270     const std::string* Filename();
271 
272     // Returns true if this oat file can be used for running code. The oat
273     // file can be used for running code as long as it is not out of date with
274     // respect to the dex code or boot image. An oat file that is out of date
275     // with respect to relocation is considered useable, because it's possible
276     // to interpret the dex code rather than run the unrelocated compiled
277     // code.
278     bool IsUseable();
279 
280     // Returns the status of this oat file.
281     OatStatus Status();
282 
283     // Return the DexOptNeeded value for this oat file with respect to the
284     // given target_compilation_filter.
285     // profile_changed should be true to indicate the profile has recently
286     // changed for this dex location.
287     // downgrade should be true if the purpose of dexopt is to downgrade the
288     // compiler filter.
289     DexOptNeeded GetDexOptNeeded(CompilerFilter::Filter target_compiler_filter,
290                                  ClassLoaderContext* context,
291                                  const std::vector<int>& context_fds,
292                                  bool profile_changed,
293                                  bool downgrade);
294 
295     // Returns the loaded file.
296     // Loads the file if needed. Returns null if the file failed to load.
297     // The caller shouldn't clean up or free the returned pointer.
298     const OatFile* GetFile();
299 
300     // Returns true if the file is opened executable.
301     bool IsExecutable();
302 
303     // Clear any cached information about the file that depends on the
304     // contents of the file. This does not reset the provided filename.
305     void Reset();
306 
307     // Clear any cached information and switch to getting info about the oat
308     // file with the given filename.
309     void Reset(const std::string& filename,
310                bool use_fd,
311                int zip_fd = -1,
312                int vdex_fd = -1,
313                int oat_fd = -1);
314 
315     // Release the loaded oat file for runtime use.
316     // Returns null if the oat file hasn't been loaded or is out of date.
317     // Ensures the returned file is not loaded executable if it has unuseable
318     // compiled code.
319     //
320     // After this call, no other methods of the OatFileInfo should be
321     // called, because access to the loaded oat file has been taken away from
322     // the OatFileInfo object.
323     std::unique_ptr<OatFile> ReleaseFileForUse();
324 
325    private:
326     // Returns true if the compiler filter used to generate the file is at
327     // least as good as the given target filter. profile_changed should be
328     // true to indicate the profile has recently changed for this dex
329     // location.
330     // downgrade should be true if the purpose of dexopt is to downgrade the
331     // compiler filter.
332     bool CompilerFilterIsOkay(CompilerFilter::Filter target, bool profile_changed, bool downgrade);
333 
334     bool ClassLoaderContextIsOkay(ClassLoaderContext* context, const std::vector<int>& context_fds);
335 
336     // Release the loaded oat file.
337     // Returns null if the oat file hasn't been loaded.
338     //
339     // After this call, no other methods of the OatFileInfo should be
340     // called, because access to the loaded oat file has been taken away from
341     // the OatFileInfo object.
342     std::unique_ptr<OatFile> ReleaseFile();
343 
344     OatFileAssistant* oat_file_assistant_;
345     const bool is_oat_location_;
346 
347     bool filename_provided_ = false;
348     std::string filename_;
349 
350     int zip_fd_ = -1;
351     int oat_fd_ = -1;
352     int vdex_fd_ = -1;
353     bool use_fd_ = false;
354 
355     bool load_attempted_ = false;
356     std::unique_ptr<OatFile> file_;
357 
358     bool status_attempted_ = false;
359     OatStatus status_ = OatStatus::kOatCannotOpen;
360 
361     // For debugging only.
362     // If this flag is set, the file has been released to the user and the
363     // OatFileInfo object is in a bad state and should no longer be used.
364     bool file_released_ = false;
365   };
366 
367   // Return info for the best oat file.
368   OatFileInfo& GetBestInfo();
369 
370   // Returns true when vdex/oat/odex files should be read from file descriptors.
371   // The method checks the value of zip_fd_, and if the value is valid, returns
372   // true. This is required to have a deterministic behavior around how different
373   // files are being read.
374   bool UseFdToReadFiles();
375 
376   // Returns true if the dex checksums in the given vdex file are up to date
377   // with respect to the dex location. If the dex checksums are not up to
378   // date, error_msg is updated with a message describing the problem.
379   bool DexChecksumUpToDate(const VdexFile& file, std::string* error_msg);
380 
381   // Returns true if the dex checksums in the given oat file are up to date
382   // with respect to the dex location. If the dex checksums are not up to
383   // date, error_msg is updated with a message describing the problem.
384   bool DexChecksumUpToDate(const OatFile& file, std::string* error_msg);
385 
386   // Return the status for a given opened oat file with respect to the dex
387   // location.
388   OatStatus GivenOatFileStatus(const OatFile& file);
389 
390   // Gets the dex checksums required for an up-to-date oat file.
391   // Returns cached_required_dex_checksums if the required checksums were
392   // located. Returns null if the required checksums were not found.  The
393   // caller shouldn't clean up or free the returned pointer.  This sets the
394   // has_original_dex_files_ field to true if the checksums were found for the
395   // dex_location_ dex file.
396   const std::vector<uint32_t>* GetRequiredDexChecksums();
397 
398   // Validates the boot class path checksum of an OatFile.
399   bool ValidateBootClassPathChecksums(const OatFile& oat_file);
400 
401   std::string dex_location_;
402 
403   // Whether or not the parent directory of the dex file is writable.
404   bool dex_parent_writable_ = false;
405 
406   // In a properly constructed OatFileAssistant object, isa_ should be either
407   // the 32 or 64 bit variant for the current device.
408   const InstructionSet isa_ = InstructionSet::kNone;
409 
410   // Whether we will attempt to load oat files executable.
411   bool load_executable_ = false;
412 
413   // Whether only oat files on /system are loaded executable.
414   const bool only_load_system_executable_ = false;
415   // Whether the potential zip file only contains uncompressed dex.
416   // Will be set during GetRequiredDexChecksums.
417   bool zip_file_only_contains_uncompressed_dex_ = true;
418 
419   // Cached value of the required dex checksums.
420   // This should be accessed only by the GetRequiredDexChecksums() method.
421   std::vector<uint32_t> cached_required_dex_checksums_;
422   bool required_dex_checksums_attempted_ = false;
423   bool required_dex_checksums_found_;
424   bool has_original_dex_files_;
425 
426   OatFileInfo odex_;
427   OatFileInfo oat_;
428 
429   // File descriptor corresponding to apk, dex file, or zip.
430   int zip_fd_;
431 
432   std::string cached_boot_class_path_;
433   std::string cached_boot_class_path_checksums_;
434 
435   friend class OatFileAssistantTest;
436 
437   DISALLOW_COPY_AND_ASSIGN(OatFileAssistant);
438 };
439 
440 std::ostream& operator << (std::ostream& stream, const OatFileAssistant::OatStatus status);
441 
442 }  // namespace art
443 
444 #endif  // ART_RUNTIME_OAT_FILE_ASSISTANT_H_
445