blob: e3c4cffaa87fac0f8ff2b0b0207c884a605c02e2 [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,
Shubham Ajmerab22dea02017-10-04 18:36:41 -070072 bool load_executable,
73 int vdex_fd,
74 int oat_fd)
Richard Uhler88bc6732016-11-14 14:38:03 +000075 : isa_(isa),
76 load_executable_(load_executable),
77 odex_(this, /*is_oat_location*/ false),
78 oat_(this, /*is_oat_location*/ true) {
Richard Uhler740eec92015-10-15 15:12:23 -070079 CHECK(dex_location != nullptr) << "OatFileAssistant: null dex location";
Calin Juravle357c66d2017-05-04 01:57:17 +000080
81 // Try to get the realpath for the dex location.
82 //
83 // This is OK with respect to dalvik cache naming scheme because we never
84 // generate oat files starting from symlinks which go into dalvik cache.
85 // (recall that the oat files in dalvik cache are encoded by replacing '/'
86 // with '@' in the path).
87 // The boot image oat files (which are symlinked in dalvik-cache) are not
88 // loaded via the oat file assistant.
89 //
90 // The only case when the dex location may resolve to a different path
91 // is for secondary dex files (e.g. /data/user/0 symlinks to /data/data and
92 // the app is free to create its own internal layout). Related to this it is
93 // worthwhile to mention that installd resolves the secondary dex location
94 // before calling dex2oat.
95 UniqueCPtr<const char[]> dex_location_real(realpath(dex_location, nullptr));
96 if (dex_location_real != nullptr) {
97 dex_location_.assign(dex_location_real.get());
98 } else {
99 // If we can't get the realpath of the location there's not much point in trying to move on.
100 PLOG(ERROR) << "Could not get the realpath of dex_location " << dex_location;
101 return;
102 }
Richard Uhler740eec92015-10-15 15:12:23 -0700103
Richard Uhler66d874d2015-01-15 09:37:19 -0800104 if (load_executable_ && isa != kRuntimeISA) {
105 LOG(WARNING) << "OatFileAssistant: Load executable specified, "
106 << "but isa is not kRuntimeISA. Will not attempt to load executable.";
107 load_executable_ = false;
108 }
109
Richard Uhler743bf362016-04-19 15:39:37 -0700110 // Get the odex filename.
Richard Uhlerd684f522016-04-19 13:24:41 -0700111 std::string error_msg;
Richard Uhler743bf362016-04-19 15:39:37 -0700112 std::string odex_file_name;
113 if (DexLocationToOdexFilename(dex_location_, isa_, &odex_file_name, &error_msg)) {
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700114 odex_.Reset(odex_file_name, vdex_fd, oat_fd);
Richard Uhler743bf362016-04-19 15:39:37 -0700115 } else {
Richard Uhlerd684f522016-04-19 13:24:41 -0700116 LOG(WARNING) << "Failed to determine odex file name: " << error_msg;
117 }
118
Richard Uhler743bf362016-04-19 15:39:37 -0700119 // Get the oat filename.
Calin Juravle357c66d2017-05-04 01:57:17 +0000120 std::string oat_file_name;
121 if (DexLocationToOatFilename(dex_location_, isa_, &oat_file_name, &error_msg)) {
122 oat_.Reset(oat_file_name);
Richard Uhlerd684f522016-04-19 13:24:41 -0700123 } else {
Calin Juravle357c66d2017-05-04 01:57:17 +0000124 LOG(WARNING) << "Failed to determine oat file name for dex location "
Calin Juravle9bfc6bb2017-05-04 00:13:50 +0000125 << dex_location_ << ": " << error_msg;
Calin Juravle357c66d2017-05-04 01:57:17 +0000126 }
127
128 // Check if the dex directory is writable.
129 // This will be needed in most uses of OatFileAssistant and so it's OK to
130 // compute it eagerly. (the only use which will not make use of it is
131 // OatFileAssistant::GetStatusDump())
132 size_t pos = dex_location_.rfind('/');
133 if (pos == std::string::npos) {
134 LOG(WARNING) << "Failed to determine dex file parent directory: " << dex_location_;
135 } else {
136 std::string parent = dex_location_.substr(0, pos);
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700137 if (access(parent.c_str(), W_OK) == 0 || oat_fd > 0) {
Calin Juravle357c66d2017-05-04 01:57:17 +0000138 dex_parent_writable_ = true;
139 } else {
140 VLOG(oat) << "Dex parent of " << dex_location_ << " is not writable: " << strerror(errno);
Richard Uhlerd684f522016-04-19 13:24:41 -0700141 }
Richard Uhler66d874d2015-01-15 09:37:19 -0800142 }
Richard Uhler66d874d2015-01-15 09:37:19 -0800143}
144
145OatFileAssistant::~OatFileAssistant() {
146 // Clean up the lock file.
Narayan Kamatha3d27eb2017-05-11 13:50:59 +0100147 if (flock_.get() != nullptr) {
148 unlink(flock_->GetPath().c_str());
Richard Uhler66d874d2015-01-15 09:37:19 -0800149 }
150}
151
152bool OatFileAssistant::IsInBootClassPath() {
153 // Note: We check the current boot class path, regardless of the ISA
154 // specified by the user. This is okay, because the boot class path should
155 // be the same for all ISAs.
156 // TODO: Can we verify the boot class path is the same for all ISAs?
157 Runtime* runtime = Runtime::Current();
158 ClassLinker* class_linker = runtime->GetClassLinker();
159 const auto& boot_class_path = class_linker->GetBootClassPath();
160 for (size_t i = 0; i < boot_class_path.size(); i++) {
Richard Uhler740eec92015-10-15 15:12:23 -0700161 if (boot_class_path[i]->GetLocation() == dex_location_) {
Richard Uhler66d874d2015-01-15 09:37:19 -0800162 VLOG(oat) << "Dex location " << dex_location_ << " is in boot class path";
163 return true;
164 }
165 }
166 return false;
167}
168
169bool OatFileAssistant::Lock(std::string* error_msg) {
170 CHECK(error_msg != nullptr);
Narayan Kamatha3d27eb2017-05-11 13:50:59 +0100171 CHECK(flock_.get() == nullptr) << "OatFileAssistant::Lock already acquired";
Richard Uhler66d874d2015-01-15 09:37:19 -0800172
Calin Juravle357c66d2017-05-04 01:57:17 +0000173 // Note the lock will only succeed for secondary dex files and in test
174 // environment.
175 //
176 // The lock *will fail* for all primary apks in a production environment.
177 // The app does not have permissions to create locks next to its dex location
178 // (be it system, data or vendor parition). We also cannot use the odex or
179 // oat location for the same reasoning.
180 //
181 // This is best effort and if it fails it's unlikely that we will be able
182 // to generate oat files anyway.
183 std::string lock_file_name = dex_location_ + "." + GetInstructionSetString(isa_) + ".flock";
Richard Uhler66d874d2015-01-15 09:37:19 -0800184
Narayan Kamatha3d27eb2017-05-11 13:50:59 +0100185 flock_ = LockedFile::Open(lock_file_name.c_str(), error_msg);
186 if (flock_.get() == nullptr) {
Vladimir Marko66fdcbd2016-04-05 14:19:08 +0100187 unlink(lock_file_name.c_str());
Richard Uhler66d874d2015-01-15 09:37:19 -0800188 return false;
189 }
190 return true;
191}
192
Shubham Ajmerae4e812a2017-05-25 20:09:58 -0700193int OatFileAssistant::GetDexOptNeeded(CompilerFilter::Filter target,
194 bool profile_changed,
Calin Juravle44e5efa2017-09-12 00:54:26 -0700195 bool downgrade,
196 ClassLoaderContext* class_loader_context) {
Richard Uhler88bc6732016-11-14 14:38:03 +0000197 OatFileInfo& info = GetBestInfo();
Calin Juravle44e5efa2017-09-12 00:54:26 -0700198 DexOptNeeded dexopt_needed = info.GetDexOptNeeded(target,
199 profile_changed,
200 downgrade,
201 class_loader_context);
Richard Uhler7225a8d2016-11-22 10:12:03 +0000202 if (info.IsOatLocation() || dexopt_needed == kDex2OatFromScratch) {
203 return dexopt_needed;
Richard Uhler66d874d2015-01-15 09:37:19 -0800204 }
Richard Uhler7225a8d2016-11-22 10:12:03 +0000205 return -dexopt_needed;
Richard Uhler66d874d2015-01-15 09:37:19 -0800206}
207
Richard Uhlerf4b34872016-04-13 11:03:46 -0700208// Figure out the currently specified compile filter option in the runtime.
209// Returns true on success, false if the compiler filter is invalid, in which
210// case error_msg describes the problem.
211static bool GetRuntimeCompilerFilterOption(CompilerFilter::Filter* filter,
212 std::string* error_msg) {
213 CHECK(filter != nullptr);
214 CHECK(error_msg != nullptr);
215
Calin Juravle357c66d2017-05-04 01:57:17 +0000216 *filter = OatFileAssistant::kDefaultCompilerFilterForDexLoading;
Richard Uhlerf4b34872016-04-13 11:03:46 -0700217 for (StringPiece option : Runtime::Current()->GetCompilerOptions()) {
218 if (option.starts_with("--compiler-filter=")) {
219 const char* compiler_filter_string = option.substr(strlen("--compiler-filter=")).data();
220 if (!CompilerFilter::ParseCompilerFilter(compiler_filter_string, filter)) {
221 *error_msg = std::string("Unknown --compiler-filter value: ")
222 + std::string(compiler_filter_string);
223 return false;
224 }
225 }
226 }
227 return true;
228}
229
Richard Uhler01be6812016-05-17 10:34:52 -0700230bool OatFileAssistant::IsUpToDate() {
Richard Uhler88bc6732016-11-14 14:38:03 +0000231 return GetBestInfo().Status() == kOatUpToDate;
Richard Uhler01be6812016-05-17 10:34:52 -0700232}
233
Richard Uhler1e860612016-03-30 12:17:55 -0700234OatFileAssistant::ResultOfAttemptToUpdate
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700235OatFileAssistant::MakeUpToDate(bool profile_changed,
Calin Juravle44e5efa2017-09-12 00:54:26 -0700236 ClassLoaderContext* class_loader_context,
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700237 std::string* error_msg) {
Richard Uhlerf4b34872016-04-13 11:03:46 -0700238 CompilerFilter::Filter target;
239 if (!GetRuntimeCompilerFilterOption(&target, error_msg)) {
240 return kUpdateNotAttempted;
241 }
242
Richard Uhler88bc6732016-11-14 14:38:03 +0000243 OatFileInfo& info = GetBestInfo();
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700244 // TODO(calin, jeffhao): the context should really be passed to GetDexOptNeeded: b/62269291.
245 // This is actually not trivial in the current logic as it will interact with the collision
246 // check:
247 // - currently, if the context does not match but we have no collisions we still accept the
248 // oat file.
249 // - if GetDexOptNeeded would return kDex2OatFromScratch for a context mismatch and we make
250 // the oat code up to date the collision check becomes useless.
251 // - however, MakeUpToDate will not always succeed (e.g. for primary apks, or for dex files
252 // loaded in other processes). So it boils down to how far do we want to complicate
253 // 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 -0700254 switch (info.GetDexOptNeeded(
255 target, profile_changed, /*downgrade*/ false, class_loader_context)) {
Richard Uhler7225a8d2016-11-22 10:12:03 +0000256 case kNoDexOptNeeded:
257 return kUpdateSucceeded;
Richard Uhler88bc6732016-11-14 14:38:03 +0000258
Richard Uhler7225a8d2016-11-22 10:12:03 +0000259 // TODO: For now, don't bother with all the different ways we can call
260 // dex2oat to generate the oat file. Always generate the oat file as if it
261 // were kDex2OatFromScratch.
262 case kDex2OatFromScratch:
263 case kDex2OatForBootImage:
264 case kDex2OatForRelocation:
265 case kDex2OatForFilter:
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700266 return GenerateOatFileNoChecks(info, target, class_loader_context, error_msg);
Richard Uhler66d874d2015-01-15 09:37:19 -0800267 }
268 UNREACHABLE();
269}
270
271std::unique_ptr<OatFile> OatFileAssistant::GetBestOatFile() {
Richard Uhler88bc6732016-11-14 14:38:03 +0000272 return GetBestInfo().ReleaseFileForUse();
Richard Uhler66d874d2015-01-15 09:37:19 -0800273}
274
Richard Uhler46cc64f2016-11-14 14:53:55 +0000275std::string OatFileAssistant::GetStatusDump() {
276 std::ostringstream status;
277 bool oat_file_exists = false;
278 bool odex_file_exists = false;
Richard Uhler03bc6592016-11-22 09:42:04 +0000279 if (oat_.Status() != kOatCannotOpen) {
Richard Uhler2f27abd2017-01-31 14:02:34 +0000280 // If we can open the file, Filename should not return null.
Richard Uhler03bc6592016-11-22 09:42:04 +0000281 CHECK(oat_.Filename() != nullptr);
Richard Uhler03bc6592016-11-22 09:42:04 +0000282
Richard Uhler46cc64f2016-11-14 14:53:55 +0000283 oat_file_exists = true;
Richard Uhler2f27abd2017-01-31 14:02:34 +0000284 status << *oat_.Filename() << "[status=" << oat_.Status() << ", ";
285 const OatFile* file = oat_.GetFile();
286 if (file == nullptr) {
287 // If the file is null even though the status is not kOatCannotOpen, it
288 // means we must have a vdex file with no corresponding oat file. In
289 // this case we cannot determine the compilation filter. Indicate that
290 // we have only the vdex file instead.
291 status << "vdex-only";
292 } else {
293 status << "compilation_filter=" << CompilerFilter::NameOfFilter(file->GetCompilerFilter());
294 }
Richard Uhler46cc64f2016-11-14 14:53:55 +0000295 }
296
Richard Uhler03bc6592016-11-22 09:42:04 +0000297 if (odex_.Status() != kOatCannotOpen) {
Richard Uhler2f27abd2017-01-31 14:02:34 +0000298 // If we can open the file, Filename should not return null.
Richard Uhler03bc6592016-11-22 09:42:04 +0000299 CHECK(odex_.Filename() != nullptr);
Richard Uhler03bc6592016-11-22 09:42:04 +0000300
Richard Uhler46cc64f2016-11-14 14:53:55 +0000301 odex_file_exists = true;
302 if (oat_file_exists) {
303 status << "] ";
304 }
Richard Uhler2f27abd2017-01-31 14:02:34 +0000305 status << *odex_.Filename() << "[status=" << odex_.Status() << ", ";
306 const OatFile* file = odex_.GetFile();
307 if (file == nullptr) {
308 status << "vdex-only";
309 } else {
310 status << "compilation_filter=" << CompilerFilter::NameOfFilter(file->GetCompilerFilter());
311 }
Richard Uhler46cc64f2016-11-14 14:53:55 +0000312 }
313
314 if (!oat_file_exists && !odex_file_exists) {
315 status << "invalid[";
316 }
317
318 status << "]";
319 return status.str();
320}
321
Richard Uhler66d874d2015-01-15 09:37:19 -0800322std::vector<std::unique_ptr<const DexFile>> OatFileAssistant::LoadDexFiles(
Calin Juravle87e2cb62017-06-13 21:48:45 -0700323 const OatFile &oat_file, const char *dex_location) {
Richard Uhler66d874d2015-01-15 09:37:19 -0800324 std::vector<std::unique_ptr<const DexFile>> dex_files;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700325 if (LoadDexFiles(oat_file, dex_location, &dex_files)) {
326 return dex_files;
327 } else {
328 return std::vector<std::unique_ptr<const DexFile>>();
329 }
330}
Richard Uhler66d874d2015-01-15 09:37:19 -0800331
Calin Juravle87e2cb62017-06-13 21:48:45 -0700332bool OatFileAssistant::LoadDexFiles(
333 const OatFile &oat_file,
334 const std::string& dex_location,
335 std::vector<std::unique_ptr<const DexFile>>* out_dex_files) {
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000336 // Load the main dex file.
Richard Uhler66d874d2015-01-15 09:37:19 -0800337 std::string error_msg;
338 const OatFile::OatDexFile* oat_dex_file = oat_file.GetOatDexFile(
Calin Juravle87e2cb62017-06-13 21:48:45 -0700339 dex_location.c_str(), nullptr, &error_msg);
Richard Uhler66d874d2015-01-15 09:37:19 -0800340 if (oat_dex_file == nullptr) {
Richard Uhler9a37efc2016-08-05 16:32:55 -0700341 LOG(WARNING) << error_msg;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700342 return false;
Richard Uhler66d874d2015-01-15 09:37:19 -0800343 }
344
Igor Murashkinb1d8c312015-08-04 11:18:43 -0700345 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
Richard Uhler66d874d2015-01-15 09:37:19 -0800346 if (dex_file.get() == nullptr) {
347 LOG(WARNING) << "Failed to open dex file from oat dex file: " << error_msg;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700348 return false;
Richard Uhler66d874d2015-01-15 09:37:19 -0800349 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700350 out_dex_files->push_back(std::move(dex_file));
Richard Uhler66d874d2015-01-15 09:37:19 -0800351
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000352 // Load the rest of the multidex entries
Calin Juravle87e2cb62017-06-13 21:48:45 -0700353 for (size_t i = 1;; i++) {
354 std::string multidex_dex_location = DexFile::GetMultiDexLocation(i, dex_location.c_str());
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000355 oat_dex_file = oat_file.GetOatDexFile(multidex_dex_location.c_str(), nullptr);
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700356 if (oat_dex_file == nullptr) {
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000357 // There are no more multidex entries to load.
Richard Uhler66d874d2015-01-15 09:37:19 -0800358 break;
359 }
360
Igor Murashkinb1d8c312015-08-04 11:18:43 -0700361 dex_file = oat_dex_file->OpenDexFile(&error_msg);
Richard Uhler66d874d2015-01-15 09:37:19 -0800362 if (dex_file.get() == nullptr) {
363 LOG(WARNING) << "Failed to open dex file from oat dex file: " << error_msg;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700364 return false;
Richard Uhler66d874d2015-01-15 09:37:19 -0800365 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700366 out_dex_files->push_back(std::move(dex_file));
Richard Uhler66d874d2015-01-15 09:37:19 -0800367 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700368 return true;
Richard Uhler66d874d2015-01-15 09:37:19 -0800369}
370
Richard Uhler9b994ea2015-06-24 08:44:19 -0700371bool OatFileAssistant::HasOriginalDexFiles() {
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000372 // Ensure GetRequiredDexChecksums has been run so that
Richard Uhler9b994ea2015-06-24 08:44:19 -0700373 // has_original_dex_files_ is initialized. We don't care about the result of
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000374 // GetRequiredDexChecksums.
375 GetRequiredDexChecksums();
Richard Uhler9b994ea2015-06-24 08:44:19 -0700376 return has_original_dex_files_;
377}
378
Richard Uhler95abd042015-03-24 09:51:28 -0700379OatFileAssistant::OatStatus OatFileAssistant::OdexFileStatus() {
Richard Uhler743bf362016-04-19 15:39:37 -0700380 return odex_.Status();
Richard Uhler66d874d2015-01-15 09:37:19 -0800381}
382
Richard Uhler95abd042015-03-24 09:51:28 -0700383OatFileAssistant::OatStatus OatFileAssistant::OatFileStatus() {
Richard Uhler743bf362016-04-19 15:39:37 -0700384 return oat_.Status();
Richard Uhler66d874d2015-01-15 09:37:19 -0800385}
386
Richard Uhler2f27abd2017-01-31 14:02:34 +0000387bool OatFileAssistant::DexChecksumUpToDate(const VdexFile& file, std::string* error_msg) {
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000388 const std::vector<uint32_t>* required_dex_checksums = GetRequiredDexChecksums();
389 if (required_dex_checksums == nullptr) {
390 LOG(WARNING) << "Required dex checksums not found. Assuming dex checksums are up to date.";
391 return true;
392 }
393
394 uint32_t number_of_dex_files = file.GetHeader().GetNumberOfDexFiles();
395 if (required_dex_checksums->size() != number_of_dex_files) {
396 *error_msg = StringPrintf("expected %zu dex files but found %u",
397 required_dex_checksums->size(),
398 number_of_dex_files);
Richard Uhler2f27abd2017-01-31 14:02:34 +0000399 return false;
Andreas Gampef8cd8902017-01-18 16:05:01 -0800400 }
401
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000402 for (uint32_t i = 0; i < number_of_dex_files; i++) {
403 uint32_t expected_checksum = (*required_dex_checksums)[i];
404 uint32_t actual_checksum = file.GetLocationChecksum(i);
405 if (expected_checksum != actual_checksum) {
406 std::string dex = DexFile::GetMultiDexLocation(i, dex_location_.c_str());
407 *error_msg = StringPrintf("Dex checksum does not match for dex: %s."
408 "Expected: %u, actual: %u",
409 dex.c_str(),
410 expected_checksum,
411 actual_checksum);
Richard Uhler2f27abd2017-01-31 14:02:34 +0000412 return false;
413 }
414 }
415
Richard Uhler2f27abd2017-01-31 14:02:34 +0000416 return true;
417}
418
419bool OatFileAssistant::DexChecksumUpToDate(const OatFile& file, std::string* error_msg) {
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000420 const std::vector<uint32_t>* required_dex_checksums = GetRequiredDexChecksums();
421 if (required_dex_checksums == nullptr) {
422 LOG(WARNING) << "Required dex checksums not found. Assuming dex checksums are up to date.";
423 return true;
424 }
425
426 uint32_t number_of_dex_files = file.GetOatHeader().GetDexFileCount();
427 if (required_dex_checksums->size() != number_of_dex_files) {
428 *error_msg = StringPrintf("expected %zu dex files but found %u",
429 required_dex_checksums->size(),
430 number_of_dex_files);
Richard Uhler2f27abd2017-01-31 14:02:34 +0000431 return false;
Richard Uhler66d874d2015-01-15 09:37:19 -0800432 }
433
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000434 for (uint32_t i = 0; i < number_of_dex_files; i++) {
435 std::string dex = DexFile::GetMultiDexLocation(i, dex_location_.c_str());
436 uint32_t expected_checksum = (*required_dex_checksums)[i];
437 const OatFile::OatDexFile* oat_dex_file = file.GetOatDexFile(dex.c_str(), nullptr);
438 if (oat_dex_file == nullptr) {
439 *error_msg = StringPrintf("failed to find %s in %s", dex.c_str(), file.GetLocation().c_str());
440 return false;
Richard Uhler66d874d2015-01-15 09:37:19 -0800441 }
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000442 uint32_t actual_checksum = oat_dex_file->GetDexFileLocationChecksum();
443 if (expected_checksum != actual_checksum) {
444 VLOG(oat) << "Dex checksum does not match for dex: " << dex
445 << ". Expected: " << expected_checksum
446 << ", Actual: " << actual_checksum;
447 return false;
Richard Uhler66d874d2015-01-15 09:37:19 -0800448 }
449 }
Richard Uhler2f27abd2017-01-31 14:02:34 +0000450 return true;
451}
452
453OatFileAssistant::OatStatus OatFileAssistant::GivenOatFileStatus(const OatFile& file) {
454 // Verify the ART_USE_READ_BARRIER state.
455 // TODO: Don't fully reject files due to read barrier state. If they contain
456 // compiled code and are otherwise okay, we should return something like
457 // kOatRelocationOutOfDate. If they don't contain compiled code, the read
458 // barrier state doesn't matter.
459 const bool is_cc = file.GetOatHeader().IsConcurrentCopying();
460 constexpr bool kRuntimeIsCC = kUseReadBarrier;
461 if (is_cc != kRuntimeIsCC) {
462 return kOatCannotOpen;
463 }
464
465 // Verify the dex checksum.
466 std::string error_msg;
467 if (kIsVdexEnabled) {
468 VdexFile* vdex = file.GetVdexFile();
469 if (!DexChecksumUpToDate(*vdex, &error_msg)) {
470 LOG(ERROR) << error_msg;
471 return kOatDexOutOfDate;
472 }
473 } else {
474 if (!DexChecksumUpToDate(file, &error_msg)) {
475 LOG(ERROR) << error_msg;
476 return kOatDexOutOfDate;
477 }
478 }
Richard Uhler66d874d2015-01-15 09:37:19 -0800479
Andreas Gampe29d38e72016-03-23 15:31:51 +0000480 CompilerFilter::Filter current_compiler_filter = file.GetCompilerFilter();
David Brazdilce4b0ba2016-01-28 15:05:49 +0000481
Richard Uhler66d874d2015-01-15 09:37:19 -0800482 // Verify the image checksum
Andreas Gampe29d38e72016-03-23 15:31:51 +0000483 if (CompilerFilter::DependsOnImageChecksum(current_compiler_filter)) {
484 const ImageInfo* image_info = GetImageInfo();
485 if (image_info == nullptr) {
486 VLOG(oat) << "No image for oat image checksum to match against.";
Andreas Gampe29d38e72016-03-23 15:31:51 +0000487
Richard Uhler76f5cb62016-04-04 13:30:16 -0700488 if (HasOriginalDexFiles()) {
Richard Uhler03bc6592016-11-22 09:42:04 +0000489 return kOatBootImageOutOfDate;
Richard Uhler76f5cb62016-04-04 13:30:16 -0700490 }
491
492 // If there is no original dex file to fall back to, grudgingly accept
493 // the oat file. This could technically lead to crashes, but there's no
494 // way we could find a better oat file to use for this dex location,
495 // and it's better than being stuck in a boot loop with no way out.
496 // The problem will hopefully resolve itself the next time the runtime
497 // starts up.
498 LOG(WARNING) << "Dex location " << dex_location_ << " does not seem to include dex file. "
499 << "Allow oat file use. This is potentially dangerous.";
Richard Uhler95e09672017-02-22 11:37:41 +0000500 } else if (file.GetOatHeader().GetImageFileLocationOatChecksum() != image_info->oat_checksum) {
Andreas Gampe29d38e72016-03-23 15:31:51 +0000501 VLOG(oat) << "Oat image checksum does not match image checksum.";
Richard Uhler03bc6592016-11-22 09:42:04 +0000502 return kOatBootImageOutOfDate;
Andreas Gampe29d38e72016-03-23 15:31:51 +0000503 }
504 } else {
505 VLOG(oat) << "Image checksum test skipped for compiler filter " << current_compiler_filter;
Richard Uhler66d874d2015-01-15 09:37:19 -0800506 }
507
Nicolas Geoffray49cda062017-04-21 13:08:25 +0100508 if (CompilerFilter::IsAotCompilationEnabled(current_compiler_filter)) {
Andreas Gampe29d38e72016-03-23 15:31:51 +0000509 if (!file.IsPic()) {
510 const ImageInfo* image_info = GetImageInfo();
511 if (image_info == nullptr) {
512 VLOG(oat) << "No image to check oat relocation against.";
Richard Uhler03bc6592016-11-22 09:42:04 +0000513 return kOatRelocationOutOfDate;
Andreas Gampe29d38e72016-03-23 15:31:51 +0000514 }
Richard Uhlera62d2f02016-03-18 15:05:30 -0700515
Andreas Gampe29d38e72016-03-23 15:31:51 +0000516 // Verify the oat_data_begin recorded for the image in the oat file matches
517 // the actual oat_data_begin for boot.oat in the image.
518 const OatHeader& oat_header = file.GetOatHeader();
519 uintptr_t oat_data_begin = oat_header.GetImageFileLocationOatDataBegin();
520 if (oat_data_begin != image_info->oat_data_begin) {
521 VLOG(oat) << file.GetLocation() <<
522 ": Oat file image oat_data_begin (" << oat_data_begin << ")"
523 << " does not match actual image oat_data_begin ("
524 << image_info->oat_data_begin << ")";
Richard Uhler03bc6592016-11-22 09:42:04 +0000525 return kOatRelocationOutOfDate;
Andreas Gampe29d38e72016-03-23 15:31:51 +0000526 }
Richard Uhlera62d2f02016-03-18 15:05:30 -0700527
Andreas Gampe29d38e72016-03-23 15:31:51 +0000528 // Verify the oat_patch_delta recorded for the image in the oat file matches
529 // the actual oat_patch_delta for the image.
530 int32_t oat_patch_delta = oat_header.GetImagePatchDelta();
531 if (oat_patch_delta != image_info->patch_delta) {
532 VLOG(oat) << file.GetLocation() <<
533 ": Oat file image patch delta (" << oat_patch_delta << ")"
534 << " does not match actual image patch delta ("
535 << image_info->patch_delta << ")";
Richard Uhler03bc6592016-11-22 09:42:04 +0000536 return kOatRelocationOutOfDate;
Andreas Gampe29d38e72016-03-23 15:31:51 +0000537 }
538 } else {
539 // Oat files compiled in PIC mode do not require relocation.
540 VLOG(oat) << "Oat relocation test skipped for PIC oat file";
541 }
542 } else {
543 VLOG(oat) << "Oat relocation test skipped for compiler filter " << current_compiler_filter;
Richard Uhler66d874d2015-01-15 09:37:19 -0800544 }
Richard Uhlere8109f72016-04-18 10:40:50 -0700545 return kOatUpToDate;
Richard Uhler66d874d2015-01-15 09:37:19 -0800546}
547
Calin Juravle357c66d2017-05-04 01:57:17 +0000548static bool DexLocationToOdexNames(const std::string& location,
549 InstructionSet isa,
550 std::string* odex_filename,
551 std::string* oat_dir,
552 std::string* isa_dir,
553 std::string* error_msg) {
554 CHECK(odex_filename != nullptr);
555 CHECK(error_msg != nullptr);
556
557 // The odex file name is formed by replacing the dex_location extension with
558 // .odex and inserting an oat/<isa> directory. For example:
559 // location = /foo/bar/baz.jar
560 // odex_location = /foo/bar/oat/<isa>/baz.odex
561
562 // Find the directory portion of the dex location and add the oat/<isa>
563 // directory.
564 size_t pos = location.rfind('/');
565 if (pos == std::string::npos) {
566 *error_msg = "Dex location " + location + " has no directory.";
567 return false;
568 }
569 std::string dir = location.substr(0, pos+1);
570 // Add the oat directory.
571 dir += "oat";
572 if (oat_dir != nullptr) {
573 *oat_dir = dir;
574 }
575 // Add the isa directory
576 dir += "/" + std::string(GetInstructionSetString(isa));
577 if (isa_dir != nullptr) {
578 *isa_dir = dir;
579 }
580
581 // Get the base part of the file without the extension.
582 std::string file = location.substr(pos+1);
583 pos = file.rfind('.');
584 if (pos == std::string::npos) {
585 *error_msg = "Dex location " + location + " has no extension.";
586 return false;
587 }
588 std::string base = file.substr(0, pos);
589
590 *odex_filename = dir + "/" + base + ".odex";
591 return true;
592}
593
594// Prepare a subcomponent of the odex directory.
595// (i.e. create and set the expected permissions on the path `dir`).
596static bool PrepareDirectory(const std::string& dir, std::string* error_msg) {
597 struct stat dir_stat;
598 if (TEMP_FAILURE_RETRY(stat(dir.c_str(), &dir_stat)) == 0) {
599 // The directory exists. Check if it is indeed a directory.
600 if (!S_ISDIR(dir_stat.st_mode)) {
601 *error_msg = dir + " is not a dir";
602 return false;
603 } else {
604 // The dir is already on disk.
605 return true;
606 }
607 }
608
609 // Failed to stat. We need to create the directory.
610 if (errno != ENOENT) {
611 *error_msg = "Could not stat isa dir " + dir + ":" + strerror(errno);
612 return false;
613 }
614
615 mode_t mode = S_IRWXU | S_IXGRP | S_IXOTH;
616 if (mkdir(dir.c_str(), mode) != 0) {
617 *error_msg = "Could not create dir " + dir + ":" + strerror(errno);
618 return false;
619 }
620 if (chmod(dir.c_str(), mode) != 0) {
621 *error_msg = "Could not create the oat dir " + dir + ":" + strerror(errno);
622 return false;
623 }
624 return true;
625}
626
627// Prepares the odex directory for the given dex location.
628static bool PrepareOdexDirectories(const std::string& dex_location,
629 const std::string& expected_odex_location,
630 InstructionSet isa,
631 std::string* error_msg) {
632 std::string actual_odex_location;
633 std::string oat_dir;
634 std::string isa_dir;
635 if (!DexLocationToOdexNames(
636 dex_location, isa, &actual_odex_location, &oat_dir, &isa_dir, error_msg)) {
637 return false;
638 }
639 DCHECK_EQ(expected_odex_location, actual_odex_location);
640
641 if (!PrepareDirectory(oat_dir, error_msg)) {
642 return false;
643 }
644 if (!PrepareDirectory(isa_dir, error_msg)) {
645 return false;
646 }
647 return true;
648}
649
Calin Juravled4215bb2017-09-20 11:54:21 -0700650class Dex2oatFileWrapper {
651 public:
652 explicit Dex2oatFileWrapper(File* file)
653 : file_(file),
654 unlink_file_at_destruction_(true) {
655 }
656
657 ~Dex2oatFileWrapper() {
658 if (unlink_file_at_destruction_ && (file_ != nullptr)) {
659 file_->Erase(/*unlink*/ true);
660 }
661 }
662
663 File* GetFile() { return file_.get(); }
664
665 void DisableUnlinkAtDestruction() {
666 unlink_file_at_destruction_ = false;
667 };
668
669 private:
670 std::unique_ptr<File> file_;
671 bool unlink_file_at_destruction_;
672};
673
Calin Juravle357c66d2017-05-04 01:57:17 +0000674OatFileAssistant::ResultOfAttemptToUpdate OatFileAssistant::GenerateOatFileNoChecks(
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700675 OatFileAssistant::OatFileInfo& info,
676 CompilerFilter::Filter filter,
Calin Juravle44e5efa2017-09-12 00:54:26 -0700677 const ClassLoaderContext* class_loader_context,
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700678 std::string* error_msg) {
Richard Uhler66d874d2015-01-15 09:37:19 -0800679 CHECK(error_msg != nullptr);
680
Richard Uhler8327cf72015-10-13 16:34:59 -0700681 Runtime* runtime = Runtime::Current();
682 if (!runtime->IsDex2OatEnabled()) {
683 *error_msg = "Generation of oat file for dex location " + dex_location_
684 + " not attempted because dex2oat is disabled.";
Richard Uhler1e860612016-03-30 12:17:55 -0700685 return kUpdateNotAttempted;
Richard Uhler8327cf72015-10-13 16:34:59 -0700686 }
687
Calin Juravle357c66d2017-05-04 01:57:17 +0000688 if (info.Filename() == nullptr) {
Richard Uhler740eec92015-10-15 15:12:23 -0700689 *error_msg = "Generation of oat file for dex location " + dex_location_
Richard Uhler66d874d2015-01-15 09:37:19 -0800690 + " not attempted because the oat file name could not be determined.";
Richard Uhler1e860612016-03-30 12:17:55 -0700691 return kUpdateNotAttempted;
Richard Uhler66d874d2015-01-15 09:37:19 -0800692 }
Calin Juravle357c66d2017-05-04 01:57:17 +0000693 const std::string& oat_file_name = *info.Filename();
Calin Juravle367b9d82017-05-15 18:18:39 -0700694 const std::string& vdex_file_name = GetVdexFilename(oat_file_name);
Richard Uhler66d874d2015-01-15 09:37:19 -0800695
Richard Uhler66d874d2015-01-15 09:37:19 -0800696 // dex2oat ignores missing dex files and doesn't report an error.
697 // Check explicitly here so we can detect the error properly.
698 // TODO: Why does dex2oat behave that way?
Calin Juravle357c66d2017-05-04 01:57:17 +0000699 struct stat dex_path_stat;
700 if (TEMP_FAILURE_RETRY(stat(dex_location_.c_str(), &dex_path_stat)) != 0) {
701 *error_msg = "Could not access dex location " + dex_location_ + ":" + strerror(errno);
Richard Uhler1e860612016-03-30 12:17:55 -0700702 return kUpdateNotAttempted;
Richard Uhler66d874d2015-01-15 09:37:19 -0800703 }
704
Calin Juravle357c66d2017-05-04 01:57:17 +0000705 // If this is the odex location, we need to create the odex file layout (../oat/isa/..)
706 if (!info.IsOatLocation()) {
707 if (!PrepareOdexDirectories(dex_location_, oat_file_name, isa_, error_msg)) {
708 return kUpdateNotAttempted;
709 }
710 }
711
712 // Set the permissions for the oat and the vdex files.
713 // The user always gets read and write while the group and others propagate
714 // the reading access of the original dex file.
715 mode_t file_mode = S_IRUSR | S_IWUSR |
716 (dex_path_stat.st_mode & S_IRGRP) |
717 (dex_path_stat.st_mode & S_IROTH);
718
Calin Juravled4215bb2017-09-20 11:54:21 -0700719 Dex2oatFileWrapper vdex_file_wrapper(OS::CreateEmptyFile(vdex_file_name.c_str()));
720 File* vdex_file = vdex_file_wrapper.GetFile();
721 if (vdex_file == nullptr) {
David Brazdil7b49e6c2016-09-01 11:06:18 +0100722 *error_msg = "Generation of oat file " + oat_file_name
723 + " not attempted because the vdex file " + vdex_file_name
724 + " could not be opened.";
725 return kUpdateNotAttempted;
726 }
727
Calin Juravle357c66d2017-05-04 01:57:17 +0000728 if (fchmod(vdex_file->Fd(), file_mode) != 0) {
David Brazdil7b49e6c2016-09-01 11:06:18 +0100729 *error_msg = "Generation of oat file " + oat_file_name
730 + " not attempted because the vdex file " + vdex_file_name
731 + " could not be made world readable.";
732 return kUpdateNotAttempted;
733 }
734
Calin Juravled4215bb2017-09-20 11:54:21 -0700735 Dex2oatFileWrapper oat_file_wrapper(OS::CreateEmptyFile(oat_file_name.c_str()));
736 File* oat_file = oat_file_wrapper.GetFile();
737 if (oat_file == nullptr) {
Richard Uhler8327cf72015-10-13 16:34:59 -0700738 *error_msg = "Generation of oat file " + oat_file_name
739 + " not attempted because the oat file could not be created.";
Richard Uhler1e860612016-03-30 12:17:55 -0700740 return kUpdateNotAttempted;
Richard Uhler8327cf72015-10-13 16:34:59 -0700741 }
742
Calin Juravle357c66d2017-05-04 01:57:17 +0000743 if (fchmod(oat_file->Fd(), file_mode) != 0) {
Richard Uhler8327cf72015-10-13 16:34:59 -0700744 *error_msg = "Generation of oat file " + oat_file_name
745 + " not attempted because the oat file could not be made world readable.";
Richard Uhler1e860612016-03-30 12:17:55 -0700746 return kUpdateNotAttempted;
Richard Uhler8327cf72015-10-13 16:34:59 -0700747 }
748
749 std::vector<std::string> args;
750 args.push_back("--dex-file=" + dex_location_);
Nicolas Geoffraya6a448a2016-11-10 10:49:40 +0000751 args.push_back("--output-vdex-fd=" + std::to_string(vdex_file->Fd()));
Richard Uhler8327cf72015-10-13 16:34:59 -0700752 args.push_back("--oat-fd=" + std::to_string(oat_file->Fd()));
753 args.push_back("--oat-location=" + oat_file_name);
Calin Juravle07c6d722017-06-07 17:06:12 +0000754 args.push_back("--compiler-filter=" + CompilerFilter::NameOfFilter(filter));
Calin Juravle44e5efa2017-09-12 00:54:26 -0700755 const std::string dex2oat_context = class_loader_context == nullptr
756 ? OatFile::kSpecialSharedLibrary
757 : class_loader_context->EncodeContextForDex2oat(/*base_dir*/ "");
758 args.push_back("--class-loader-context=" + dex2oat_context);
Richard Uhler8327cf72015-10-13 16:34:59 -0700759
Richard Uhler66d874d2015-01-15 09:37:19 -0800760 if (!Dex2Oat(args, error_msg)) {
Richard Uhler1e860612016-03-30 12:17:55 -0700761 return kUpdateFailed;
Richard Uhler8327cf72015-10-13 16:34:59 -0700762 }
763
David Brazdil7b49e6c2016-09-01 11:06:18 +0100764 if (vdex_file->FlushCloseOrErase() != 0) {
765 *error_msg = "Unable to close vdex file " + vdex_file_name;
David Brazdil7b49e6c2016-09-01 11:06:18 +0100766 return kUpdateFailed;
767 }
768
Richard Uhler8327cf72015-10-13 16:34:59 -0700769 if (oat_file->FlushCloseOrErase() != 0) {
770 *error_msg = "Unable to close oat file " + oat_file_name;
Richard Uhler1e860612016-03-30 12:17:55 -0700771 return kUpdateFailed;
Richard Uhler66d874d2015-01-15 09:37:19 -0800772 }
773
Calin Juravle357c66d2017-05-04 01:57:17 +0000774 // Mark that the odex file has changed and we should try to reload.
775 info.Reset();
Calin Juravled4215bb2017-09-20 11:54:21 -0700776 // We have compiled successfully. Disable the auto-unlink.
777 vdex_file_wrapper.DisableUnlinkAtDestruction();
778 oat_file_wrapper.DisableUnlinkAtDestruction();
779
Richard Uhler1e860612016-03-30 12:17:55 -0700780 return kUpdateSucceeded;
Richard Uhler66d874d2015-01-15 09:37:19 -0800781}
782
783bool OatFileAssistant::Dex2Oat(const std::vector<std::string>& args,
784 std::string* error_msg) {
785 Runtime* runtime = Runtime::Current();
786 std::string image_location = ImageLocation();
787 if (image_location.empty()) {
788 *error_msg = "No image location found for Dex2Oat.";
789 return false;
790 }
791
792 std::vector<std::string> argv;
793 argv.push_back(runtime->GetCompilerExecutable());
Nicolas Geoffray433b79a2017-01-30 20:54:45 +0000794 if (runtime->IsJavaDebuggable()) {
Sebastien Hertz0de11332015-05-13 12:14:05 +0200795 argv.push_back("--debuggable");
796 }
Igor Murashkinb1d8c312015-08-04 11:18:43 -0700797 runtime->AddCurrentRuntimeFeaturesAsDex2OatArguments(&argv);
Richard Uhler66d874d2015-01-15 09:37:19 -0800798
799 if (!runtime->IsVerificationEnabled()) {
800 argv.push_back("--compiler-filter=verify-none");
801 }
802
803 if (runtime->MustRelocateIfPossible()) {
804 argv.push_back("--runtime-arg");
805 argv.push_back("-Xrelocate");
806 } else {
807 argv.push_back("--runtime-arg");
808 argv.push_back("-Xnorelocate");
809 }
810
811 if (!kIsTargetBuild) {
812 argv.push_back("--host");
813 }
814
815 argv.push_back("--boot-image=" + image_location);
816
817 std::vector<std::string> compiler_options = runtime->GetCompilerOptions();
818 argv.insert(argv.end(), compiler_options.begin(), compiler_options.end());
819
820 argv.insert(argv.end(), args.begin(), args.end());
821
Andreas Gampe9186ced2016-12-12 14:28:21 -0800822 std::string command_line(android::base::Join(argv, ' '));
Richard Uhler66d874d2015-01-15 09:37:19 -0800823 return Exec(argv, error_msg);
824}
825
Richard Uhlerb81881d2016-04-19 13:08:04 -0700826bool OatFileAssistant::DexLocationToOdexFilename(const std::string& location,
827 InstructionSet isa,
828 std::string* odex_filename,
829 std::string* error_msg) {
Calin Juravle357c66d2017-05-04 01:57:17 +0000830 return DexLocationToOdexNames(location, isa, odex_filename, nullptr, nullptr, error_msg);
Richard Uhler66d874d2015-01-15 09:37:19 -0800831}
832
Richard Uhlerb81881d2016-04-19 13:08:04 -0700833bool OatFileAssistant::DexLocationToOatFilename(const std::string& location,
834 InstructionSet isa,
835 std::string* oat_filename,
836 std::string* error_msg) {
837 CHECK(oat_filename != nullptr);
838 CHECK(error_msg != nullptr);
Richard Uhler66d874d2015-01-15 09:37:19 -0800839
Richard Uhler55b58b62016-08-12 09:05:13 -0700840 std::string cache_dir = GetDalvikCache(GetInstructionSetString(isa));
841 if (cache_dir.empty()) {
842 *error_msg = "Dalvik cache directory does not exist";
843 return false;
844 }
Richard Uhlerb81881d2016-04-19 13:08:04 -0700845
846 // TODO: The oat file assistant should be the definitive place for
847 // determining the oat file name from the dex location, not
848 // GetDalvikCacheFilename.
Richard Uhlerb81881d2016-04-19 13:08:04 -0700849 return GetDalvikCacheFilename(location.c_str(), cache_dir.c_str(), oat_filename, error_msg);
Richard Uhler66d874d2015-01-15 09:37:19 -0800850}
851
Richard Uhler66d874d2015-01-15 09:37:19 -0800852std::string OatFileAssistant::ImageLocation() {
853 Runtime* runtime = Runtime::Current();
Andreas Gampe8994a042015-12-30 19:03:17 +0000854 const std::vector<gc::space::ImageSpace*>& image_spaces =
855 runtime->GetHeap()->GetBootImageSpaces();
856 if (image_spaces.empty()) {
857 return "";
858 }
859 return image_spaces[0]->GetImageLocation();
Richard Uhler66d874d2015-01-15 09:37:19 -0800860}
861
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000862const std::vector<uint32_t>* OatFileAssistant::GetRequiredDexChecksums() {
863 if (!required_dex_checksums_attempted_) {
864 required_dex_checksums_attempted_ = true;
865 required_dex_checksums_found_ = false;
866 cached_required_dex_checksums_.clear();
Richard Uhler66d874d2015-01-15 09:37:19 -0800867 std::string error_msg;
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000868 if (DexFile::GetMultiDexChecksums(dex_location_.c_str(),
869 &cached_required_dex_checksums_,
870 &error_msg)) {
871 required_dex_checksums_found_ = true;
Richard Uhler9b994ea2015-06-24 08:44:19 -0700872 has_original_dex_files_ = true;
Richard Uhler66d874d2015-01-15 09:37:19 -0800873 } else {
874 // This can happen if the original dex file has been stripped from the
875 // apk.
876 VLOG(oat) << "OatFileAssistant: " << error_msg;
Richard Uhler9b994ea2015-06-24 08:44:19 -0700877 has_original_dex_files_ = false;
Richard Uhler66d874d2015-01-15 09:37:19 -0800878
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000879 // Get the checksums from the odex if we can.
Richard Uhler743bf362016-04-19 15:39:37 -0700880 const OatFile* odex_file = odex_.GetFile();
Richard Uhler66d874d2015-01-15 09:37:19 -0800881 if (odex_file != nullptr) {
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000882 required_dex_checksums_found_ = true;
883 for (size_t i = 0; i < odex_file->GetOatHeader().GetDexFileCount(); i++) {
884 std::string dex = DexFile::GetMultiDexLocation(i, dex_location_.c_str());
885 const OatFile::OatDexFile* odex_dex_file = odex_file->GetOatDexFile(dex.c_str(), nullptr);
886 if (odex_dex_file == nullptr) {
887 required_dex_checksums_found_ = false;
888 break;
889 }
890 cached_required_dex_checksums_.push_back(odex_dex_file->GetDexFileLocationChecksum());
Richard Uhler66d874d2015-01-15 09:37:19 -0800891 }
892 }
893 }
894 }
Richard Uhler69bcf2c2017-01-24 10:25:21 +0000895 return required_dex_checksums_found_ ? &cached_required_dex_checksums_ : nullptr;
Richard Uhler66d874d2015-01-15 09:37:19 -0800896}
897
Richard Uhler95e09672017-02-22 11:37:41 +0000898std::unique_ptr<OatFileAssistant::ImageInfo>
899OatFileAssistant::ImageInfo::GetRuntimeImageInfo(InstructionSet isa, std::string* error_msg) {
900 CHECK(error_msg != nullptr);
901
Richard Uhler95e09672017-02-22 11:37:41 +0000902 Runtime* runtime = Runtime::Current();
Richard Uhler8f104862017-02-22 12:34:01 +0000903 std::unique_ptr<ImageInfo> info(new ImageInfo());
904 info->location = runtime->GetImageLocation();
905
906 std::unique_ptr<ImageHeader> image_header(
907 gc::space::ImageSpace::ReadImageHeader(info->location.c_str(), isa, error_msg));
908 if (image_header == nullptr) {
Richard Uhler95e09672017-02-22 11:37:41 +0000909 return nullptr;
910 }
911
Richard Uhler8f104862017-02-22 12:34:01 +0000912 info->oat_checksum = image_header->GetOatChecksum();
913 info->oat_data_begin = reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin());
914 info->patch_delta = image_header->GetPatchDelta();
Richard Uhler95e09672017-02-22 11:37:41 +0000915 return info;
916}
917
Richard Uhler66d874d2015-01-15 09:37:19 -0800918const OatFileAssistant::ImageInfo* OatFileAssistant::GetImageInfo() {
919 if (!image_info_load_attempted_) {
920 image_info_load_attempted_ = true;
Richard Uhler95e09672017-02-22 11:37:41 +0000921 std::string error_msg;
922 cached_image_info_ = ImageInfo::GetRuntimeImageInfo(isa_, &error_msg);
923 if (cached_image_info_ == nullptr) {
924 LOG(WARNING) << "Unable to get runtime image info: " << error_msg;
Richard Uhler66d874d2015-01-15 09:37:19 -0800925 }
Richard Uhler66d874d2015-01-15 09:37:19 -0800926 }
Richard Uhler95e09672017-02-22 11:37:41 +0000927 return cached_image_info_.get();
Richard Uhler66d874d2015-01-15 09:37:19 -0800928}
929
Richard Uhler88bc6732016-11-14 14:38:03 +0000930OatFileAssistant::OatFileInfo& OatFileAssistant::GetBestInfo() {
Calin Juravle357c66d2017-05-04 01:57:17 +0000931 // TODO(calin): Document the side effects of class loading when
932 // running dalvikvm command line.
933 if (dex_parent_writable_) {
934 // If the parent of the dex file is writable it means that we can
935 // create the odex file. In this case we unconditionally pick the odex
936 // as the best oat file. This corresponds to the regular use case when
937 // apps gets installed or when they load private, secondary dex file.
938 // For apps on the system partition the odex location will not be
939 // writable and thus the oat location might be more up to date.
940 return odex_;
941 }
942
943 // We cannot write to the odex location. This must be a system app.
944
945 // If the oat location is usable take it.
946 if (oat_.IsUseable()) {
947 return oat_;
948 }
949
950 // The oat file is not usable but the odex file might be up to date.
951 // This is an indication that we are dealing with an up to date prebuilt
952 // (that doesn't need relocation).
953 if (odex_.Status() == kOatUpToDate) {
954 return odex_;
955 }
956
957 // The oat file is not usable and the odex file is not up to date.
958 // However we have access to the original dex file which means we can make
959 // the oat location up to date.
960 if (HasOriginalDexFiles()) {
961 return oat_;
962 }
963
964 // We got into the worst situation here:
965 // - the oat location is not usable
966 // - the prebuild odex location is not up to date
967 // - and we don't have the original dex file anymore (stripped).
968 // Pick the odex if it exists, or the oat if not.
969 return (odex_.Status() == kOatCannotOpen) ? oat_ : odex_;
Richard Uhler88bc6732016-11-14 14:38:03 +0000970}
971
Andreas Gampea463b6a2016-08-12 21:53:32 -0700972std::unique_ptr<gc::space::ImageSpace> OatFileAssistant::OpenImageSpace(const OatFile* oat_file) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800973 DCHECK(oat_file != nullptr);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100974 std::string art_file = ReplaceFileExtension(oat_file->GetLocation(), "art");
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800975 if (art_file.empty()) {
976 return nullptr;
977 }
978 std::string error_msg;
979 ScopedObjectAccess soa(Thread::Current());
Andreas Gampea463b6a2016-08-12 21:53:32 -0700980 std::unique_ptr<gc::space::ImageSpace> ret =
981 gc::space::ImageSpace::CreateFromAppImage(art_file.c_str(), oat_file, &error_msg);
Mathieu Chartiere778fc72016-01-25 20:11:28 -0800982 if (ret == nullptr && (VLOG_IS_ON(image) || OS::FileExists(art_file.c_str()))) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800983 LOG(INFO) << "Failed to open app image " << art_file.c_str() << " " << error_msg;
984 }
985 return ret;
986}
987
Richard Uhler88bc6732016-11-14 14:38:03 +0000988OatFileAssistant::OatFileInfo::OatFileInfo(OatFileAssistant* oat_file_assistant,
989 bool is_oat_location)
990 : oat_file_assistant_(oat_file_assistant), is_oat_location_(is_oat_location)
Richard Uhler743bf362016-04-19 15:39:37 -0700991{}
992
Richard Uhler88bc6732016-11-14 14:38:03 +0000993bool OatFileAssistant::OatFileInfo::IsOatLocation() {
994 return is_oat_location_;
995}
996
Richard Uhler743bf362016-04-19 15:39:37 -0700997const std::string* OatFileAssistant::OatFileInfo::Filename() {
998 return filename_provided_ ? &filename_ : nullptr;
999}
1000
Richard Uhler03bc6592016-11-22 09:42:04 +00001001bool OatFileAssistant::OatFileInfo::IsUseable() {
1002 switch (Status()) {
1003 case kOatCannotOpen:
1004 case kOatDexOutOfDate:
1005 case kOatBootImageOutOfDate: return false;
1006
1007 case kOatRelocationOutOfDate:
1008 case kOatUpToDate: return true;
1009 }
1010 UNREACHABLE();
Richard Uhler743bf362016-04-19 15:39:37 -07001011}
1012
1013OatFileAssistant::OatStatus OatFileAssistant::OatFileInfo::Status() {
1014 if (!status_attempted_) {
1015 status_attempted_ = true;
1016 const OatFile* file = GetFile();
1017 if (file == nullptr) {
Richard Uhler2f27abd2017-01-31 14:02:34 +00001018 // Check to see if there is a vdex file we can make use of.
1019 std::string error_msg;
Calin Juravle367b9d82017-05-15 18:18:39 -07001020 std::string vdex_filename = GetVdexFilename(filename_);
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001021 std::unique_ptr<VdexFile> vdex;
1022 if (vdex_fd_ == -1) {
1023 vdex = VdexFile::Open(vdex_filename,
1024 false /*writeable*/,
1025 false /*low_4gb*/,
1026 false /*unquicken*/,
1027 &error_msg);
1028 } else {
1029 struct stat s;
1030 int rc = TEMP_FAILURE_RETRY(fstat(vdex_fd_, &s));
1031 if (rc == -1) {
1032 PLOG(WARNING) << "Failed getting length of vdex file";
1033 } else {
1034 vdex = VdexFile::Open(vdex_fd_,
1035 s.st_size,
1036 vdex_filename,
1037 false /*writable*/,
1038 false /*low_4gb*/,
1039 false /* unquicken */,
1040 &error_msg);
1041 }
1042 }
Richard Uhler2f27abd2017-01-31 14:02:34 +00001043 if (vdex == nullptr) {
1044 status_ = kOatCannotOpen;
1045 VLOG(oat) << "unable to open vdex file " << vdex_filename << ": " << error_msg;
1046 } else {
1047 if (oat_file_assistant_->DexChecksumUpToDate(*vdex, &error_msg)) {
1048 // The vdex file does not contain enough information to determine
1049 // whether it is up to date with respect to the boot image, so we
1050 // assume it is out of date.
1051 VLOG(oat) << error_msg;
1052 status_ = kOatBootImageOutOfDate;
1053 } else {
1054 status_ = kOatDexOutOfDate;
1055 }
1056 }
Richard Uhler743bf362016-04-19 15:39:37 -07001057 } else {
1058 status_ = oat_file_assistant_->GivenOatFileStatus(*file);
Richard Uhler9a37efc2016-08-05 16:32:55 -07001059 VLOG(oat) << file->GetLocation() << " is " << status_
1060 << " with filter " << file->GetCompilerFilter();
Richard Uhler743bf362016-04-19 15:39:37 -07001061 }
1062 }
1063 return status_;
1064}
1065
Richard Uhler70a84262016-11-08 16:51:51 +00001066OatFileAssistant::DexOptNeeded OatFileAssistant::OatFileInfo::GetDexOptNeeded(
Calin Juravle44e5efa2017-09-12 00:54:26 -07001067 CompilerFilter::Filter target,
1068 bool profile_changed,
1069 bool downgrade,
1070 ClassLoaderContext* context) {
1071
Nicolas Geoffray49cda062017-04-21 13:08:25 +01001072 bool compilation_desired = CompilerFilter::IsAotCompilationEnabled(target);
Shubham Ajmerae4e812a2017-05-25 20:09:58 -07001073 bool filter_okay = CompilerFilterIsOkay(target, profile_changed, downgrade);
Calin Juravle44e5efa2017-09-12 00:54:26 -07001074 bool class_loader_context_okay = ClassLoaderContextIsOkay(context);
Richard Uhler70a84262016-11-08 16:51:51 +00001075
Calin Juravle44e5efa2017-09-12 00:54:26 -07001076 // Only check the filter and relocation if the class loader context is ok.
1077 // If it is not, we will return kDex2OatFromScratch as the compilation needs to be redone.
1078 if (class_loader_context_okay) {
1079 if (filter_okay && Status() == kOatUpToDate) {
1080 // The oat file is in good shape as is.
1081 return kNoDexOptNeeded;
1082 }
Richard Uhler70a84262016-11-08 16:51:51 +00001083
Calin Juravle44e5efa2017-09-12 00:54:26 -07001084 if (filter_okay && !compilation_desired && Status() == kOatRelocationOutOfDate) {
1085 // If no compilation is desired, then it doesn't matter if the oat
1086 // file needs relocation. It's in good shape as is.
1087 return kNoDexOptNeeded;
1088 }
Richard Uhler7225a8d2016-11-22 10:12:03 +00001089
Calin Juravle44e5efa2017-09-12 00:54:26 -07001090 if (filter_okay && Status() == kOatRelocationOutOfDate) {
1091 return kDex2OatForRelocation;
1092 }
Richard Uhler7225a8d2016-11-22 10:12:03 +00001093
Calin Juravle44e5efa2017-09-12 00:54:26 -07001094 if (IsUseable()) {
1095 return kDex2OatForFilter;
1096 }
Nicolas Geoffray08e9eed2017-04-25 17:36:51 +01001097
Calin Juravle44e5efa2017-09-12 00:54:26 -07001098 if (Status() == kOatBootImageOutOfDate) {
1099 return kDex2OatForBootImage;
1100 }
Nicolas Geoffray08e9eed2017-04-25 17:36:51 +01001101 }
1102
1103 if (oat_file_assistant_->HasOriginalDexFiles()) {
1104 return kDex2OatFromScratch;
1105 } else {
1106 // Otherwise there is nothing we can do, even if we want to.
1107 return kNoDexOptNeeded;
1108 }
Richard Uhler70a84262016-11-08 16:51:51 +00001109}
1110
Richard Uhler743bf362016-04-19 15:39:37 -07001111const OatFile* OatFileAssistant::OatFileInfo::GetFile() {
1112 CHECK(!file_released_) << "GetFile called after oat file released.";
1113 if (!load_attempted_) {
1114 load_attempted_ = true;
1115 if (filename_provided_) {
1116 std::string error_msg;
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001117 if (oat_fd_ != -1 && vdex_fd_ != -1) {
1118 file_.reset(OatFile::Open(vdex_fd_,
1119 oat_fd_,
1120 filename_.c_str(),
1121 nullptr,
1122 nullptr,
1123 oat_file_assistant_->load_executable_,
1124 false /* low_4gb */,
1125 oat_file_assistant_->dex_location_.c_str(),
1126 &error_msg));
1127 } else {
1128 file_.reset(OatFile::Open(filename_.c_str(),
1129 filename_.c_str(),
1130 nullptr,
1131 nullptr,
1132 oat_file_assistant_->load_executable_,
1133 false /* low_4gb */,
1134 oat_file_assistant_->dex_location_.c_str(),
1135 &error_msg));
1136 }
Richard Uhler743bf362016-04-19 15:39:37 -07001137 if (file_.get() == nullptr) {
1138 VLOG(oat) << "OatFileAssistant test for existing oat file "
1139 << filename_ << ": " << error_msg;
1140 }
1141 }
1142 }
1143 return file_.get();
1144}
1145
1146bool OatFileAssistant::OatFileInfo::CompilerFilterIsOkay(
Shubham Ajmerae4e812a2017-05-25 20:09:58 -07001147 CompilerFilter::Filter target, bool profile_changed, bool downgrade) {
Richard Uhler743bf362016-04-19 15:39:37 -07001148 const OatFile* file = GetFile();
1149 if (file == nullptr) {
1150 return false;
1151 }
1152
1153 CompilerFilter::Filter current = file->GetCompilerFilter();
1154 if (profile_changed && CompilerFilter::DependsOnProfile(current)) {
1155 VLOG(oat) << "Compiler filter not okay because Profile changed";
1156 return false;
1157 }
Shubham Ajmerae4e812a2017-05-25 20:09:58 -07001158 return downgrade ? !CompilerFilter::IsBetter(current, target) :
1159 CompilerFilter::IsAsGoodAs(current, target);
Richard Uhler743bf362016-04-19 15:39:37 -07001160}
1161
Calin Juravle44e5efa2017-09-12 00:54:26 -07001162bool OatFileAssistant::OatFileInfo::ClassLoaderContextIsOkay(ClassLoaderContext* context) {
1163 if (context == nullptr) {
1164 VLOG(oat) << "ClassLoaderContext check ignored: null context";
1165 return true;
1166 }
1167
1168 const OatFile* file = GetFile();
1169 if (file == nullptr) {
1170 return false;
1171 }
1172
1173 size_t dir_index = file->GetLocation().rfind('/');
1174 std::string classpath_dir = (dir_index != std::string::npos)
1175 ? file->GetLocation().substr(0, dir_index)
1176 : "";
1177
1178 if (!context->OpenDexFiles(oat_file_assistant_->isa_, classpath_dir)) {
1179 VLOG(oat) << "ClassLoaderContext check failed: dex files from the context could not be opened";
1180 return false;
1181 }
1182
1183 bool result = context->VerifyClassLoaderContextMatch(file->GetClassLoaderContext());
1184 if (!result) {
1185 VLOG(oat) << "ClassLoaderContext check failed. Context was "
1186 << file->GetClassLoaderContext()
1187 << ". The expected context is " << context->EncodeContextForOatFile(classpath_dir);
1188 }
1189 return result;
1190}
1191
Richard Uhler743bf362016-04-19 15:39:37 -07001192bool OatFileAssistant::OatFileInfo::IsExecutable() {
1193 const OatFile* file = GetFile();
1194 return (file != nullptr && file->IsExecutable());
1195}
1196
Richard Uhler743bf362016-04-19 15:39:37 -07001197void OatFileAssistant::OatFileInfo::Reset() {
1198 load_attempted_ = false;
1199 file_.reset();
1200 status_attempted_ = false;
1201}
1202
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001203void OatFileAssistant::OatFileInfo::Reset(const std::string& filename, int vdex_fd,
1204 int oat_fd) {
Richard Uhler743bf362016-04-19 15:39:37 -07001205 filename_provided_ = true;
1206 filename_ = filename;
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001207 vdex_fd_ = vdex_fd;
1208 oat_fd_ = oat_fd;
Richard Uhler743bf362016-04-19 15:39:37 -07001209 Reset();
1210}
1211
1212std::unique_ptr<OatFile> OatFileAssistant::OatFileInfo::ReleaseFile() {
1213 file_released_ = true;
1214 return std::move(file_);
1215}
1216
Richard Uhler70a84262016-11-08 16:51:51 +00001217std::unique_ptr<OatFile> OatFileAssistant::OatFileInfo::ReleaseFileForUse() {
Richard Uhler3e580bc2016-11-08 16:23:07 +00001218 if (Status() == kOatUpToDate) {
Richard Uhler70a84262016-11-08 16:51:51 +00001219 return ReleaseFile();
1220 }
1221
1222 VLOG(oat) << "Oat File Assistant: No relocated oat file found,"
1223 << " attempting to fall back to interpreting oat file instead.";
1224
Richard Uhler03bc6592016-11-22 09:42:04 +00001225 if (Status() == kOatRelocationOutOfDate && !IsExecutable()) {
Richard Uhler70a84262016-11-08 16:51:51 +00001226 return ReleaseFile();
1227 }
1228
Richard Uhler03bc6592016-11-22 09:42:04 +00001229 if (Status() == kOatRelocationOutOfDate) {
Richard Uhler70a84262016-11-08 16:51:51 +00001230 // We are loading an oat file for runtime use that needs relocation.
1231 // Reload the file non-executable to ensure that we interpret out of the
1232 // dex code in the oat file rather than trying to execute the unrelocated
1233 // compiled code.
1234 oat_file_assistant_->load_executable_ = false;
1235 Reset();
Richard Uhler03bc6592016-11-22 09:42:04 +00001236 if (IsUseable()) {
Richard Uhler70a84262016-11-08 16:51:51 +00001237 CHECK(!IsExecutable());
1238 return ReleaseFile();
1239 }
1240 }
1241 return std::unique_ptr<OatFile>();
1242}
Richard Uhler66d874d2015-01-15 09:37:19 -08001243} // namespace art