blob: f3a0725f793d6bb075c30beb16ff3c156b76b8f4 [file] [log] [blame]
Richard Uhler66d874d2015-01-15 09:37:19 -08001/*
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#include "oat_file_assistant.h"
18
Richard Uhler46cc64f2016-11-14 14:53:55 +000019#include <sstream>
20
Richard Uhler66d874d2015-01-15 09:37:19 -080021#include <sys/stat.h>
Andreas Gampe9186ced2016-12-12 14:28:21 -080022
Andreas Gampec15a2f42017-04-21 12:09:39 -070023#include "android-base/stringprintf.h"
Andreas Gampe9186ced2016-12-12 14:28:21 -080024#include "android-base/strings.h"
25
Richard Uhler66d874d2015-01-15 09:37:19 -080026#include "base/logging.h"
Andreas Gampe5678db52017-06-08 14:11:18 -070027#include "base/stl_util.h"
Richard Uhler66d874d2015-01-15 09:37:19 -080028#include "class_linker.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070029#include "compiler_filter.h"
David Sehr97c381e2017-02-01 15:09:58 -080030#include "exec_utils.h"
Richard Uhler66d874d2015-01-15 09:37:19 -080031#include "gc/heap.h"
32#include "gc/space/image_space.h"
33#include "image.h"
34#include "oat.h"
35#include "os.h"
Richard Uhler66d874d2015-01-15 09:37:19 -080036#include "runtime.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070037#include "scoped_thread_state_change-inl.h"
Richard Uhler66d874d2015-01-15 09:37:19 -080038#include "utils.h"
Richard Uhler2f27abd2017-01-31 14:02:34 +000039#include "vdex_file.h"
Calin Juravle27e0d1f2017-07-26 00:16:07 -070040#include "class_loader_context.h"
Richard Uhler66d874d2015-01-15 09:37:19 -080041
42namespace art {
43
Richard Uhler69bcf2c2017-01-24 10:25:21 +000044using android::base::StringPrintf;
45
Narayan Kamath8943c1d2016-05-02 13:14:48 +010046std::ostream& operator << (std::ostream& stream, const OatFileAssistant::OatStatus status) {
47 switch (status) {
Richard Uhler03bc6592016-11-22 09:42:04 +000048 case OatFileAssistant::kOatCannotOpen:
49 stream << "kOatCannotOpen";
50 break;
51 case OatFileAssistant::kOatDexOutOfDate:
52 stream << "kOatDexOutOfDate";
53 break;
54 case OatFileAssistant::kOatBootImageOutOfDate:
55 stream << "kOatBootImageOutOfDate";
56 break;
57 case OatFileAssistant::kOatRelocationOutOfDate:
58 stream << "kOatRelocationOutOfDate";
Narayan Kamath8943c1d2016-05-02 13:14:48 +010059 break;
60 case OatFileAssistant::kOatUpToDate:
61 stream << "kOatUpToDate";
62 break;
Narayan Kamath8943c1d2016-05-02 13:14:48 +010063 default:
64 UNREACHABLE();
65 }
66
67 return stream;
68}
69
Richard Uhler66d874d2015-01-15 09:37:19 -080070OatFileAssistant::OatFileAssistant(const char* dex_location,
71 const InstructionSet isa,
72 bool load_executable)
Richard Uhler88bc6732016-11-14 14:38:03 +000073 : isa_(isa),
74 load_executable_(load_executable),
75 odex_(this, /*is_oat_location*/ false),
76 oat_(this, /*is_oat_location*/ true) {
Richard Uhler740eec92015-10-15 15:12:23 -070077 CHECK(dex_location != nullptr) << "OatFileAssistant: null dex location";
Calin Juravle357c66d2017-05-04 01:57:17 +000078
79 // Try to get the realpath for the dex location.
80 //
81 // This is OK with respect to dalvik cache naming scheme because we never
82 // generate oat files starting from symlinks which go into dalvik cache.
83 // (recall that the oat files in dalvik cache are encoded by replacing '/'
84 // with '@' in the path).
85 // The boot image oat files (which are symlinked in dalvik-cache) are not
86 // loaded via the oat file assistant.
87 //
88 // The only case when the dex location may resolve to a different path
89 // is for secondary dex files (e.g. /data/user/0 symlinks to /data/data and
90 // the app is free to create its own internal layout). Related to this it is
91 // worthwhile to mention that installd resolves the secondary dex location
92 // before calling dex2oat.
93 UniqueCPtr<const char[]> dex_location_real(realpath(dex_location, nullptr));
94 if (dex_location_real != nullptr) {
95 dex_location_.assign(dex_location_real.get());
96 } else {
97 // If we can't get the realpath of the location there's not much point in trying to move on.
98 PLOG(ERROR) << "Could not get the realpath of dex_location " << dex_location;
99 return;
100 }
Richard Uhler740eec92015-10-15 15:12:23 -0700101
Richard Uhler66d874d2015-01-15 09:37:19 -0800102 if (load_executable_ && isa != kRuntimeISA) {
103 LOG(WARNING) << "OatFileAssistant: Load executable specified, "
104 << "but isa is not kRuntimeISA. Will not attempt to load executable.";
105 load_executable_ = false;
106 }
107
Richard Uhler743bf362016-04-19 15:39:37 -0700108 // Get the odex filename.
Richard Uhlerd684f522016-04-19 13:24:41 -0700109 std::string error_msg;
Richard Uhler743bf362016-04-19 15:39:37 -0700110 std::string odex_file_name;
111 if (DexLocationToOdexFilename(dex_location_, isa_, &odex_file_name, &error_msg)) {
112 odex_.Reset(odex_file_name);
113 } else {
Richard Uhlerd684f522016-04-19 13:24:41 -0700114 LOG(WARNING) << "Failed to determine odex file name: " << error_msg;
115 }
116
Richard Uhler743bf362016-04-19 15:39:37 -0700117 // Get the oat filename.
Calin Juravle357c66d2017-05-04 01:57:17 +0000118 std::string oat_file_name;
119 if (DexLocationToOatFilename(dex_location_, isa_, &oat_file_name, &error_msg)) {
120 oat_.Reset(oat_file_name);
Richard Uhlerd684f522016-04-19 13:24:41 -0700121 } else {
Calin Juravle357c66d2017-05-04 01:57:17 +0000122 LOG(WARNING) << "Failed to determine oat file name for dex location "
Calin Juravle9bfc6bb2017-05-04 00:13:50 +0000123 << dex_location_ << ": " << error_msg;
Calin Juravle357c66d2017-05-04 01:57:17 +0000124 }
125
126 // Check if the dex directory is writable.
127 // This will be needed in most uses of OatFileAssistant and so it's OK to
128 // compute it eagerly. (the only use which will not make use of it is
129 // OatFileAssistant::GetStatusDump())
130 size_t pos = dex_location_.rfind('/');
131 if (pos == std::string::npos) {
132 LOG(WARNING) << "Failed to determine dex file parent directory: " << dex_location_;
133 } else {
134 std::string parent = dex_location_.substr(0, pos);
135 if (access(parent.c_str(), W_OK) == 0) {
136 dex_parent_writable_ = true;
137 } else {
138 VLOG(oat) << "Dex parent of " << dex_location_ << " is not writable: " << strerror(errno);
Richard Uhlerd684f522016-04-19 13:24:41 -0700139 }
Richard Uhler66d874d2015-01-15 09:37:19 -0800140 }
Richard Uhler66d874d2015-01-15 09:37:19 -0800141}
142
143OatFileAssistant::~OatFileAssistant() {
144 // Clean up the lock file.
Narayan Kamatha3d27eb2017-05-11 13:50:59 +0100145 if (flock_.get() != nullptr) {
146 unlink(flock_->GetPath().c_str());
Richard Uhler66d874d2015-01-15 09:37:19 -0800147 }
148}
149
150bool OatFileAssistant::IsInBootClassPath() {
151 // Note: We check the current boot class path, regardless of the ISA
152 // specified by the user. This is okay, because the boot class path should
153 // be the same for all ISAs.
154 // TODO: Can we verify the boot class path is the same for all ISAs?
155 Runtime* runtime = Runtime::Current();
156 ClassLinker* class_linker = runtime->GetClassLinker();
157 const auto& boot_class_path = class_linker->GetBootClassPath();
158 for (size_t i = 0; i < boot_class_path.size(); i++) {
Richard Uhler740eec92015-10-15 15:12:23 -0700159 if (boot_class_path[i]->GetLocation() == dex_location_) {
Richard Uhler66d874d2015-01-15 09:37:19 -0800160 VLOG(oat) << "Dex location " << dex_location_ << " is in boot class path";
161 return true;
162 }
163 }
164 return false;
165}
166
167bool OatFileAssistant::Lock(std::string* error_msg) {
168 CHECK(error_msg != nullptr);
Narayan Kamatha3d27eb2017-05-11 13:50:59 +0100169 CHECK(flock_.get() == nullptr) << "OatFileAssistant::Lock already acquired";
Richard Uhler66d874d2015-01-15 09:37:19 -0800170
Calin Juravle357c66d2017-05-04 01:57:17 +0000171 // Note the lock will only succeed for secondary dex files and in test
172 // environment.
173 //
174 // The lock *will fail* for all primary apks in a production environment.
175 // The app does not have permissions to create locks next to its dex location
176 // (be it system, data or vendor parition). We also cannot use the odex or
177 // oat location for the same reasoning.
178 //
179 // This is best effort and if it fails it's unlikely that we will be able
180 // to generate oat files anyway.
181 std::string lock_file_name = dex_location_ + "." + GetInstructionSetString(isa_) + ".flock";
Richard Uhler66d874d2015-01-15 09:37:19 -0800182
Narayan Kamatha3d27eb2017-05-11 13:50:59 +0100183 flock_ = LockedFile::Open(lock_file_name.c_str(), error_msg);
184 if (flock_.get() == nullptr) {
Vladimir Marko66fdcbd2016-04-05 14:19:08 +0100185 unlink(lock_file_name.c_str());
Richard Uhler66d874d2015-01-15 09:37:19 -0800186 return false;
187 }
188 return true;
189}
190
Shubham Ajmerae4e812a2017-05-25 20:09:58 -0700191int OatFileAssistant::GetDexOptNeeded(CompilerFilter::Filter target,
192 bool profile_changed,
Calin Juravle44e5efa2017-09-12 00:54:26 -0700193 bool downgrade,
194 ClassLoaderContext* class_loader_context) {
Richard Uhler88bc6732016-11-14 14:38:03 +0000195 OatFileInfo& info = GetBestInfo();
Calin Juravle44e5efa2017-09-12 00:54:26 -0700196 DexOptNeeded dexopt_needed = info.GetDexOptNeeded(target,
197 profile_changed,
198 downgrade,
199 class_loader_context);
Richard Uhler7225a8d2016-11-22 10:12:03 +0000200 if (info.IsOatLocation() || dexopt_needed == kDex2OatFromScratch) {
201 return dexopt_needed;
Richard Uhler66d874d2015-01-15 09:37:19 -0800202 }
Richard Uhler7225a8d2016-11-22 10:12:03 +0000203 return -dexopt_needed;
Richard Uhler66d874d2015-01-15 09:37:19 -0800204}
205
Richard Uhlerf4b34872016-04-13 11:03:46 -0700206// Figure out the currently specified compile filter option in the runtime.
207// Returns true on success, false if the compiler filter is invalid, in which
208// case error_msg describes the problem.
209static bool GetRuntimeCompilerFilterOption(CompilerFilter::Filter* filter,
210 std::string* error_msg) {
211 CHECK(filter != nullptr);
212 CHECK(error_msg != nullptr);
213
Calin Juravle357c66d2017-05-04 01:57:17 +0000214 *filter = OatFileAssistant::kDefaultCompilerFilterForDexLoading;
Richard Uhlerf4b34872016-04-13 11:03:46 -0700215 for (StringPiece option : Runtime::Current()->GetCompilerOptions()) {
216 if (option.starts_with("--compiler-filter=")) {
217 const char* compiler_filter_string = option.substr(strlen("--compiler-filter=")).data();
218 if (!CompilerFilter::ParseCompilerFilter(compiler_filter_string, filter)) {
219 *error_msg = std::string("Unknown --compiler-filter value: ")
220 + std::string(compiler_filter_string);
221 return false;
222 }
223 }
224 }
225 return true;
226}
227
Richard Uhler01be6812016-05-17 10:34:52 -0700228bool OatFileAssistant::IsUpToDate() {
Richard Uhler88bc6732016-11-14 14:38:03 +0000229 return GetBestInfo().Status() == kOatUpToDate;
Richard Uhler01be6812016-05-17 10:34:52 -0700230}
231
Richard Uhler1e860612016-03-30 12:17:55 -0700232OatFileAssistant::ResultOfAttemptToUpdate
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700233OatFileAssistant::MakeUpToDate(bool profile_changed,
Calin Juravle44e5efa2017-09-12 00:54:26 -0700234 ClassLoaderContext* class_loader_context,
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700235 std::string* error_msg) {
Richard Uhlerf4b34872016-04-13 11:03:46 -0700236 CompilerFilter::Filter target;
237 if (!GetRuntimeCompilerFilterOption(&target, error_msg)) {
238 return kUpdateNotAttempted;
239 }
240
Richard Uhler88bc6732016-11-14 14:38:03 +0000241 OatFileInfo& info = GetBestInfo();
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700242 // TODO(calin, jeffhao): the context should really be passed to GetDexOptNeeded: b/62269291.
243 // This is actually not trivial in the current logic as it will interact with the collision
244 // check:
245 // - currently, if the context does not match but we have no collisions we still accept the
246 // oat file.
247 // - if GetDexOptNeeded would return kDex2OatFromScratch for a context mismatch and we make
248 // the oat code up to date the collision check becomes useless.
249 // - however, MakeUpToDate will not always succeed (e.g. for primary apks, or for dex files
250 // loaded in other processes). So it boils down to how far do we want to complicate
251 // the logic in order to enable the use of oat files. Maybe its time to try simplify it.
Calin Juravle44e5efa2017-09-12 00:54:26 -0700252 switch (info.GetDexOptNeeded(
253 target, profile_changed, /*downgrade*/ false, class_loader_context)) {
Richard Uhler7225a8d2016-11-22 10:12:03 +0000254 case kNoDexOptNeeded:
255 return kUpdateSucceeded;
Richard Uhler88bc6732016-11-14 14:38:03 +0000256
Richard Uhler7225a8d2016-11-22 10:12:03 +0000257 // TODO: For now, don't bother with all the different ways we can call
258 // dex2oat to generate the oat file. Always generate the oat file as if it
259 // were kDex2OatFromScratch.
260 case kDex2OatFromScratch:
261 case kDex2OatForBootImage:
262 case kDex2OatForRelocation:
263 case kDex2OatForFilter:
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700264 return GenerateOatFileNoChecks(info, target, class_loader_context, error_msg);
Richard Uhler66d874d2015-01-15 09:37:19 -0800265 }
266 UNREACHABLE();
267}
268
269std::unique_ptr<OatFile> OatFileAssistant::GetBestOatFile() {
Richard Uhler88bc6732016-11-14 14:38:03 +0000270 return GetBestInfo().ReleaseFileForUse();
Richard Uhler66d874d2015-01-15 09:37:19 -0800271}
272
Richard Uhler46cc64f2016-11-14 14:53:55 +0000273std::string OatFileAssistant::GetStatusDump() {
274 std::ostringstream status;
275 bool oat_file_exists = false;
276 bool odex_file_exists = false;
Richard Uhler03bc6592016-11-22 09:42:04 +0000277 if (oat_.Status() != kOatCannotOpen) {
Richard Uhler2f27abd2017-01-31 14:02:34 +0000278 // If we can open the file, Filename should not return null.
Richard Uhler03bc6592016-11-22 09:42:04 +0000279 CHECK(oat_.Filename() != nullptr);
Richard Uhler03bc6592016-11-22 09:42:04 +0000280
Richard Uhler46cc64f2016-11-14 14:53:55 +0000281 oat_file_exists = true;
Richard Uhler2f27abd2017-01-31 14:02:34 +0000282 status << *oat_.Filename() << "[status=" << oat_.Status() << ", ";
283 const OatFile* file = oat_.GetFile();
284 if (file == nullptr) {
285 // If the file is null even though the status is not kOatCannotOpen, it
286 // means we must have a vdex file with no corresponding oat file. In
287 // this case we cannot determine the compilation filter. Indicate that
288 // we have only the vdex file instead.
289 status << "vdex-only";
290 } else {
291 status << "compilation_filter=" << CompilerFilter::NameOfFilter(file->GetCompilerFilter());
292 }
Richard Uhler46cc64f2016-11-14 14:53:55 +0000293 }
294
Richard Uhler03bc6592016-11-22 09:42:04 +0000295 if (odex_.Status() != kOatCannotOpen) {
Richard Uhler2f27abd2017-01-31 14:02:34 +0000296 // If we can open the file, Filename should not return null.
Richard Uhler03bc6592016-11-22 09:42:04 +0000297 CHECK(odex_.Filename() != nullptr);
Richard Uhler03bc6592016-11-22 09:42:04 +0000298
Richard Uhler46cc64f2016-11-14 14:53:55 +0000299 odex_file_exists = true;
300 if (oat_file_exists) {
301 status << "] ";
302 }
Richard Uhler2f27abd2017-01-31 14:02:34 +0000303 status << *odex_.Filename() << "[status=" << odex_.Status() << ", ";
304 const OatFile* file = odex_.GetFile();
305 if (file == nullptr) {
306 status << "vdex-only";
307 } else {
308 status << "compilation_filter=" << CompilerFilter::NameOfFilter(file->GetCompilerFilter());
309 }
Richard Uhler46cc64f2016-11-14 14:53:55 +0000310 }
311
312 if (!oat_file_exists && !odex_file_exists) {
313 status << "invalid[";
314 }
315
316 status << "]";
317 return status.str();
318}
319
Richard Uhler66d874d2015-01-15 09:37:19 -0800320std::vector<std::unique_ptr<const DexFile>> OatFileAssistant::LoadDexFiles(
Calin Juravle87e2cb62017-06-13 21:48:45 -0700321 const OatFile &oat_file, const char *dex_location) {
Richard Uhler66d874d2015-01-15 09:37:19 -0800322 std::vector<std::unique_ptr<const DexFile>> dex_files;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700323 if (LoadDexFiles(oat_file, dex_location, &dex_files)) {
324 return dex_files;
325 } else {
326 return std::vector<std::unique_ptr<const DexFile>>();
327 }
328}
Richard Uhler66d874d2015-01-15 09:37:19 -0800329
Calin Juravle87e2cb62017-06-13 21:48:45 -0700330bool OatFileAssistant::LoadDexFiles(
331 const OatFile &oat_file,
332 const std::string& dex_location,
333 std::vector<std::unique_ptr<const DexFile>>* out_dex_files) {
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000334 // Load the main dex file.
Richard Uhler66d874d2015-01-15 09:37:19 -0800335 std::string error_msg;
336 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(
Calin Juravle87e2cb62017-06-13 21:48:45 -0700337 dex_location.c_str(), nullptr, &error_msg);
Richard Uhler66d874d2015-01-15 09:37:19 -0800338 if (oat_dex_file == nullptr) {
Richard Uhler9a37efc2016-08-05 16:32:55 -0700339 LOG(WARNING) << error_msg;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700340 return false;
Richard Uhler66d874d2015-01-15 09:37:19 -0800341 }
342
Igor Murashkinb1d8c312015-08-04 11:18:43 -0700343 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
Richard Uhler66d874d2015-01-15 09:37:19 -0800344 if (dex_file.get() == nullptr) {
345 LOG(WARNING) << "Failed to open dex file from oat dex file: " << error_msg;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700346 return false;
Richard Uhler66d874d2015-01-15 09:37:19 -0800347 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700348 out_dex_files->push_back(std::move(dex_file));
Richard Uhler66d874d2015-01-15 09:37:19 -0800349
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000350 // Load the rest of the multidex entries
Calin Juravle87e2cb62017-06-13 21:48:45 -0700351 for (size_t i = 1;; i++) {
352 std::string multidex_dex_location = DexFile::GetMultiDexLocation(i, dex_location.c_str());
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000353 oat_dex_file = oat_file.GetOatDexFile(multidex_dex_location.c_str(), nullptr);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700354 if (oat_dex_file == nullptr) {
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000355 // There are no more multidex entries to load.
Richard Uhler66d874d2015-01-15 09:37:19 -0800356 break;
357 }
358
Igor Murashkinb1d8c312015-08-04 11:18:43 -0700359 dex_file = oat_dex_file->OpenDexFile(&error_msg);
Richard Uhler66d874d2015-01-15 09:37:19 -0800360 if (dex_file.get() == nullptr) {
361 LOG(WARNING) << "Failed to open dex file from oat dex file: " << error_msg;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700362 return false;
Richard Uhler66d874d2015-01-15 09:37:19 -0800363 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700364 out_dex_files->push_back(std::move(dex_file));
Richard Uhler66d874d2015-01-15 09:37:19 -0800365 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700366 return true;
Richard Uhler66d874d2015-01-15 09:37:19 -0800367}
368
Richard Uhler9b994ea2015-06-24 08:44:19 -0700369bool OatFileAssistant::HasOriginalDexFiles() {
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000370 // Ensure GetRequiredDexChecksums has been run so that
Richard Uhler9b994ea2015-06-24 08:44:19 -0700371 // has_original_dex_files_ is initialized. We don't care about the result of
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000372 // GetRequiredDexChecksums.
373 GetRequiredDexChecksums();
Richard Uhler9b994ea2015-06-24 08:44:19 -0700374 return has_original_dex_files_;
375}
376
Richard Uhler95abd042015-03-24 09:51:28 -0700377OatFileAssistant::OatStatus OatFileAssistant::OdexFileStatus() {
Richard Uhler743bf362016-04-19 15:39:37 -0700378 return odex_.Status();
Richard Uhler66d874d2015-01-15 09:37:19 -0800379}
380
Richard Uhler95abd042015-03-24 09:51:28 -0700381OatFileAssistant::OatStatus OatFileAssistant::OatFileStatus() {
Richard Uhler743bf362016-04-19 15:39:37 -0700382 return oat_.Status();
Richard Uhler66d874d2015-01-15 09:37:19 -0800383}
384
Richard Uhler2f27abd2017-01-31 14:02:34 +0000385bool OatFileAssistant::DexChecksumUpToDate(const VdexFile& file, std::string* error_msg) {
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000386 const std::vector<uint32_t>* required_dex_checksums = GetRequiredDexChecksums();
387 if (required_dex_checksums == nullptr) {
388 LOG(WARNING) << "Required dex checksums not found. Assuming dex checksums are up to date.";
389 return true;
390 }
391
392 uint32_t number_of_dex_files = file.GetHeader().GetNumberOfDexFiles();
393 if (required_dex_checksums->size() != number_of_dex_files) {
394 *error_msg = StringPrintf("expected %zu dex files but found %u",
395 required_dex_checksums->size(),
396 number_of_dex_files);
Richard Uhler2f27abd2017-01-31 14:02:34 +0000397 return false;
Andreas Gampef8cd8902017-01-18 16:05:01 -0800398 }
399
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000400 for (uint32_t i = 0; i < number_of_dex_files; i++) {
401 uint32_t expected_checksum = (*required_dex_checksums)[i];
402 uint32_t actual_checksum = file.GetLocationChecksum(i);
403 if (expected_checksum != actual_checksum) {
404 std::string dex = DexFile::GetMultiDexLocation(i, dex_location_.c_str());
405 *error_msg = StringPrintf("Dex checksum does not match for dex: %s."
406 "Expected: %u, actual: %u",
407 dex.c_str(),
408 expected_checksum,
409 actual_checksum);
Richard Uhler2f27abd2017-01-31 14:02:34 +0000410 return false;
411 }
412 }
413
Richard Uhler2f27abd2017-01-31 14:02:34 +0000414 return true;
415}
416
417bool OatFileAssistant::DexChecksumUpToDate(const OatFile& file, std::string* error_msg) {
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000418 const std::vector<uint32_t>* required_dex_checksums = GetRequiredDexChecksums();
419 if (required_dex_checksums == nullptr) {
420 LOG(WARNING) << "Required dex checksums not found. Assuming dex checksums are up to date.";
421 return true;
422 }
423
424 uint32_t number_of_dex_files = file.GetOatHeader().GetDexFileCount();
425 if (required_dex_checksums->size() != number_of_dex_files) {
426 *error_msg = StringPrintf("expected %zu dex files but found %u",
427 required_dex_checksums->size(),
428 number_of_dex_files);
Richard Uhler2f27abd2017-01-31 14:02:34 +0000429 return false;
Richard Uhler66d874d2015-01-15 09:37:19 -0800430 }
431
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000432 for (uint32_t i = 0; i < number_of_dex_files; i++) {
433 std::string dex = DexFile::GetMultiDexLocation(i, dex_location_.c_str());
434 uint32_t expected_checksum = (*required_dex_checksums)[i];
435 const OatFile::OatDexFile* oat_dex_file = file.GetOatDexFile(dex.c_str(), nullptr);
436 if (oat_dex_file == nullptr) {
437 *error_msg = StringPrintf("failed to find %s in %s", dex.c_str(), file.GetLocation().c_str());
438 return false;
Richard Uhler66d874d2015-01-15 09:37:19 -0800439 }
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000440 uint32_t actual_checksum = oat_dex_file->GetDexFileLocationChecksum();
441 if (expected_checksum != actual_checksum) {
442 VLOG(oat) << "Dex checksum does not match for dex: " << dex
443 << ". Expected: " << expected_checksum
444 << ", Actual: " << actual_checksum;
445 return false;
Richard Uhler66d874d2015-01-15 09:37:19 -0800446 }
447 }
Richard Uhler2f27abd2017-01-31 14:02:34 +0000448 return true;
449}
450
451OatFileAssistant::OatStatus OatFileAssistant::GivenOatFileStatus(const OatFile& file) {
452 // Verify the ART_USE_READ_BARRIER state.
453 // TODO: Don't fully reject files due to read barrier state. If they contain
454 // compiled code and are otherwise okay, we should return something like
455 // kOatRelocationOutOfDate. If they don't contain compiled code, the read
456 // barrier state doesn't matter.
457 const bool is_cc = file.GetOatHeader().IsConcurrentCopying();
458 constexpr bool kRuntimeIsCC = kUseReadBarrier;
459 if (is_cc != kRuntimeIsCC) {
460 return kOatCannotOpen;
461 }
462
463 // Verify the dex checksum.
464 std::string error_msg;
465 if (kIsVdexEnabled) {
466 VdexFile* vdex = file.GetVdexFile();
467 if (!DexChecksumUpToDate(*vdex, &error_msg)) {
468 LOG(ERROR) << error_msg;
469 return kOatDexOutOfDate;
470 }
471 } else {
472 if (!DexChecksumUpToDate(file, &error_msg)) {
473 LOG(ERROR) << error_msg;
474 return kOatDexOutOfDate;
475 }
476 }
Richard Uhler66d874d2015-01-15 09:37:19 -0800477
Andreas Gampe29d38e72016-03-23 15:31:51 +0000478 CompilerFilter::Filter current_compiler_filter = file.GetCompilerFilter();
David Brazdilce4b0ba2016-01-28 15:05:49 +0000479
Richard Uhler66d874d2015-01-15 09:37:19 -0800480 // Verify the image checksum
Andreas Gampe29d38e72016-03-23 15:31:51 +0000481 if (CompilerFilter::DependsOnImageChecksum(current_compiler_filter)) {
482 const ImageInfo* image_info = GetImageInfo();
483 if (image_info == nullptr) {
484 VLOG(oat) << "No image for oat image checksum to match against.";
Andreas Gampe29d38e72016-03-23 15:31:51 +0000485
Richard Uhler76f5cb62016-04-04 13:30:16 -0700486 if (HasOriginalDexFiles()) {
Richard Uhler03bc6592016-11-22 09:42:04 +0000487 return kOatBootImageOutOfDate;
Richard Uhler76f5cb62016-04-04 13:30:16 -0700488 }
489
490 // If there is no original dex file to fall back to, grudgingly accept
491 // the oat file. This could technically lead to crashes, but there's no
492 // way we could find a better oat file to use for this dex location,
493 // and it's better than being stuck in a boot loop with no way out.
494 // The problem will hopefully resolve itself the next time the runtime
495 // starts up.
496 LOG(WARNING) << "Dex location " << dex_location_ << " does not seem to include dex file. "
497 << "Allow oat file use. This is potentially dangerous.";
Richard Uhler95e09672017-02-22 11:37:41 +0000498 } else if (file.GetOatHeader().GetImageFileLocationOatChecksum() != image_info->oat_checksum) {
Andreas Gampe29d38e72016-03-23 15:31:51 +0000499 VLOG(oat) << "Oat image checksum does not match image checksum.";
Richard Uhler03bc6592016-11-22 09:42:04 +0000500 return kOatBootImageOutOfDate;
Andreas Gampe29d38e72016-03-23 15:31:51 +0000501 }
502 } else {
503 VLOG(oat) << "Image checksum test skipped for compiler filter " << current_compiler_filter;
Richard Uhler66d874d2015-01-15 09:37:19 -0800504 }
505
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100506 if (CompilerFilter::IsAotCompilationEnabled(current_compiler_filter)) {
Andreas Gampe29d38e72016-03-23 15:31:51 +0000507 if (!file.IsPic()) {
508 const ImageInfo* image_info = GetImageInfo();
509 if (image_info == nullptr) {
510 VLOG(oat) << "No image to check oat relocation against.";
Richard Uhler03bc6592016-11-22 09:42:04 +0000511 return kOatRelocationOutOfDate;
Andreas Gampe29d38e72016-03-23 15:31:51 +0000512 }
Richard Uhlera62d2f02016-03-18 15:05:30 -0700513
Andreas Gampe29d38e72016-03-23 15:31:51 +0000514 // Verify the oat_data_begin recorded for the image in the oat file matches
515 // the actual oat_data_begin for boot.oat in the image.
516 const OatHeader& oat_header = file.GetOatHeader();
517 uintptr_t oat_data_begin = oat_header.GetImageFileLocationOatDataBegin();
518 if (oat_data_begin != image_info->oat_data_begin) {
519 VLOG(oat) << file.GetLocation() <<
520 ": Oat file image oat_data_begin (" << oat_data_begin << ")"
521 << " does not match actual image oat_data_begin ("
522 << image_info->oat_data_begin << ")";
Richard Uhler03bc6592016-11-22 09:42:04 +0000523 return kOatRelocationOutOfDate;
Andreas Gampe29d38e72016-03-23 15:31:51 +0000524 }
Richard Uhlera62d2f02016-03-18 15:05:30 -0700525
Andreas Gampe29d38e72016-03-23 15:31:51 +0000526 // Verify the oat_patch_delta recorded for the image in the oat file matches
527 // the actual oat_patch_delta for the image.
528 int32_t oat_patch_delta = oat_header.GetImagePatchDelta();
529 if (oat_patch_delta != image_info->patch_delta) {
530 VLOG(oat) << file.GetLocation() <<
531 ": Oat file image patch delta (" << oat_patch_delta << ")"
532 << " does not match actual image patch delta ("
533 << image_info->patch_delta << ")";
Richard Uhler03bc6592016-11-22 09:42:04 +0000534 return kOatRelocationOutOfDate;
Andreas Gampe29d38e72016-03-23 15:31:51 +0000535 }
536 } else {
537 // Oat files compiled in PIC mode do not require relocation.
538 VLOG(oat) << "Oat relocation test skipped for PIC oat file";
539 }
540 } else {
541 VLOG(oat) << "Oat relocation test skipped for compiler filter " << current_compiler_filter;
Richard Uhler66d874d2015-01-15 09:37:19 -0800542 }
Richard Uhlere8109f72016-04-18 10:40:50 -0700543 return kOatUpToDate;
Richard Uhler66d874d2015-01-15 09:37:19 -0800544}
545
Calin Juravle357c66d2017-05-04 01:57:17 +0000546static bool DexLocationToOdexNames(const std::string& location,
547 InstructionSet isa,
548 std::string* odex_filename,
549 std::string* oat_dir,
550 std::string* isa_dir,
551 std::string* error_msg) {
552 CHECK(odex_filename != nullptr);
553 CHECK(error_msg != nullptr);
554
555 // The odex file name is formed by replacing the dex_location extension with
556 // .odex and inserting an oat/<isa> directory. For example:
557 // location = /foo/bar/baz.jar
558 // odex_location = /foo/bar/oat/<isa>/baz.odex
559
560 // Find the directory portion of the dex location and add the oat/<isa>
561 // directory.
562 size_t pos = location.rfind('/');
563 if (pos == std::string::npos) {
564 *error_msg = "Dex location " + location + " has no directory.";
565 return false;
566 }
567 std::string dir = location.substr(0, pos+1);
568 // Add the oat directory.
569 dir += "oat";
570 if (oat_dir != nullptr) {
571 *oat_dir = dir;
572 }
573 // Add the isa directory
574 dir += "/" + std::string(GetInstructionSetString(isa));
575 if (isa_dir != nullptr) {
576 *isa_dir = dir;
577 }
578
579 // Get the base part of the file without the extension.
580 std::string file = location.substr(pos+1);
581 pos = file.rfind('.');
582 if (pos == std::string::npos) {
583 *error_msg = "Dex location " + location + " has no extension.";
584 return false;
585 }
586 std::string base = file.substr(0, pos);
587
588 *odex_filename = dir + "/" + base + ".odex";
589 return true;
590}
591
592// Prepare a subcomponent of the odex directory.
593// (i.e. create and set the expected permissions on the path `dir`).
594static bool PrepareDirectory(const std::string& dir, std::string* error_msg) {
595 struct stat dir_stat;
596 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &dir_stat)) == 0) {
597 // The directory exists. Check if it is indeed a directory.
598 if (!S_ISDIR(dir_stat.st_mode)) {
599 *error_msg = dir + " is not a dir";
600 return false;
601 } else {
602 // The dir is already on disk.
603 return true;
604 }
605 }
606
607 // Failed to stat. We need to create the directory.
608 if (errno != ENOENT) {
609 *error_msg = "Could not stat isa dir " + dir + ":" + strerror(errno);
610 return false;
611 }
612
613 mode_t mode = S_IRWXU | S_IXGRP | S_IXOTH;
614 if (mkdir(dir.c_str(), mode) != 0) {
615 *error_msg = "Could not create dir " + dir + ":" + strerror(errno);
616 return false;
617 }
618 if (chmod(dir.c_str(), mode) != 0) {
619 *error_msg = "Could not create the oat dir " + dir + ":" + strerror(errno);
620 return false;
621 }
622 return true;
623}
624
625// Prepares the odex directory for the given dex location.
626static bool PrepareOdexDirectories(const std::string& dex_location,
627 const std::string& expected_odex_location,
628 InstructionSet isa,
629 std::string* error_msg) {
630 std::string actual_odex_location;
631 std::string oat_dir;
632 std::string isa_dir;
633 if (!DexLocationToOdexNames(
634 dex_location, isa, &actual_odex_location, &oat_dir, &isa_dir, error_msg)) {
635 return false;
636 }
637 DCHECK_EQ(expected_odex_location, actual_odex_location);
638
639 if (!PrepareDirectory(oat_dir, error_msg)) {
640 return false;
641 }
642 if (!PrepareDirectory(isa_dir, error_msg)) {
643 return false;
644 }
645 return true;
646}
647
Calin Juravled4215bb2017-09-20 11:54:21 -0700648class Dex2oatFileWrapper {
649 public:
650 explicit Dex2oatFileWrapper(File* file)
651 : file_(file),
652 unlink_file_at_destruction_(true) {
653 }
654
655 ~Dex2oatFileWrapper() {
656 if (unlink_file_at_destruction_ && (file_ != nullptr)) {
657 file_->Erase(/*unlink*/ true);
658 }
659 }
660
661 File* GetFile() { return file_.get(); }
662
663 void DisableUnlinkAtDestruction() {
664 unlink_file_at_destruction_ = false;
665 };
666
667 private:
668 std::unique_ptr<File> file_;
669 bool unlink_file_at_destruction_;
670};
671
Calin Juravle357c66d2017-05-04 01:57:17 +0000672OatFileAssistant::ResultOfAttemptToUpdate OatFileAssistant::GenerateOatFileNoChecks(
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700673 OatFileAssistant::OatFileInfo& info,
674 CompilerFilter::Filter filter,
Calin Juravle44e5efa2017-09-12 00:54:26 -0700675 const ClassLoaderContext* class_loader_context,
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700676 std::string* error_msg) {
Richard Uhler66d874d2015-01-15 09:37:19 -0800677 CHECK(error_msg != nullptr);
678
Richard Uhler8327cf72015-10-13 16:34:59 -0700679 Runtime* runtime = Runtime::Current();
680 if (!runtime->IsDex2OatEnabled()) {
681 *error_msg = "Generation of oat file for dex location " + dex_location_
682 + " not attempted because dex2oat is disabled.";
Richard Uhler1e860612016-03-30 12:17:55 -0700683 return kUpdateNotAttempted;
Richard Uhler8327cf72015-10-13 16:34:59 -0700684 }
685
Calin Juravle357c66d2017-05-04 01:57:17 +0000686 if (info.Filename() == nullptr) {
Richard Uhler740eec92015-10-15 15:12:23 -0700687 *error_msg = "Generation of oat file for dex location " + dex_location_
Richard Uhler66d874d2015-01-15 09:37:19 -0800688 + " not attempted because the oat file name could not be determined.";
Richard Uhler1e860612016-03-30 12:17:55 -0700689 return kUpdateNotAttempted;
Richard Uhler66d874d2015-01-15 09:37:19 -0800690 }
Calin Juravle357c66d2017-05-04 01:57:17 +0000691 const std::string& oat_file_name = *info.Filename();
Calin Juravle367b9d82017-05-15 18:18:39 -0700692 const std::string& vdex_file_name = GetVdexFilename(oat_file_name);
Richard Uhler66d874d2015-01-15 09:37:19 -0800693
Richard Uhler66d874d2015-01-15 09:37:19 -0800694 // dex2oat ignores missing dex files and doesn't report an error.
695 // Check explicitly here so we can detect the error properly.
696 // TODO: Why does dex2oat behave that way?
Calin Juravle357c66d2017-05-04 01:57:17 +0000697 struct stat dex_path_stat;
698 if (TEMP_FAILURE_RETRY(stat(dex_location_.c_str(), &dex_path_stat)) != 0) {
699 *error_msg = "Could not access dex location " + dex_location_ + ":" + strerror(errno);
Richard Uhler1e860612016-03-30 12:17:55 -0700700 return kUpdateNotAttempted;
Richard Uhler66d874d2015-01-15 09:37:19 -0800701 }
702
Calin Juravle357c66d2017-05-04 01:57:17 +0000703 // If this is the odex location, we need to create the odex file layout (../oat/isa/..)
704 if (!info.IsOatLocation()) {
705 if (!PrepareOdexDirectories(dex_location_, oat_file_name, isa_, error_msg)) {
706 return kUpdateNotAttempted;
707 }
708 }
709
710 // Set the permissions for the oat and the vdex files.
711 // The user always gets read and write while the group and others propagate
712 // the reading access of the original dex file.
713 mode_t file_mode = S_IRUSR | S_IWUSR |
714 (dex_path_stat.st_mode & S_IRGRP) |
715 (dex_path_stat.st_mode & S_IROTH);
716
Calin Juravled4215bb2017-09-20 11:54:21 -0700717 Dex2oatFileWrapper vdex_file_wrapper(OS::CreateEmptyFile(vdex_file_name.c_str()));
718 File* vdex_file = vdex_file_wrapper.GetFile();
719 if (vdex_file == nullptr) {
David Brazdil7b49e6c2016-09-01 11:06:18 +0100720 *error_msg = "Generation of oat file " + oat_file_name
721 + " not attempted because the vdex file " + vdex_file_name
722 + " could not be opened.";
723 return kUpdateNotAttempted;
724 }
725
Calin Juravle357c66d2017-05-04 01:57:17 +0000726 if (fchmod(vdex_file->Fd(), file_mode) != 0) {
David Brazdil7b49e6c2016-09-01 11:06:18 +0100727 *error_msg = "Generation of oat file " + oat_file_name
728 + " not attempted because the vdex file " + vdex_file_name
729 + " could not be made world readable.";
730 return kUpdateNotAttempted;
731 }
732
Calin Juravled4215bb2017-09-20 11:54:21 -0700733 Dex2oatFileWrapper oat_file_wrapper(OS::CreateEmptyFile(oat_file_name.c_str()));
734 File* oat_file = oat_file_wrapper.GetFile();
735 if (oat_file == nullptr) {
Richard Uhler8327cf72015-10-13 16:34:59 -0700736 *error_msg = "Generation of oat file " + oat_file_name
737 + " not attempted because the oat file could not be created.";
Richard Uhler1e860612016-03-30 12:17:55 -0700738 return kUpdateNotAttempted;
Richard Uhler8327cf72015-10-13 16:34:59 -0700739 }
740
Calin Juravle357c66d2017-05-04 01:57:17 +0000741 if (fchmod(oat_file->Fd(), file_mode) != 0) {
Richard Uhler8327cf72015-10-13 16:34:59 -0700742 *error_msg = "Generation of oat file " + oat_file_name
743 + " not attempted because the oat file could not be made world readable.";
Richard Uhler1e860612016-03-30 12:17:55 -0700744 return kUpdateNotAttempted;
Richard Uhler8327cf72015-10-13 16:34:59 -0700745 }
746
747 std::vector<std::string> args;
748 args.push_back("--dex-file=" + dex_location_);
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +0000749 args.push_back("--output-vdex-fd=" + std::to_string(vdex_file->Fd()));
Richard Uhler8327cf72015-10-13 16:34:59 -0700750 args.push_back("--oat-fd=" + std::to_string(oat_file->Fd()));
751 args.push_back("--oat-location=" + oat_file_name);
Calin Juravle07c6d722017-06-07 17:06:12 +0000752 args.push_back("--compiler-filter=" + CompilerFilter::NameOfFilter(filter));
Calin Juravle44e5efa2017-09-12 00:54:26 -0700753 const std::string dex2oat_context = class_loader_context == nullptr
754 ? OatFile::kSpecialSharedLibrary
755 : class_loader_context->EncodeContextForDex2oat(/*base_dir*/ "");
756 args.push_back("--class-loader-context=" + dex2oat_context);
Richard Uhler8327cf72015-10-13 16:34:59 -0700757
Richard Uhler66d874d2015-01-15 09:37:19 -0800758 if (!Dex2Oat(args, error_msg)) {
Richard Uhler1e860612016-03-30 12:17:55 -0700759 return kUpdateFailed;
Richard Uhler8327cf72015-10-13 16:34:59 -0700760 }
761
David Brazdil7b49e6c2016-09-01 11:06:18 +0100762 if (vdex_file->FlushCloseOrErase() != 0) {
763 *error_msg = "Unable to close vdex file " + vdex_file_name;
David Brazdil7b49e6c2016-09-01 11:06:18 +0100764 return kUpdateFailed;
765 }
766
Richard Uhler8327cf72015-10-13 16:34:59 -0700767 if (oat_file->FlushCloseOrErase() != 0) {
768 *error_msg = "Unable to close oat file " + oat_file_name;
Richard Uhler1e860612016-03-30 12:17:55 -0700769 return kUpdateFailed;
Richard Uhler66d874d2015-01-15 09:37:19 -0800770 }
771
Calin Juravle357c66d2017-05-04 01:57:17 +0000772 // Mark that the odex file has changed and we should try to reload.
773 info.Reset();
Calin Juravled4215bb2017-09-20 11:54:21 -0700774 // We have compiled successfully. Disable the auto-unlink.
775 vdex_file_wrapper.DisableUnlinkAtDestruction();
776 oat_file_wrapper.DisableUnlinkAtDestruction();
777
Richard Uhler1e860612016-03-30 12:17:55 -0700778 return kUpdateSucceeded;
Richard Uhler66d874d2015-01-15 09:37:19 -0800779}
780
781bool OatFileAssistant::Dex2Oat(const std::vector<std::string>& args,
782 std::string* error_msg) {
783 Runtime* runtime = Runtime::Current();
784 std::string image_location = ImageLocation();
785 if (image_location.empty()) {
786 *error_msg = "No image location found for Dex2Oat.";
787 return false;
788 }
789
790 std::vector<std::string> argv;
791 argv.push_back(runtime->GetCompilerExecutable());
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000792 if (runtime->IsJavaDebuggable()) {
Sebastien Hertz0de11332015-05-13 12:14:05 +0200793 argv.push_back("--debuggable");
794 }
Igor Murashkinb1d8c312015-08-04 11:18:43 -0700795 runtime->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
Richard Uhler66d874d2015-01-15 09:37:19 -0800796
797 if (!runtime->IsVerificationEnabled()) {
798 argv.push_back("--compiler-filter=verify-none");
799 }
800
801 if (runtime->MustRelocateIfPossible()) {
802 argv.push_back("--runtime-arg");
803 argv.push_back("-Xrelocate");
804 } else {
805 argv.push_back("--runtime-arg");
806 argv.push_back("-Xnorelocate");
807 }
808
809 if (!kIsTargetBuild) {
810 argv.push_back("--host");
811 }
812
813 argv.push_back("--boot-image=" + image_location);
814
815 std::vector<std::string> compiler_options = runtime->GetCompilerOptions();
816 argv.insert(argv.end(), compiler_options.begin(), compiler_options.end());
817
818 argv.insert(argv.end(), args.begin(), args.end());
819
Andreas Gampe9186ced2016-12-12 14:28:21 -0800820 std::string command_line(android::base::Join(argv, ' '));
Richard Uhler66d874d2015-01-15 09:37:19 -0800821 return Exec(argv, error_msg);
822}
823
Richard Uhlerb81881d2016-04-19 13:08:04 -0700824bool OatFileAssistant::DexLocationToOdexFilename(const std::string& location,
825 InstructionSet isa,
826 std::string* odex_filename,
827 std::string* error_msg) {
Calin Juravle357c66d2017-05-04 01:57:17 +0000828 return DexLocationToOdexNames(location, isa, odex_filename, nullptr, nullptr, error_msg);
Richard Uhler66d874d2015-01-15 09:37:19 -0800829}
830
Richard Uhlerb81881d2016-04-19 13:08:04 -0700831bool OatFileAssistant::DexLocationToOatFilename(const std::string& location,
832 InstructionSet isa,
833 std::string* oat_filename,
834 std::string* error_msg) {
835 CHECK(oat_filename != nullptr);
836 CHECK(error_msg != nullptr);
Richard Uhler66d874d2015-01-15 09:37:19 -0800837
Richard Uhler55b58b62016-08-12 09:05:13 -0700838 std::string cache_dir = GetDalvikCache(GetInstructionSetString(isa));
839 if (cache_dir.empty()) {
840 *error_msg = "Dalvik cache directory does not exist";
841 return false;
842 }
Richard Uhlerb81881d2016-04-19 13:08:04 -0700843
844 // TODO: The oat file assistant should be the definitive place for
845 // determining the oat file name from the dex location, not
846 // GetDalvikCacheFilename.
Richard Uhlerb81881d2016-04-19 13:08:04 -0700847 return GetDalvikCacheFilename(location.c_str(), cache_dir.c_str(), oat_filename, error_msg);
Richard Uhler66d874d2015-01-15 09:37:19 -0800848}
849
Richard Uhler66d874d2015-01-15 09:37:19 -0800850std::string OatFileAssistant::ImageLocation() {
851 Runtime* runtime = Runtime::Current();
Andreas Gampe8994a042015-12-30 19:03:17 +0000852 const std::vector<gc::space::ImageSpace*>& image_spaces =
853 runtime->GetHeap()->GetBootImageSpaces();
854 if (image_spaces.empty()) {
855 return "";
856 }
857 return image_spaces[0]->GetImageLocation();
Richard Uhler66d874d2015-01-15 09:37:19 -0800858}
859
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000860const std::vector<uint32_t>* OatFileAssistant::GetRequiredDexChecksums() {
861 if (!required_dex_checksums_attempted_) {
862 required_dex_checksums_attempted_ = true;
863 required_dex_checksums_found_ = false;
864 cached_required_dex_checksums_.clear();
Richard Uhler66d874d2015-01-15 09:37:19 -0800865 std::string error_msg;
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000866 if (DexFile::GetMultiDexChecksums(dex_location_.c_str(),
867 &cached_required_dex_checksums_,
868 &error_msg)) {
869 required_dex_checksums_found_ = true;
Richard Uhler9b994ea2015-06-24 08:44:19 -0700870 has_original_dex_files_ = true;
Richard Uhler66d874d2015-01-15 09:37:19 -0800871 } else {
872 // This can happen if the original dex file has been stripped from the
873 // apk.
874 VLOG(oat) << "OatFileAssistant: " << error_msg;
Richard Uhler9b994ea2015-06-24 08:44:19 -0700875 has_original_dex_files_ = false;
Richard Uhler66d874d2015-01-15 09:37:19 -0800876
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000877 // Get the checksums from the odex if we can.
Richard Uhler743bf362016-04-19 15:39:37 -0700878 const OatFile* odex_file = odex_.GetFile();
Richard Uhler66d874d2015-01-15 09:37:19 -0800879 if (odex_file != nullptr) {
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000880 required_dex_checksums_found_ = true;
881 for (size_t i = 0; i < odex_file->GetOatHeader().GetDexFileCount(); i++) {
882 std::string dex = DexFile::GetMultiDexLocation(i, dex_location_.c_str());
883 const OatFile::OatDexFile* odex_dex_file = odex_file->GetOatDexFile(dex.c_str(), nullptr);
884 if (odex_dex_file == nullptr) {
885 required_dex_checksums_found_ = false;
886 break;
887 }
888 cached_required_dex_checksums_.push_back(odex_dex_file->GetDexFileLocationChecksum());
Richard Uhler66d874d2015-01-15 09:37:19 -0800889 }
890 }
891 }
892 }
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000893 return required_dex_checksums_found_ ? &cached_required_dex_checksums_ : nullptr;
Richard Uhler66d874d2015-01-15 09:37:19 -0800894}
895
Richard Uhler95e09672017-02-22 11:37:41 +0000896std::unique_ptr<OatFileAssistant::ImageInfo>
897OatFileAssistant::ImageInfo::GetRuntimeImageInfo(InstructionSet isa, std::string* error_msg) {
898 CHECK(error_msg != nullptr);
899
Richard Uhler95e09672017-02-22 11:37:41 +0000900 Runtime* runtime = Runtime::Current();
Richard Uhler8f104862017-02-22 12:34:01 +0000901 std::unique_ptr<ImageInfo> info(new ImageInfo());
902 info->location = runtime->GetImageLocation();
903
904 std::unique_ptr<ImageHeader> image_header(
905 gc::space::ImageSpace::ReadImageHeader(info->location.c_str(), isa, error_msg));
906 if (image_header == nullptr) {
Richard Uhler95e09672017-02-22 11:37:41 +0000907 return nullptr;
908 }
909
Richard Uhler8f104862017-02-22 12:34:01 +0000910 info->oat_checksum = image_header->GetOatChecksum();
911 info->oat_data_begin = reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin());
912 info->patch_delta = image_header->GetPatchDelta();
Richard Uhler95e09672017-02-22 11:37:41 +0000913 return info;
914}
915
Richard Uhler66d874d2015-01-15 09:37:19 -0800916const OatFileAssistant::ImageInfo* OatFileAssistant::GetImageInfo() {
917 if (!image_info_load_attempted_) {
918 image_info_load_attempted_ = true;
Richard Uhler95e09672017-02-22 11:37:41 +0000919 std::string error_msg;
920 cached_image_info_ = ImageInfo::GetRuntimeImageInfo(isa_, &error_msg);
921 if (cached_image_info_ == nullptr) {
922 LOG(WARNING) << "Unable to get runtime image info: " << error_msg;
Richard Uhler66d874d2015-01-15 09:37:19 -0800923 }
Richard Uhler66d874d2015-01-15 09:37:19 -0800924 }
Richard Uhler95e09672017-02-22 11:37:41 +0000925 return cached_image_info_.get();
Richard Uhler66d874d2015-01-15 09:37:19 -0800926}
927
Richard Uhler88bc6732016-11-14 14:38:03 +0000928OatFileAssistant::OatFileInfo& OatFileAssistant::GetBestInfo() {
Calin Juravle357c66d2017-05-04 01:57:17 +0000929 // TODO(calin): Document the side effects of class loading when
930 // running dalvikvm command line.
931 if (dex_parent_writable_) {
932 // If the parent of the dex file is writable it means that we can
933 // create the odex file. In this case we unconditionally pick the odex
934 // as the best oat file. This corresponds to the regular use case when
935 // apps gets installed or when they load private, secondary dex file.
936 // For apps on the system partition the odex location will not be
937 // writable and thus the oat location might be more up to date.
938 return odex_;
939 }
940
941 // We cannot write to the odex location. This must be a system app.
942
943 // If the oat location is usable take it.
944 if (oat_.IsUseable()) {
945 return oat_;
946 }
947
948 // The oat file is not usable but the odex file might be up to date.
949 // This is an indication that we are dealing with an up to date prebuilt
950 // (that doesn't need relocation).
951 if (odex_.Status() == kOatUpToDate) {
952 return odex_;
953 }
954
955 // The oat file is not usable and the odex file is not up to date.
956 // However we have access to the original dex file which means we can make
957 // the oat location up to date.
958 if (HasOriginalDexFiles()) {
959 return oat_;
960 }
961
962 // We got into the worst situation here:
963 // - the oat location is not usable
964 // - the prebuild odex location is not up to date
965 // - and we don't have the original dex file anymore (stripped).
966 // Pick the odex if it exists, or the oat if not.
967 return (odex_.Status() == kOatCannotOpen) ? oat_ : odex_;
Richard Uhler88bc6732016-11-14 14:38:03 +0000968}
969
Andreas Gampea463b6a2016-08-12 21:53:32 -0700970std::unique_ptr<gc::space::ImageSpace> OatFileAssistant::OpenImageSpace(const OatFile* oat_file) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800971 DCHECK(oat_file != nullptr);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100972 std::string art_file = ReplaceFileExtension(oat_file->GetLocation(), "art");
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800973 if (art_file.empty()) {
974 return nullptr;
975 }
976 std::string error_msg;
977 ScopedObjectAccess soa(Thread::Current());
Andreas Gampea463b6a2016-08-12 21:53:32 -0700978 std::unique_ptr<gc::space::ImageSpace> ret =
979 gc::space::ImageSpace::CreateFromAppImage(art_file.c_str(), oat_file, &error_msg);
Mathieu Chartiere778fc72016-01-25 20:11:28 -0800980 if (ret == nullptr && (VLOG_IS_ON(image) || OS::FileExists(art_file.c_str()))) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800981 LOG(INFO) << "Failed to open app image " << art_file.c_str() << " " << error_msg;
982 }
983 return ret;
984}
985
Richard Uhler88bc6732016-11-14 14:38:03 +0000986OatFileAssistant::OatFileInfo::OatFileInfo(OatFileAssistant* oat_file_assistant,
987 bool is_oat_location)
988 : oat_file_assistant_(oat_file_assistant), is_oat_location_(is_oat_location)
Richard Uhler743bf362016-04-19 15:39:37 -0700989{}
990
Richard Uhler88bc6732016-11-14 14:38:03 +0000991bool OatFileAssistant::OatFileInfo::IsOatLocation() {
992 return is_oat_location_;
993}
994
Richard Uhler743bf362016-04-19 15:39:37 -0700995const std::string* OatFileAssistant::OatFileInfo::Filename() {
996 return filename_provided_ ? &filename_ : nullptr;
997}
998
Richard Uhler03bc6592016-11-22 09:42:04 +0000999bool OatFileAssistant::OatFileInfo::IsUseable() {
1000 switch (Status()) {
1001 case kOatCannotOpen:
1002 case kOatDexOutOfDate:
1003 case kOatBootImageOutOfDate: return false;
1004
1005 case kOatRelocationOutOfDate:
1006 case kOatUpToDate: return true;
1007 }
1008 UNREACHABLE();
Richard Uhler743bf362016-04-19 15:39:37 -07001009}
1010
1011OatFileAssistant::OatStatus OatFileAssistant::OatFileInfo::Status() {
1012 if (!status_attempted_) {
1013 status_attempted_ = true;
1014 const OatFile* file = GetFile();
1015 if (file == nullptr) {
Richard Uhler2f27abd2017-01-31 14:02:34 +00001016 // Check to see if there is a vdex file we can make use of.
1017 std::string error_msg;
Calin Juravle367b9d82017-05-15 18:18:39 -07001018 std::string vdex_filename = GetVdexFilename(filename_);
Richard Uhler2f27abd2017-01-31 14:02:34 +00001019 std::unique_ptr<VdexFile> vdex = VdexFile::Open(vdex_filename,
1020 /*writeable*/false,
1021 /*low_4gb*/false,
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +01001022 /*unquicken*/false,
Richard Uhler2f27abd2017-01-31 14:02:34 +00001023 &error_msg);
1024 if (vdex == nullptr) {
1025 status_ = kOatCannotOpen;
1026 VLOG(oat) << "unable to open vdex file " << vdex_filename << ": " << error_msg;
1027 } else {
1028 if (oat_file_assistant_->DexChecksumUpToDate(*vdex, &error_msg)) {
1029 // The vdex file does not contain enough information to determine
1030 // whether it is up to date with respect to the boot image, so we
1031 // assume it is out of date.
1032 VLOG(oat) << error_msg;
1033 status_ = kOatBootImageOutOfDate;
1034 } else {
1035 status_ = kOatDexOutOfDate;
1036 }
1037 }
Richard Uhler743bf362016-04-19 15:39:37 -07001038 } else {
1039 status_ = oat_file_assistant_->GivenOatFileStatus(*file);
Richard Uhler9a37efc2016-08-05 16:32:55 -07001040 VLOG(oat) << file->GetLocation() << " is " << status_
1041 << " with filter " << file->GetCompilerFilter();
Richard Uhler743bf362016-04-19 15:39:37 -07001042 }
1043 }
1044 return status_;
1045}
1046
Richard Uhler70a84262016-11-08 16:51:51 +00001047OatFileAssistant::DexOptNeeded OatFileAssistant::OatFileInfo::GetDexOptNeeded(
Calin Juravle44e5efa2017-09-12 00:54:26 -07001048 CompilerFilter::Filter target,
1049 bool profile_changed,
1050 bool downgrade,
1051 ClassLoaderContext* context) {
1052
Nicolas Geoffray49cda062017-04-21 13:08:25 +01001053 bool compilation_desired = CompilerFilter::IsAotCompilationEnabled(target);
Shubham Ajmerae4e812a2017-05-25 20:09:58 -07001054 bool filter_okay = CompilerFilterIsOkay(target, profile_changed, downgrade);
Calin Juravle44e5efa2017-09-12 00:54:26 -07001055 bool class_loader_context_okay = ClassLoaderContextIsOkay(context);
Richard Uhler70a84262016-11-08 16:51:51 +00001056
Calin Juravle44e5efa2017-09-12 00:54:26 -07001057 // Only check the filter and relocation if the class loader context is ok.
1058 // If it is not, we will return kDex2OatFromScratch as the compilation needs to be redone.
1059 if (class_loader_context_okay) {
1060 if (filter_okay && Status() == kOatUpToDate) {
1061 // The oat file is in good shape as is.
1062 return kNoDexOptNeeded;
1063 }
Richard Uhler70a84262016-11-08 16:51:51 +00001064
Calin Juravle44e5efa2017-09-12 00:54:26 -07001065 if (filter_okay && !compilation_desired && Status() == kOatRelocationOutOfDate) {
1066 // If no compilation is desired, then it doesn't matter if the oat
1067 // file needs relocation. It's in good shape as is.
1068 return kNoDexOptNeeded;
1069 }
Richard Uhler7225a8d2016-11-22 10:12:03 +00001070
Calin Juravle44e5efa2017-09-12 00:54:26 -07001071 if (filter_okay && Status() == kOatRelocationOutOfDate) {
1072 return kDex2OatForRelocation;
1073 }
Richard Uhler7225a8d2016-11-22 10:12:03 +00001074
Calin Juravle44e5efa2017-09-12 00:54:26 -07001075 if (IsUseable()) {
1076 return kDex2OatForFilter;
1077 }
Nicolas Geoffray08e9eed2017-04-25 17:36:51 +01001078
Calin Juravle44e5efa2017-09-12 00:54:26 -07001079 if (Status() == kOatBootImageOutOfDate) {
1080 return kDex2OatForBootImage;
1081 }
Nicolas Geoffray08e9eed2017-04-25 17:36:51 +01001082 }
1083
1084 if (oat_file_assistant_->HasOriginalDexFiles()) {
1085 return kDex2OatFromScratch;
1086 } else {
1087 // Otherwise there is nothing we can do, even if we want to.
1088 return kNoDexOptNeeded;
1089 }
Richard Uhler70a84262016-11-08 16:51:51 +00001090}
1091
Richard Uhler743bf362016-04-19 15:39:37 -07001092const OatFile* OatFileAssistant::OatFileInfo::GetFile() {
1093 CHECK(!file_released_) << "GetFile called after oat file released.";
1094 if (!load_attempted_) {
1095 load_attempted_ = true;
1096 if (filename_provided_) {
1097 std::string error_msg;
1098 file_.reset(OatFile::Open(filename_.c_str(),
1099 filename_.c_str(),
1100 nullptr,
1101 nullptr,
1102 oat_file_assistant_->load_executable_,
1103 /*low_4gb*/false,
1104 oat_file_assistant_->dex_location_.c_str(),
1105 &error_msg));
1106 if (file_.get() == nullptr) {
1107 VLOG(oat) << "OatFileAssistant test for existing oat file "
1108 << filename_ << ": " << error_msg;
1109 }
1110 }
1111 }
1112 return file_.get();
1113}
1114
1115bool OatFileAssistant::OatFileInfo::CompilerFilterIsOkay(
Shubham Ajmerae4e812a2017-05-25 20:09:58 -07001116 CompilerFilter::Filter target, bool profile_changed, bool downgrade) {
Richard Uhler743bf362016-04-19 15:39:37 -07001117 const OatFile* file = GetFile();
1118 if (file == nullptr) {
1119 return false;
1120 }
1121
1122 CompilerFilter::Filter current = file->GetCompilerFilter();
1123 if (profile_changed && CompilerFilter::DependsOnProfile(current)) {
1124 VLOG(oat) << "Compiler filter not okay because Profile changed";
1125 return false;
1126 }
Shubham Ajmerae4e812a2017-05-25 20:09:58 -07001127 return downgrade ? !CompilerFilter::IsBetter(current, target) :
1128 CompilerFilter::IsAsGoodAs(current, target);
Richard Uhler743bf362016-04-19 15:39:37 -07001129}
1130
Calin Juravle44e5efa2017-09-12 00:54:26 -07001131bool OatFileAssistant::OatFileInfo::ClassLoaderContextIsOkay(ClassLoaderContext* context) {
1132 if (context == nullptr) {
1133 VLOG(oat) << "ClassLoaderContext check ignored: null context";
1134 return true;
1135 }
1136
1137 const OatFile* file = GetFile();
1138 if (file == nullptr) {
1139 return false;
1140 }
1141
1142 size_t dir_index = file->GetLocation().rfind('/');
1143 std::string classpath_dir = (dir_index != std::string::npos)
1144 ? file->GetLocation().substr(0, dir_index)
1145 : "";
1146
1147 if (!context->OpenDexFiles(oat_file_assistant_->isa_, classpath_dir)) {
1148 VLOG(oat) << "ClassLoaderContext check failed: dex files from the context could not be opened";
1149 return false;
1150 }
1151
1152 bool result = context->VerifyClassLoaderContextMatch(file->GetClassLoaderContext());
1153 if (!result) {
1154 VLOG(oat) << "ClassLoaderContext check failed. Context was "
1155 << file->GetClassLoaderContext()
1156 << ". The expected context is " << context->EncodeContextForOatFile(classpath_dir);
1157 }
1158 return result;
1159}
1160
Richard Uhler743bf362016-04-19 15:39:37 -07001161bool OatFileAssistant::OatFileInfo::IsExecutable() {
1162 const OatFile* file = GetFile();
1163 return (file != nullptr && file->IsExecutable());
1164}
1165
Richard Uhler743bf362016-04-19 15:39:37 -07001166void OatFileAssistant::OatFileInfo::Reset() {
1167 load_attempted_ = false;
1168 file_.reset();
1169 status_attempted_ = false;
1170}
1171
1172void OatFileAssistant::OatFileInfo::Reset(const std::string& filename) {
1173 filename_provided_ = true;
1174 filename_ = filename;
1175 Reset();
1176}
1177
1178std::unique_ptr<OatFile> OatFileAssistant::OatFileInfo::ReleaseFile() {
1179 file_released_ = true;
1180 return std::move(file_);
1181}
1182
Richard Uhler70a84262016-11-08 16:51:51 +00001183std::unique_ptr<OatFile> OatFileAssistant::OatFileInfo::ReleaseFileForUse() {
Richard Uhler3e580bc2016-11-08 16:23:07 +00001184 if (Status() == kOatUpToDate) {
Richard Uhler70a84262016-11-08 16:51:51 +00001185 return ReleaseFile();
1186 }
1187
1188 VLOG(oat) << "Oat File Assistant: No relocated oat file found,"
1189 << " attempting to fall back to interpreting oat file instead.";
1190
Richard Uhler03bc6592016-11-22 09:42:04 +00001191 if (Status() == kOatRelocationOutOfDate && !IsExecutable()) {
Richard Uhler70a84262016-11-08 16:51:51 +00001192 return ReleaseFile();
1193 }
1194
Richard Uhler03bc6592016-11-22 09:42:04 +00001195 if (Status() == kOatRelocationOutOfDate) {
Richard Uhler70a84262016-11-08 16:51:51 +00001196 // We are loading an oat file for runtime use that needs relocation.
1197 // Reload the file non-executable to ensure that we interpret out of the
1198 // dex code in the oat file rather than trying to execute the unrelocated
1199 // compiled code.
1200 oat_file_assistant_->load_executable_ = false;
1201 Reset();
Richard Uhler03bc6592016-11-22 09:42:04 +00001202 if (IsUseable()) {
Richard Uhler70a84262016-11-08 16:51:51 +00001203 CHECK(!IsExecutable());
1204 return ReleaseFile();
1205 }
1206 }
1207 return std::unique_ptr<OatFile>();
1208}
Richard Uhler66d874d2015-01-15 09:37:19 -08001209} // namespace art