blob: 506723769d9c4314ef82c306dd4c39c996af0043 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 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 */
Brian Carlstrome24fa612011-09-29 00:53:55 -070016
17#include "oat_file.h"
18
Brian Carlstrom700c8d32012-11-05 10:42:02 -080019#include <dlfcn.h>
David Srbecky1baabf02015-06-16 17:12:34 +000020#ifndef __APPLE__
21#include <link.h> // for dl_iterate_phdr.
22#endif
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070023#include <unistd.h>
24
25#include <cstdlib>
26#include <cstring>
Richard Uhlere5fed032015-03-18 08:21:11 -070027#include <sstream>
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070028#include <type_traits>
Shubham Ajmerab22dea02017-10-04 18:36:41 -070029#include <sys/stat.h>
Richard Uhlere5fed032015-03-18 08:21:11 -070030
Andreas Gampefa8429b2015-04-07 18:34:42 -070031// dlopen_ext support from bionic.
Bilyan Borisovbb661c02016-04-04 16:27:32 +010032#ifdef ART_TARGET_ANDROID
Andreas Gampefa8429b2015-04-07 18:34:42 -070033#include "android/dlext.h"
34#endif
35
Andreas Gampe875b4f22018-11-19 12:59:15 -080036#include <android-base/logging.h>
Andreas Gampe46ee31b2016-12-14 10:11:49 -080037#include "android-base/stringprintf.h"
38
David Brazdil7126c5b2019-03-05 00:02:51 +000039#include "arch/instruction_set_features.h"
Andreas Gampec6ea7d02017-02-01 16:46:28 -080040#include "art_method.h"
Brian Carlstromba150c32013-08-27 17:31:03 -070041#include "base/bit_vector.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070042#include "base/enums.h"
David Sehr891a50e2017-10-27 17:01:07 -070043#include "base/file_utils.h"
Andreas Gampe170331f2017-12-07 18:41:03 -080044#include "base/logging.h" // For VLOG_IS_ON.
David Sehr79e26072018-04-06 17:58:50 -070045#include "base/mem_map.h"
David Sehrc431b9d2018-03-02 12:01:51 -080046#include "base/os.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080047#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080048#include "base/systrace.h"
Elliott Hughes76160052012-12-12 16:31:20 -080049#include "base/unix_file/fd_file.h"
David Sehrc431b9d2018-03-02 12:01:51 -080050#include "base/utils.h"
David Sehr013fd802018-01-11 22:55:24 -080051#include "dex/art_dex_file_loader.h"
Andreas Gampe3f1dcd32018-12-28 09:39:56 -080052#include "dex/dex_file.h"
David Sehr9e734c72018-01-04 17:56:19 -080053#include "dex/dex_file_loader.h"
Andreas Gampe3f1dcd32018-12-28 09:39:56 -080054#include "dex/dex_file_structs.h"
David Sehr9e734c72018-01-04 17:56:19 -080055#include "dex/dex_file_types.h"
56#include "dex/standard_dex_file.h"
David Sehr9c4a0152018-04-05 12:23:54 -070057#include "dex/type_lookup_table.h"
David Sehr0225f8e2018-01-31 08:52:24 +000058#include "dex/utf-inl.h"
David Srbecky50928112019-03-22 17:06:28 +000059#include "elf/elf_utils.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080060#include "elf_file.h"
Vladimir Markoaad75c62016-10-03 08:46:48 +000061#include "gc_root.h"
Vladimir Marko1cedb4a2019-02-06 14:13:28 +000062#include "gc/heap.h"
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +010063#include "gc/space/image_space.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080064#include "mirror/class.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070065#include "mirror/object-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070066#include "oat.h"
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +010067#include "oat_file-inl.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070068#include "oat_file_manager.h"
Vladimir Marko1cedb4a2019-02-06 14:13:28 +000069#include "runtime-inl.h"
Vladimir Marko97d7e1c2016-10-04 14:44:28 +010070#include "vdex_file.h"
David Brazdil7126c5b2019-03-05 00:02:51 +000071#include "verifier/verifier_deps.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070072
73namespace art {
74
Andreas Gampe46ee31b2016-12-14 10:11:49 -080075using android::base::StringPrintf;
76
Andreas Gampe049cff02015-12-01 23:27:12 -080077// Whether OatFile::Open will try dlopen. Fallback is our own ELF loader.
David Srbecky1baabf02015-06-16 17:12:34 +000078static constexpr bool kUseDlopen = true;
Andreas Gampefa8429b2015-04-07 18:34:42 -070079
Andreas Gampe049cff02015-12-01 23:27:12 -080080// Whether OatFile::Open will try dlopen on the host. On the host we're not linking against
Andreas Gampefa8429b2015-04-07 18:34:42 -070081// bionic, so cannot take advantage of the support for changed semantics (loading the same soname
82// multiple times). However, if/when we switch the above, we likely want to switch this, too,
83// to get test coverage of the code paths.
David Srbecky1baabf02015-06-16 17:12:34 +000084static constexpr bool kUseDlopenOnHost = true;
Andreas Gampefa8429b2015-04-07 18:34:42 -070085
86// For debugging, Open will print DlOpen error message if set to true.
87static constexpr bool kPrintDlOpenErrorMessage = false;
88
Andreas Gampe049cff02015-12-01 23:27:12 -080089// Note for OatFileBase and descendents:
90//
91// These are used in OatFile::Open to try all our loaders.
92//
93// The process is simple:
94//
95// 1) Allocate an instance through the standard constructor (location, executable)
96// 2) Load() to try to open the file.
97// 3) ComputeFields() to populate the OatFile fields like begin_, using FindDynamicSymbolAddress.
98// 4) PreSetup() for any steps that should be done before the final setup.
99// 5) Setup() to complete the procedure.
Richard Uhlere5fed032015-03-18 08:21:11 -0700100
Andreas Gampe049cff02015-12-01 23:27:12 -0800101class OatFileBase : public OatFile {
102 public:
103 virtual ~OatFileBase() {}
Richard Uhlere5fed032015-03-18 08:21:11 -0700104
Andreas Gampe049cff02015-12-01 23:27:12 -0800105 template <typename kOatFileBaseSubType>
Nicolas Geoffray30025092018-04-19 14:43:29 +0100106 static OatFileBase* OpenOatFile(int zip_fd,
107 const std::string& vdex_filename,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100108 const std::string& elf_filename,
Alex Light84d76052014-08-22 17:49:35 -0700109 const std::string& location,
Andreas Gampe049cff02015-12-01 23:27:12 -0800110 bool writable,
111 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800112 bool low_4gb,
Richard Uhlere5fed032015-03-18 08:21:11 -0700113 const char* abs_dex_location,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100114 /*inout*/MemMap* reservation, // Where to load if not null.
115 /*out*/std::string* error_msg);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800116
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700117 template <typename kOatFileBaseSubType>
Nicolas Geoffray30025092018-04-19 14:43:29 +0100118 static OatFileBase* OpenOatFile(int zip_fd,
119 int vdex_fd,
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700120 int oat_fd,
121 const std::string& vdex_filename,
122 const std::string& oat_filename,
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700123 bool writable,
124 bool executable,
125 bool low_4gb,
126 const char* abs_dex_location,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100127 /*inout*/MemMap* reservation, // Where to load if not null.
128 /*out*/std::string* error_msg);
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700129
Andreas Gampe049cff02015-12-01 23:27:12 -0800130 protected:
131 OatFileBase(const std::string& filename, bool executable) : OatFile(filename, executable) {}
Andreas Gampefa8429b2015-04-07 18:34:42 -0700132
Andreas Gampe049cff02015-12-01 23:27:12 -0800133 virtual const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
134 std::string* error_msg) const = 0;
135
Andreas Gampe4075f832016-05-18 13:09:54 -0700136 virtual void PreLoad() = 0;
137
David Brazdil7b49e6c2016-09-01 11:06:18 +0100138 bool LoadVdex(const std::string& vdex_filename,
139 bool writable,
140 bool low_4gb,
141 std::string* error_msg);
142
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700143 bool LoadVdex(int vdex_fd,
144 const std::string& vdex_filename,
145 bool writable,
146 bool low_4gb,
147 std::string* error_msg);
148
Andreas Gampe049cff02015-12-01 23:27:12 -0800149 virtual bool Load(const std::string& elf_filename,
Andreas Gampe049cff02015-12-01 23:27:12 -0800150 bool writable,
151 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800152 bool low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100153 /*inout*/MemMap* reservation, // Where to load if not null.
154 /*out*/std::string* error_msg) = 0;
Andreas Gampe049cff02015-12-01 23:27:12 -0800155
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700156 virtual bool Load(int oat_fd,
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700157 bool writable,
158 bool executable,
159 bool low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100160 /*inout*/MemMap* reservation, // Where to load if not null.
161 /*out*/std::string* error_msg) = 0;
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700162
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100163 bool ComputeFields(const std::string& file_path, std::string* error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -0800164
165 virtual void PreSetup(const std::string& elf_filename) = 0;
166
Nicolas Geoffray30025092018-04-19 14:43:29 +0100167 bool Setup(int zip_fd, const char* abs_dex_location, std::string* error_msg);
David Brazdil7126c5b2019-03-05 00:02:51 +0000168 bool Setup(const std::vector<const DexFile*>& dex_files);
Andreas Gampe049cff02015-12-01 23:27:12 -0800169
170 // Setters exposed for ElfOatFile.
171
172 void SetBegin(const uint8_t* begin) {
173 begin_ = begin;
Andreas Gampefa8429b2015-04-07 18:34:42 -0700174 }
175
Andreas Gampe049cff02015-12-01 23:27:12 -0800176 void SetEnd(const uint8_t* end) {
177 end_ = end;
178 }
179
David Brazdilc93b3be2016-09-12 18:49:58 +0100180 void SetVdex(VdexFile* vdex) {
181 vdex_.reset(vdex);
182 }
183
Andreas Gampe049cff02015-12-01 23:27:12 -0800184 private:
185 DISALLOW_COPY_AND_ASSIGN(OatFileBase);
186};
187
188template <typename kOatFileBaseSubType>
Nicolas Geoffray30025092018-04-19 14:43:29 +0100189OatFileBase* OatFileBase::OpenOatFile(int zip_fd,
190 const std::string& vdex_filename,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100191 const std::string& elf_filename,
Andreas Gampe049cff02015-12-01 23:27:12 -0800192 const std::string& location,
Andreas Gampe049cff02015-12-01 23:27:12 -0800193 bool writable,
194 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800195 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800196 const char* abs_dex_location,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100197 /*inout*/MemMap* reservation,
198 /*out*/std::string* error_msg) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800199 std::unique_ptr<OatFileBase> ret(new kOatFileBaseSubType(location, executable));
Andreas Gampe4075f832016-05-18 13:09:54 -0700200
201 ret->PreLoad();
202
Andreas Gampe049cff02015-12-01 23:27:12 -0800203 if (!ret->Load(elf_filename,
Andreas Gampe049cff02015-12-01 23:27:12 -0800204 writable,
205 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800206 low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100207 reservation,
Andreas Gampe049cff02015-12-01 23:27:12 -0800208 error_msg)) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800209 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800210 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800211
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100212 if (!ret->ComputeFields(elf_filename, error_msg)) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800213 return nullptr;
214 }
Andreas Gampe4075f832016-05-18 13:09:54 -0700215
David Sehr2300b2d2018-05-10 14:20:10 -0700216 ret->PreSetup(elf_filename);
217
David Srbeckyec2cdf42017-12-08 16:21:25 +0000218 if (!ret->LoadVdex(vdex_filename, writable, low_4gb, error_msg)) {
219 return nullptr;
220 }
221
Nicolas Geoffray30025092018-04-19 14:43:29 +0100222 if (!ret->Setup(zip_fd, abs_dex_location, error_msg)) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800223 return nullptr;
224 }
225
Dave Allison69dfe512014-07-11 17:11:58 +0000226 return ret.release();
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800227}
228
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700229template <typename kOatFileBaseSubType>
Nicolas Geoffray30025092018-04-19 14:43:29 +0100230OatFileBase* OatFileBase::OpenOatFile(int zip_fd,
231 int vdex_fd,
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700232 int oat_fd,
233 const std::string& vdex_location,
234 const std::string& oat_location,
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700235 bool writable,
236 bool executable,
237 bool low_4gb,
238 const char* abs_dex_location,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100239 /*inout*/MemMap* reservation,
240 /*out*/std::string* error_msg) {
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700241 std::unique_ptr<OatFileBase> ret(new kOatFileBaseSubType(oat_location, executable));
242
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700243 if (!ret->Load(oat_fd,
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700244 writable,
245 executable,
246 low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100247 reservation,
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700248 error_msg)) {
249 return nullptr;
250 }
251
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100252 if (!ret->ComputeFields(oat_location, error_msg)) {
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700253 return nullptr;
254 }
255
David Sehr2300b2d2018-05-10 14:20:10 -0700256 ret->PreSetup(oat_location);
257
David Srbeckyec2cdf42017-12-08 16:21:25 +0000258 if (!ret->LoadVdex(vdex_fd, vdex_location, writable, low_4gb, error_msg)) {
259 return nullptr;
260 }
261
Nicolas Geoffray30025092018-04-19 14:43:29 +0100262 if (!ret->Setup(zip_fd, abs_dex_location, error_msg)) {
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700263 return nullptr;
264 }
265
266 return ret.release();
267}
268
David Brazdil7b49e6c2016-09-01 11:06:18 +0100269bool OatFileBase::LoadVdex(const std::string& vdex_filename,
270 bool writable,
271 bool low_4gb,
272 std::string* error_msg) {
David Srbeckyec2cdf42017-12-08 16:21:25 +0000273 vdex_ = VdexFile::OpenAtAddress(vdex_begin_,
274 vdex_end_ - vdex_begin_,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100275 /*mmap_reuse=*/ vdex_begin_ != nullptr,
David Srbeckyec2cdf42017-12-08 16:21:25 +0000276 vdex_filename,
277 writable,
278 low_4gb,
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700279 /* unquicken=*/ false,
David Srbeckyec2cdf42017-12-08 16:21:25 +0000280 error_msg);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100281 if (vdex_.get() == nullptr) {
282 *error_msg = StringPrintf("Failed to load vdex file '%s' %s",
283 vdex_filename.c_str(),
284 error_msg->c_str());
285 return false;
286 }
287 return true;
288}
289
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700290bool OatFileBase::LoadVdex(int vdex_fd,
291 const std::string& vdex_filename,
292 bool writable,
293 bool low_4gb,
294 std::string* error_msg) {
295 if (vdex_fd != -1) {
296 struct stat s;
297 int rc = TEMP_FAILURE_RETRY(fstat(vdex_fd, &s));
298 if (rc == -1) {
299 PLOG(WARNING) << "Failed getting length of vdex file";
300 } else {
David Srbeckyec2cdf42017-12-08 16:21:25 +0000301 vdex_ = VdexFile::OpenAtAddress(vdex_begin_,
302 vdex_end_ - vdex_begin_,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100303 /*mmap_reuse=*/ vdex_begin_ != nullptr,
David Srbeckyec2cdf42017-12-08 16:21:25 +0000304 vdex_fd,
305 s.st_size,
306 vdex_filename,
307 writable,
308 low_4gb,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100309 /*unquicken=*/ false,
David Srbeckyec2cdf42017-12-08 16:21:25 +0000310 error_msg);
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700311 if (vdex_.get() == nullptr) {
312 *error_msg = "Failed opening vdex file.";
313 return false;
314 }
315 }
316 }
317 return true;
318}
319
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100320bool OatFileBase::ComputeFields(const std::string& file_path, std::string* error_msg) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800321 std::string symbol_error_msg;
322 begin_ = FindDynamicSymbolAddress("oatdata", &symbol_error_msg);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700323 if (begin_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800324 *error_msg = StringPrintf("Failed to find oatdata symbol in '%s' %s",
325 file_path.c_str(),
326 symbol_error_msg.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700327 return false;
328 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800329 end_ = FindDynamicSymbolAddress("oatlastword", &symbol_error_msg);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700330 if (end_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800331 *error_msg = StringPrintf("Failed to find oatlastword symbol in '%s' %s",
332 file_path.c_str(),
333 symbol_error_msg.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700334 return false;
335 }
336 // Readjust to be non-inclusive upper bound.
337 end_ += sizeof(uint32_t);
338
Vladimir Markob066d432018-01-03 13:14:37 +0000339 data_bimg_rel_ro_begin_ = FindDynamicSymbolAddress("oatdatabimgrelro", &symbol_error_msg);
340 if (data_bimg_rel_ro_begin_ != nullptr) {
341 data_bimg_rel_ro_end_ =
342 FindDynamicSymbolAddress("oatdatabimgrelrolastword", &symbol_error_msg);
343 if (data_bimg_rel_ro_end_ == nullptr) {
344 *error_msg =
345 StringPrintf("Failed to find oatdatabimgrelrolastword symbol in '%s'", file_path.c_str());
346 return false;
347 }
348 // Readjust to be non-inclusive upper bound.
349 data_bimg_rel_ro_end_ += sizeof(uint32_t);
350 }
351
Andreas Gampe049cff02015-12-01 23:27:12 -0800352 bss_begin_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbss", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700353 if (bss_begin_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800354 // No .bss section.
Andreas Gampefa8429b2015-04-07 18:34:42 -0700355 bss_end_ = nullptr;
Andreas Gampefa8429b2015-04-07 18:34:42 -0700356 } else {
Andreas Gampe049cff02015-12-01 23:27:12 -0800357 bss_end_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbsslastword", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700358 if (bss_end_ == nullptr) {
David Srbeckyec2cdf42017-12-08 16:21:25 +0000359 *error_msg = StringPrintf("Failed to find oatbsslastword symbol in '%s'", file_path.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700360 return false;
361 }
362 // Readjust to be non-inclusive upper bound.
363 bss_end_ += sizeof(uint32_t);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100364 // Find bss methods if present.
365 bss_methods_ =
366 const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbssmethods", &symbol_error_msg));
Vladimir Markoaad75c62016-10-03 08:46:48 +0000367 // Find bss roots if present.
368 bss_roots_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbssroots", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700369 }
370
David Srbeckyec2cdf42017-12-08 16:21:25 +0000371 vdex_begin_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatdex", &symbol_error_msg));
372 if (vdex_begin_ == nullptr) {
373 // No .vdex section.
374 vdex_end_ = nullptr;
375 } else {
376 vdex_end_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatdexlastword", &symbol_error_msg));
377 if (vdex_end_ == nullptr) {
378 *error_msg = StringPrintf("Failed to find oatdexlastword symbol in '%s'", file_path.c_str());
379 return false;
380 }
381 // Readjust to be non-inclusive upper bound.
382 vdex_end_ += sizeof(uint32_t);
383 }
384
Andreas Gampe049cff02015-12-01 23:27:12 -0800385 return true;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800386}
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800387
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100388// Read an unaligned entry from the OatDexFile data in OatFile and advance the read
389// position by the number of bytes read, i.e. sizeof(T).
390// Return true on success, false if the read would go beyond the end of the OatFile.
391template <typename T>
Vladimir Marko722fa982015-10-19 18:18:27 +0100392inline static bool ReadOatDexFileData(const OatFile& oat_file,
393 /*inout*/const uint8_t** oat,
394 /*out*/T* value) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100395 DCHECK(oat != nullptr);
396 DCHECK(value != nullptr);
397 DCHECK_LE(*oat, oat_file.End());
398 if (UNLIKELY(static_cast<size_t>(oat_file.End() - *oat) < sizeof(T))) {
399 return false;
400 }
401 static_assert(std::is_trivial<T>::value, "T must be a trivial type");
Andreas Gampec55bb392018-09-21 00:02:02 +0000402 using unaligned_type __attribute__((__aligned__(1))) = T;
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100403 *value = *reinterpret_cast<const unaligned_type*>(*oat);
404 *oat += sizeof(T);
405 return true;
406}
407
Vladimir Markof3c52b42017-11-17 17:32:12 +0000408static bool ReadIndexBssMapping(OatFile* oat_file,
409 /*inout*/const uint8_t** oat,
410 size_t dex_file_index,
411 const std::string& dex_file_location,
412 const char* tag,
413 /*out*/const IndexBssMapping** mapping,
414 std::string* error_msg) {
415 uint32_t index_bss_mapping_offset;
416 if (UNLIKELY(!ReadOatDexFileData(*oat_file, oat, &index_bss_mapping_offset))) {
417 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zd for '%s' truncated "
418 "after %s bss mapping offset",
419 oat_file->GetLocation().c_str(),
420 dex_file_index,
421 dex_file_location.c_str(),
422 tag);
423 return false;
424 }
425 const bool readable_index_bss_mapping_size =
426 index_bss_mapping_offset != 0u &&
427 index_bss_mapping_offset <= oat_file->Size() &&
428 IsAligned<alignof(IndexBssMapping)>(index_bss_mapping_offset) &&
429 oat_file->Size() - index_bss_mapping_offset >= IndexBssMapping::ComputeSize(0);
430 const IndexBssMapping* index_bss_mapping = readable_index_bss_mapping_size
431 ? reinterpret_cast<const IndexBssMapping*>(oat_file->Begin() + index_bss_mapping_offset)
432 : nullptr;
433 if (index_bss_mapping_offset != 0u &&
434 (UNLIKELY(index_bss_mapping == nullptr) ||
435 UNLIKELY(index_bss_mapping->size() == 0u) ||
436 UNLIKELY(oat_file->Size() - index_bss_mapping_offset <
437 IndexBssMapping::ComputeSize(index_bss_mapping->size())))) {
438 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with unaligned or "
439 " truncated %s bss mapping, offset %u of %zu, length %zu",
440 oat_file->GetLocation().c_str(),
441 dex_file_index,
442 dex_file_location.c_str(),
443 tag,
444 index_bss_mapping_offset,
445 oat_file->Size(),
446 index_bss_mapping != nullptr ? index_bss_mapping->size() : 0u);
447 return false;
448 }
449
450 *mapping = index_bss_mapping;
451 return true;
452}
453
David Brazdil7126c5b2019-03-05 00:02:51 +0000454bool OatFileBase::Setup(const std::vector<const DexFile*>& dex_files) {
455 for (const DexFile* dex_file : dex_files) {
456 std::string dex_location = dex_file->GetLocation();
457 std::string canonical_location = DexFileLoader::GetDexCanonicalLocation(dex_location.c_str());
458
459 // Create an OatDexFile and add it to the owning container.
460 OatDexFile* oat_dex_file = new OatDexFile(this, dex_file, dex_location, canonical_location);
461 oat_dex_files_storage_.push_back(oat_dex_file);
462
463 // Add the location and canonical location (if different) to the oat_dex_files_ table.
464 std::string_view key(oat_dex_file->GetDexFileLocation());
465 oat_dex_files_.Put(key, oat_dex_file);
466 if (canonical_location != dex_location) {
467 std::string_view canonical_key(oat_dex_file->GetCanonicalDexFileLocation());
468 oat_dex_files_.Put(canonical_key, oat_dex_file);
469 }
470 }
471
472 return true;
473}
474
Nicolas Geoffray30025092018-04-19 14:43:29 +0100475bool OatFileBase::Setup(int zip_fd, const char* abs_dex_location, std::string* error_msg) {
Brian Carlstromf1b30302013-03-28 10:35:32 -0700476 if (!GetOatHeader().IsValid()) {
Andreas Gampe2bcb3b22014-12-12 15:25:14 -0800477 std::string cause = GetOatHeader().GetValidationErrorMessage();
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100478 *error_msg = StringPrintf("Invalid oat header for '%s': %s",
479 GetLocation().c_str(),
Andreas Gampe2bcb3b22014-12-12 15:25:14 -0800480 cause.c_str());
Brian Carlstromf1b30302013-03-28 10:35:32 -0700481 return false;
482 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100483 PointerSize pointer_size = GetInstructionSetPointerSize(GetOatHeader().GetInstructionSet());
484 size_t key_value_store_size =
485 (Size() >= sizeof(OatHeader)) ? GetOatHeader().GetKeyValueStoreSize() : 0u;
486 if (Size() < sizeof(OatHeader) + key_value_store_size) {
487 *error_msg = StringPrintf("In oat file '%s' found truncated OatHeader, "
488 "size = %zu < %zu + %zu",
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100489 GetLocation().c_str(),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100490 Size(),
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100491 sizeof(OatHeader),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100492 key_value_store_size);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700493 return false;
494 }
495
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100496 size_t oat_dex_files_offset = GetOatHeader().GetOatDexFilesOffset();
497 if (oat_dex_files_offset < GetOatHeader().GetHeaderSize() || oat_dex_files_offset > Size()) {
498 *error_msg = StringPrintf("In oat file '%s' found invalid oat dex files offset: "
499 "%zu is not in [%zu, %zu]",
500 GetLocation().c_str(),
501 oat_dex_files_offset,
502 GetOatHeader().GetHeaderSize(),
503 Size());
504 return false;
505 }
506 const uint8_t* oat = Begin() + oat_dex_files_offset; // Jump to the OatDexFile records.
507
Vladimir Markob066d432018-01-03 13:14:37 +0000508 if (!IsAligned<sizeof(uint32_t)>(data_bimg_rel_ro_begin_) ||
509 !IsAligned<sizeof(uint32_t)>(data_bimg_rel_ro_end_) ||
510 data_bimg_rel_ro_begin_ > data_bimg_rel_ro_end_) {
511 *error_msg = StringPrintf("In oat file '%s' found unaligned or unordered databimgrelro "
512 "symbol(s): begin = %p, end = %p",
513 GetLocation().c_str(),
514 data_bimg_rel_ro_begin_,
515 data_bimg_rel_ro_end_);
516 return false;
517 }
518
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100519 DCHECK_GE(static_cast<size_t>(pointer_size), alignof(GcRoot<mirror::Object>));
520 if (!IsAligned<kPageSize>(bss_begin_) ||
521 !IsAlignedParam(bss_methods_, static_cast<size_t>(pointer_size)) ||
522 !IsAlignedParam(bss_roots_, static_cast<size_t>(pointer_size)) ||
Vladimir Markoaad75c62016-10-03 08:46:48 +0000523 !IsAligned<alignof(GcRoot<mirror::Object>)>(bss_end_)) {
524 *error_msg = StringPrintf("In oat file '%s' found unaligned bss symbol(s): "
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100525 "begin = %p, methods_ = %p, roots = %p, end = %p",
Vladimir Markoaad75c62016-10-03 08:46:48 +0000526 GetLocation().c_str(),
527 bss_begin_,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100528 bss_methods_,
Vladimir Markoaad75c62016-10-03 08:46:48 +0000529 bss_roots_,
530 bss_end_);
531 return false;
532 }
533
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100534 if ((bss_methods_ != nullptr && (bss_methods_ < bss_begin_ || bss_methods_ > bss_end_)) ||
535 (bss_roots_ != nullptr && (bss_roots_ < bss_begin_ || bss_roots_ > bss_end_)) ||
536 (bss_methods_ != nullptr && bss_roots_ != nullptr && bss_methods_ > bss_roots_)) {
537 *error_msg = StringPrintf("In oat file '%s' found bss symbol(s) outside .bss or unordered: "
Vladimir Marko0f3c7002017-09-07 14:15:56 +0100538 "begin = %p, methods = %p, roots = %p, end = %p",
Vladimir Markoaad75c62016-10-03 08:46:48 +0000539 GetLocation().c_str(),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000540 bss_begin_,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100541 bss_methods_,
542 bss_roots_,
Vladimir Markoaad75c62016-10-03 08:46:48 +0000543 bss_end_);
544 return false;
545 }
546
Vladimir Markoe47f60c2018-02-21 13:43:28 +0000547 if (bss_methods_ != nullptr && bss_methods_ != bss_begin_) {
548 *error_msg = StringPrintf("In oat file '%s' found unexpected .bss gap before 'oatbssmethods': "
549 "begin = %p, methods = %p",
550 GetLocation().c_str(),
551 bss_begin_,
552 bss_methods_);
553 return false;
554 }
555
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100556 uint32_t dex_file_count = GetOatHeader().GetDexFileCount();
557 oat_dex_files_storage_.reserve(dex_file_count);
558 for (size_t i = 0; i < dex_file_count; i++) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100559 uint32_t dex_file_location_size;
560 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_location_size))) {
561 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu truncated after dex file "
562 "location size",
563 GetLocation().c_str(),
564 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700565 return false;
566 }
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100567 if (UNLIKELY(dex_file_location_size == 0U)) {
568 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu with empty location name",
569 GetLocation().c_str(),
570 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700571 return false;
572 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000573 if (UNLIKELY(static_cast<size_t>(End() - oat) < dex_file_location_size)) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100574 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu with truncated dex file "
575 "location",
576 GetLocation().c_str(),
577 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700578 return false;
579 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000580 const char* dex_file_location_data = reinterpret_cast<const char*>(oat);
581 oat += dex_file_location_size;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700582
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +0000583 // Location encoded in the oat file. We will use this for multidex naming,
584 // see ResolveRelativeEncodedDexLocation.
585 std::string oat_dex_file_location(dex_file_location_data, dex_file_location_size);
David Brazdil3e8aae02019-03-26 18:48:02 +0000586 // If `oat_dex_file_location` is relative (so that the oat file can be moved to
587 // a different folder), resolve to absolute location. Also resolve the file name
588 // in case dex files need to be opened from disk. The file name and location
589 // differ when cross-compiling on host for target.
590 std::string dex_file_name;
591 std::string dex_file_location;
592 ResolveRelativeEncodedDexLocation(abs_dex_location,
593 oat_dex_file_location,
594 &dex_file_location,
595 &dex_file_name);
Brian Carlstrome24fa612011-09-29 00:53:55 -0700596
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100597 uint32_t dex_file_checksum;
598 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_checksum))) {
599 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated after "
600 "dex file checksum",
601 GetLocation().c_str(),
602 i,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700603 dex_file_location.c_str());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700604 return false;
605 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700606
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100607 uint32_t dex_file_offset;
608 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_offset))) {
609 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated "
610 "after dex file offsets",
611 GetLocation().c_str(),
612 i,
613 dex_file_location.c_str());
614 return false;
615 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100616 if (UNLIKELY(dex_file_offset > DexSize())) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100617 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
618 "offset %u > %zu",
619 GetLocation().c_str(),
620 i,
621 dex_file_location.c_str(),
622 dex_file_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100623 DexSize());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700624 return false;
625 }
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000626 const uint8_t* dex_file_pointer = nullptr;
627 if (UNLIKELY(dex_file_offset == 0U)) {
628 if (uncompressed_dex_files_ == nullptr) {
Andreas Gampefc604a72018-02-08 15:43:37 -0800629 // Do not support mixed-mode oat files.
630 if (i > 0) {
631 *error_msg = StringPrintf("In oat file '%s', unsupported uncompressed-dex-file for dex "
632 "file %zu (%s)",
633 GetLocation().c_str(),
634 i,
635 dex_file_location.c_str());
636 return false;
637 }
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000638 uncompressed_dex_files_.reset(new std::vector<std::unique_ptr<const DexFile>>());
639 // No dex files, load it from location.
640 const ArtDexFileLoader dex_file_loader;
Nicolas Geoffray30025092018-04-19 14:43:29 +0100641 bool loaded = false;
642 if (zip_fd != -1) {
643 loaded = dex_file_loader.OpenZip(zip_fd,
644 dex_file_location,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100645 /*verify=*/ false,
646 /*verify_checksum=*/ false,
Nicolas Geoffray30025092018-04-19 14:43:29 +0100647 error_msg,
648 uncompressed_dex_files_.get());
649 } else {
David Brazdil3e8aae02019-03-26 18:48:02 +0000650 loaded = dex_file_loader.Open(dex_file_name.c_str(),
Nicolas Geoffray30025092018-04-19 14:43:29 +0100651 dex_file_location,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100652 /*verify=*/ false,
653 /*verify_checksum=*/ false,
Nicolas Geoffray30025092018-04-19 14:43:29 +0100654 error_msg,
655 uncompressed_dex_files_.get());
656 }
657 if (!loaded) {
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000658 if (Runtime::Current() == nullptr) {
659 // If there's no runtime, we're running oatdump, so return
660 // a half constructed oat file that oatdump knows how to deal with.
661 LOG(WARNING) << "Could not find associated dex files of oat file. "
662 << "Oatdump will only dump the header.";
663 return true;
664 } else {
665 return false;
666 }
667 }
Andreas Gampefc604a72018-02-08 15:43:37 -0800668 // The oat file may be out of date wrt/ the dex-file location. We need to be defensive
669 // here and ensure that at least the number of dex files still matches.
670 // Note: actual checksum comparisons are the duty of the OatFileAssistant and will be
671 // done after loading the OatFile.
672 if (uncompressed_dex_files_->size() != dex_file_count) {
673 *error_msg = StringPrintf("In oat file '%s', expected %u uncompressed dex files, but "
674 "found %zu in '%s'",
675 GetLocation().c_str(),
676 dex_file_count,
677 uncompressed_dex_files_->size(),
678 dex_file_location.c_str());
679 return false;
680 }
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000681 }
Vladimir Marko35d5b8a2018-07-03 09:18:32 +0100682 dex_file_pointer = (*uncompressed_dex_files_)[i]->Begin();
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000683 } else {
Andreas Gampefc604a72018-02-08 15:43:37 -0800684 // Do not support mixed-mode oat files.
685 if (uncompressed_dex_files_ != nullptr) {
686 *error_msg = StringPrintf("In oat file '%s', unsupported embedded dex-file for dex file "
687 "%zu (%s)",
688 GetLocation().c_str(),
689 i,
690 dex_file_location.c_str());
691 return false;
692 }
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000693 if (UNLIKELY(DexSize() - dex_file_offset < sizeof(DexFile::Header))) {
694 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
695 "offset %u of %zu but the size of dex file header is %zu",
696 GetLocation().c_str(),
697 i,
698 dex_file_location.c_str(),
699 dex_file_offset,
700 DexSize(),
701 sizeof(DexFile::Header));
702 return false;
703 }
704 dex_file_pointer = DexBegin() + dex_file_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000705 }
Brian Carlstrom89521892011-12-07 22:05:07 -0800706
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700707 const bool valid_magic = DexFileLoader::IsMagicValid(dex_file_pointer);
Mathieu Chartier7b074bf2017-09-25 16:22:36 -0700708 if (UNLIKELY(!valid_magic)) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100709 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with invalid "
710 "dex file magic '%s'",
711 GetLocation().c_str(),
712 i,
713 dex_file_location.c_str(),
714 dex_file_pointer);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700715 return false;
716 }
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700717 if (UNLIKELY(!DexFileLoader::IsVersionAndMagicValid(dex_file_pointer))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100718 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with invalid "
719 "dex file version '%s'",
720 GetLocation().c_str(),
721 i,
722 dex_file_location.c_str(),
723 dex_file_pointer);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700724 return false;
725 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800726 const DexFile::Header* header = reinterpret_cast<const DexFile::Header*>(dex_file_pointer);
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000727 if (dex_file_offset != 0 && (DexSize() - dex_file_offset < header->file_size_)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000728 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
729 "offset %u and size %u truncated at %zu",
730 GetLocation().c_str(),
731 i,
732 dex_file_location.c_str(),
733 dex_file_offset,
734 header->file_size_,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100735 DexSize());
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000736 return false;
737 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300738
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000739 uint32_t class_offsets_offset;
740 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &class_offsets_offset))) {
741 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated "
742 "after class offsets offset",
743 GetLocation().c_str(),
744 i,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300745 dex_file_location.c_str());
746 return false;
747 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000748 if (UNLIKELY(class_offsets_offset > Size()) ||
749 UNLIKELY((Size() - class_offsets_offset) / sizeof(uint32_t) < header->class_defs_size_)) {
750 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with truncated "
751 "class offsets, offset %u of %zu, class defs %u",
752 GetLocation().c_str(),
753 i,
754 dex_file_location.c_str(),
755 class_offsets_offset,
756 Size(),
757 header->class_defs_size_);
758 return false;
759 }
760 if (UNLIKELY(!IsAligned<alignof(uint32_t)>(class_offsets_offset))) {
761 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with unaligned "
762 "class offsets, offset %u",
763 GetLocation().c_str(),
764 i,
765 dex_file_location.c_str(),
766 class_offsets_offset);
767 return false;
768 }
769 const uint32_t* class_offsets_pointer =
770 reinterpret_cast<const uint32_t*>(Begin() + class_offsets_offset);
771
772 uint32_t lookup_table_offset;
773 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &lookup_table_offset))) {
774 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zd for '%s' truncated "
775 "after lookup table offset",
776 GetLocation().c_str(),
777 i,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300778 dex_file_location.c_str());
779 return false;
780 }
781 const uint8_t* lookup_table_data = lookup_table_offset != 0u
782 ? Begin() + lookup_table_offset
783 : nullptr;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000784 if (lookup_table_offset != 0u &&
785 (UNLIKELY(lookup_table_offset > Size()) ||
786 UNLIKELY(Size() - lookup_table_offset <
787 TypeLookupTable::RawDataLength(header->class_defs_size_)))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100788 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with truncated "
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000789 "type lookup table, offset %u of %zu, class defs %u",
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100790 GetLocation().c_str(),
791 i,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000792 dex_file_location.c_str(),
793 lookup_table_offset,
794 Size(),
795 header->class_defs_size_);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700796 return false;
797 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700798
Mathieu Chartier120aa282017-08-05 16:03:03 -0700799 uint32_t dex_layout_sections_offset;
800 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_layout_sections_offset))) {
801 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zd for '%s' truncated "
802 "after dex layout sections offset",
803 GetLocation().c_str(),
804 i,
805 dex_file_location.c_str());
806 return false;
807 }
808 const DexLayoutSections* const dex_layout_sections = dex_layout_sections_offset != 0
809 ? reinterpret_cast<const DexLayoutSections*>(Begin() + dex_layout_sections_offset)
810 : nullptr;
811
Vladimir Markof3c52b42017-11-17 17:32:12 +0000812 const IndexBssMapping* method_bss_mapping;
813 const IndexBssMapping* type_bss_mapping;
814 const IndexBssMapping* string_bss_mapping;
815 if (!ReadIndexBssMapping(
816 this, &oat, i, dex_file_location, "method", &method_bss_mapping, error_msg) ||
817 !ReadIndexBssMapping(
818 this, &oat, i, dex_file_location, "type", &type_bss_mapping, error_msg) ||
819 !ReadIndexBssMapping(
820 this, &oat, i, dex_file_location, "string", &string_bss_mapping, error_msg)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100821 return false;
822 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100823
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100824 // Create the OatDexFile and add it to the owning container.
David Brazdil3e8aae02019-03-26 18:48:02 +0000825 OatDexFile* oat_dex_file = new OatDexFile(
826 this,
827 dex_file_location,
828 DexFileLoader::GetDexCanonicalLocation(dex_file_name.c_str()),
829 dex_file_checksum,
830 dex_file_pointer,
831 lookup_table_data,
832 method_bss_mapping,
833 type_bss_mapping,
834 string_bss_mapping,
835 class_offsets_pointer,
836 dex_layout_sections);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100837 oat_dex_files_storage_.push_back(oat_dex_file);
838
839 // Add the location and canonical location (if different) to the oat_dex_files_ table.
Nicolas Geoffraye3e0f702019-03-12 07:02:02 +0000840 // Note: we use the dex_file_location_data storage for the view, as oat_dex_file_location
841 // is just a temporary string.
842 std::string_view key(dex_file_location_data, dex_file_location_size);
David Brazdil3e8aae02019-03-26 18:48:02 +0000843 std::string_view canonical_key(oat_dex_file->GetCanonicalDexFileLocation());
Vladimir Marko539690a2014-06-05 18:36:42 +0100844 oat_dex_files_.Put(key, oat_dex_file);
David Brazdil3e8aae02019-03-26 18:48:02 +0000845 if (canonical_key != key) {
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100846 oat_dex_files_.Put(canonical_key, oat_dex_file);
847 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700848 }
Vladimir Marko09d09432015-09-08 13:47:48 +0100849
Vladimir Markob066d432018-01-03 13:14:37 +0000850 if (DataBimgRelRoBegin() != nullptr) {
Vladimir Markoe80ecf32019-08-01 15:20:58 +0100851 // Make .data.bimg.rel.ro read only. ClassLinker shall temporarily make it writable for
852 // relocation when we register a dex file from this oat file. We do not do the relocation
853 // here to avoid dirtying the pages if the code is never actually ready to be executed.
Vladimir Markob066d432018-01-03 13:14:37 +0000854 uint8_t* reloc_begin = const_cast<uint8_t*>(DataBimgRelRoBegin());
855 CheckedCall(mprotect, "protect relocations", reloc_begin, DataBimgRelRoSize(), PROT_READ);
Vladimir Markoe80ecf32019-08-01 15:20:58 +0100856 // Make sure the file lists a boot image dependency, otherwise the .data.bimg.rel.ro
857 // section is bogus. The full dependency is checked before the code is executed.
858 const char* boot_class_path_checksum =
859 GetOatHeader().GetStoreValueByKey(OatHeader::kBootClassPathChecksumsKey);
860 if (boot_class_path_checksum == nullptr ||
861 boot_class_path_checksum[0] != gc::space::ImageSpace::kImageChecksumPrefix) {
862 *error_msg = StringPrintf("Oat file '%s' contains .data.bimg.rel.ro section "
863 "without boot image dependency.",
Vladimir Markob066d432018-01-03 13:14:37 +0000864 GetLocation().c_str());
865 return false;
Vladimir Markob066d432018-01-03 13:14:37 +0000866 }
867 }
868
Brian Carlstromf1b30302013-03-28 10:35:32 -0700869 return true;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700870}
871
Andreas Gampe049cff02015-12-01 23:27:12 -0800872////////////////////////
873// OatFile via dlopen //
874////////////////////////
875
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100876class DlOpenOatFile final : public OatFileBase {
Andreas Gampe049cff02015-12-01 23:27:12 -0800877 public:
878 DlOpenOatFile(const std::string& filename, bool executable)
879 : OatFileBase(filename, executable),
880 dlopen_handle_(nullptr),
Richard Uhlera206c742016-05-24 15:04:22 -0700881 shared_objects_before_(0) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800882 }
883
884 ~DlOpenOatFile() {
885 if (dlopen_handle_ != nullptr) {
Richard Uhlera206c742016-05-24 15:04:22 -0700886 if (!kIsTargetBuild) {
887 MutexLock mu(Thread::Current(), *Locks::host_dlopen_handles_lock_);
888 host_dlopen_handles_.erase(dlopen_handle_);
Mathieu Chartierc7d3f4b2016-06-01 10:48:19 -0700889 dlclose(dlopen_handle_);
890 } else {
891 dlclose(dlopen_handle_);
Richard Uhlera206c742016-05-24 15:04:22 -0700892 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800893 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800894 }
895
896 protected:
897 const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100898 std::string* error_msg) const override {
Andreas Gampe049cff02015-12-01 23:27:12 -0800899 const uint8_t* ptr =
900 reinterpret_cast<const uint8_t*>(dlsym(dlopen_handle_, symbol_name.c_str()));
901 if (ptr == nullptr) {
902 *error_msg = dlerror();
903 }
904 return ptr;
905 }
906
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100907 void PreLoad() override;
Andreas Gampe4075f832016-05-18 13:09:54 -0700908
Andreas Gampe049cff02015-12-01 23:27:12 -0800909 bool Load(const std::string& elf_filename,
Andreas Gampe049cff02015-12-01 23:27:12 -0800910 bool writable,
911 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800912 bool low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100913 /*inout*/MemMap* reservation, // Where to load if not null.
914 /*out*/std::string* error_msg) override;
Andreas Gampe049cff02015-12-01 23:27:12 -0800915
Vladimir Markoc09cd052018-08-23 16:36:36 +0100916 bool Load(int oat_fd ATTRIBUTE_UNUSED,
917 bool writable ATTRIBUTE_UNUSED,
918 bool executable ATTRIBUTE_UNUSED,
919 bool low_4gb ATTRIBUTE_UNUSED,
920 /*inout*/MemMap* reservation ATTRIBUTE_UNUSED,
921 /*out*/std::string* error_msg ATTRIBUTE_UNUSED) override {
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700922 return false;
923 }
924
Andreas Gampe049cff02015-12-01 23:27:12 -0800925 // Ask the linker where it mmaped the file and notify our mmap wrapper of the regions.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100926 void PreSetup(const std::string& elf_filename) override;
Andreas Gampe049cff02015-12-01 23:27:12 -0800927
928 private:
929 bool Dlopen(const std::string& elf_filename,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100930 /*inout*/MemMap* reservation, // Where to load if not null.
931 /*out*/std::string* error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -0800932
Richard Uhlera206c742016-05-24 15:04:22 -0700933 // On the host, if the same library is loaded again with dlopen the same
934 // file handle is returned. This differs from the behavior of dlopen on the
935 // target, where dlopen reloads the library at a different address every
936 // time you load it. The runtime relies on the target behavior to ensure
937 // each instance of the loaded library has a unique dex cache. To avoid
938 // problems, we fall back to our own linker in the case when the same
939 // library is opened multiple times on host. dlopen_handles_ is used to
940 // detect that case.
941 // Guarded by host_dlopen_handles_lock_;
942 static std::unordered_set<void*> host_dlopen_handles_;
943
Vladimir Markoc09cd052018-08-23 16:36:36 +0100944 // Reservation and dummy memory map objects corresponding to the regions mapped by dlopen.
945 // Note: Must be destroyed after dlclose() as it can hold the owning reservation.
946 std::vector<MemMap> dlopen_mmaps_;
947
Andreas Gampe049cff02015-12-01 23:27:12 -0800948 // dlopen handle during runtime.
949 void* dlopen_handle_; // TODO: Unique_ptr with custom deleter.
950
Andreas Gampe4075f832016-05-18 13:09:54 -0700951 // The number of shared objects the linker told us about before loading. Used to
952 // (optimistically) optimize the PreSetup stage (see comment there).
953 size_t shared_objects_before_;
954
Andreas Gampe049cff02015-12-01 23:27:12 -0800955 DISALLOW_COPY_AND_ASSIGN(DlOpenOatFile);
956};
957
Richard Uhlera206c742016-05-24 15:04:22 -0700958std::unordered_set<void*> DlOpenOatFile::host_dlopen_handles_;
959
Andreas Gampe4075f832016-05-18 13:09:54 -0700960void DlOpenOatFile::PreLoad() {
961#ifdef __APPLE__
Andreas Gampe39004a62016-05-18 21:27:00 -0700962 UNUSED(shared_objects_before_);
Andreas Gampe4075f832016-05-18 13:09:54 -0700963 LOG(FATAL) << "Should not reach here.";
964 UNREACHABLE();
965#else
966 // Count the entries in dl_iterate_phdr we get at this point in time.
967 struct dl_iterate_context {
Vladimir Markoc09cd052018-08-23 16:36:36 +0100968 static int callback(dl_phdr_info* info ATTRIBUTE_UNUSED,
Andreas Gampe4075f832016-05-18 13:09:54 -0700969 size_t size ATTRIBUTE_UNUSED,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100970 void* data) {
Andreas Gampe4075f832016-05-18 13:09:54 -0700971 reinterpret_cast<dl_iterate_context*>(data)->count++;
972 return 0; // Continue iteration.
973 }
974 size_t count = 0;
975 } context;
976
977 dl_iterate_phdr(dl_iterate_context::callback, &context);
978 shared_objects_before_ = context.count;
979#endif
980}
981
Andreas Gampe049cff02015-12-01 23:27:12 -0800982bool DlOpenOatFile::Load(const std::string& elf_filename,
Andreas Gampe049cff02015-12-01 23:27:12 -0800983 bool writable,
984 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800985 bool low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100986 /*inout*/MemMap* reservation, // Where to load if not null.
987 /*out*/std::string* error_msg) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800988 // Use dlopen only when flagged to do so, and when it's OK to load things executable.
989 // TODO: Also try when not executable? The issue here could be re-mapping as writable (as
990 // !executable is a sign that we may want to patch), which may not be allowed for
991 // various reasons.
992 if (!kUseDlopen) {
993 *error_msg = "DlOpen is disabled.";
994 return false;
995 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800996 if (low_4gb) {
997 *error_msg = "DlOpen does not support low 4gb loading.";
998 return false;
999 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001000 if (writable) {
1001 *error_msg = "DlOpen does not support writable loading.";
1002 return false;
1003 }
1004 if (!executable) {
1005 *error_msg = "DlOpen does not support non-executable loading.";
1006 return false;
1007 }
1008
1009 // dlopen always returns the same library if it is already opened on the host. For this reason
1010 // we only use dlopen if we are the target or we do not already have the dex file opened. Having
1011 // the same library loaded multiple times at different addresses is required for class unloading
1012 // and for having dex caches arrays in the .bss section.
1013 if (!kIsTargetBuild) {
1014 if (!kUseDlopenOnHost) {
1015 *error_msg = "DlOpen disabled for host.";
1016 return false;
1017 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001018 }
1019
Vladimir Markoc09cd052018-08-23 16:36:36 +01001020 bool success = Dlopen(elf_filename, reservation, error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -08001021 DCHECK(dlopen_handle_ != nullptr || !success);
1022
1023 return success;
1024}
1025
1026bool DlOpenOatFile::Dlopen(const std::string& elf_filename,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001027 /*inout*/MemMap* reservation,
1028 /*out*/std::string* error_msg) {
Andreas Gampe049cff02015-12-01 23:27:12 -08001029#ifdef __APPLE__
1030 // The dl_iterate_phdr syscall is missing. There is similar API on OSX,
1031 // but let's fallback to the custom loading code for the time being.
Vladimir Marko3ec8fb62018-08-31 17:47:38 +01001032 UNUSED(elf_filename, reservation);
Andreas Gampe049cff02015-12-01 23:27:12 -08001033 *error_msg = "Dlopen unsupported on Mac.";
1034 return false;
1035#else
1036 {
1037 UniqueCPtr<char> absolute_path(realpath(elf_filename.c_str(), nullptr));
1038 if (absolute_path == nullptr) {
1039 *error_msg = StringPrintf("Failed to find absolute path for '%s'", elf_filename.c_str());
1040 return false;
1041 }
Bilyan Borisovbb661c02016-04-04 16:27:32 +01001042#ifdef ART_TARGET_ANDROID
Anton Kirilov3a2e78e2017-01-06 13:33:42 +00001043 android_dlextinfo extinfo = {};
Vladimir Markof6cfd002018-11-01 16:53:31 +00001044 extinfo.flags = ANDROID_DLEXT_FORCE_LOAD; // Force-load, don't reuse handle
1045 // (open oat files multiple times).
Vladimir Markoc09cd052018-08-23 16:36:36 +01001046 if (reservation != nullptr) {
1047 if (!reservation->IsValid()) {
1048 *error_msg = StringPrintf("Invalid reservation for %s", elf_filename.c_str());
1049 return false;
1050 }
1051 extinfo.flags |= ANDROID_DLEXT_RESERVED_ADDRESS; // Use the reserved memory range.
1052 extinfo.reserved_addr = reservation->Begin();
1053 extinfo.reserved_size = reservation->Size();
1054 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001055 dlopen_handle_ = android_dlopen_ext(absolute_path.get(), RTLD_NOW, &extinfo);
Vladimir Markoc09cd052018-08-23 16:36:36 +01001056 if (reservation != nullptr && dlopen_handle_ != nullptr) {
1057 // Find used pages from the reservation.
1058 struct dl_iterate_context {
1059 static int callback(dl_phdr_info* info, size_t size ATTRIBUTE_UNUSED, void* data) {
1060 auto* context = reinterpret_cast<dl_iterate_context*>(data);
1061 static_assert(std::is_same<Elf32_Half, Elf64_Half>::value, "Half must match");
1062 using Elf_Half = Elf64_Half;
1063
1064 // See whether this callback corresponds to the file which we have just loaded.
1065 uint8_t* reservation_begin = context->reservation->Begin();
1066 bool contained_in_reservation = false;
1067 for (Elf_Half i = 0; i < info->dlpi_phnum; i++) {
1068 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
1069 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
1070 info->dlpi_phdr[i].p_vaddr);
1071 size_t memsz = info->dlpi_phdr[i].p_memsz;
1072 size_t offset = static_cast<size_t>(vaddr - reservation_begin);
1073 if (offset < context->reservation->Size()) {
1074 contained_in_reservation = true;
1075 DCHECK_LE(memsz, context->reservation->Size() - offset);
1076 } else if (vaddr < reservation_begin) {
1077 // Check that there's no overlap with the reservation.
1078 DCHECK_LE(memsz, static_cast<size_t>(reservation_begin - vaddr));
1079 }
1080 break; // It is sufficient to check the first PT_LOAD header.
1081 }
1082 }
1083
1084 if (contained_in_reservation) {
1085 for (Elf_Half i = 0; i < info->dlpi_phnum; i++) {
1086 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
1087 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
1088 info->dlpi_phdr[i].p_vaddr);
1089 size_t memsz = info->dlpi_phdr[i].p_memsz;
1090 size_t offset = static_cast<size_t>(vaddr - reservation_begin);
1091 DCHECK_LT(offset, context->reservation->Size());
1092 DCHECK_LE(memsz, context->reservation->Size() - offset);
1093 context->max_size = std::max(context->max_size, offset + memsz);
1094 }
1095 }
1096
1097 return 1; // Stop iteration and return 1 from dl_iterate_phdr.
1098 }
1099 return 0; // Continue iteration and return 0 from dl_iterate_phdr when finished.
1100 }
1101
1102 const MemMap* const reservation;
1103 size_t max_size = 0u;
1104 };
1105 dl_iterate_context context = { reservation };
1106
1107 if (dl_iterate_phdr(dl_iterate_context::callback, &context) == 0) {
1108 LOG(FATAL) << "Could not find the shared object mmapped to the reservation.";
1109 UNREACHABLE();
1110 }
1111
1112 // Take ownership of the memory used by the shared object. dlopen() does not assume
1113 // full ownership of this memory and dlclose() shall just remap it as zero pages with
1114 // PROT_NONE. We need to unmap the memory when destroying this oat file.
1115 dlopen_mmaps_.push_back(reservation->TakeReservedMemory(context.max_size));
1116 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001117#else
Steve Austin882ed6b2018-06-08 11:40:38 -07001118 static_assert(!kIsTargetBuild || kIsTargetLinux || kIsTargetFuchsia,
1119 "host_dlopen_handles_ will leak handles");
Vladimir Markoc09cd052018-08-23 16:36:36 +01001120 if (reservation != nullptr) {
1121 *error_msg = StringPrintf("dlopen() into reserved memory is unsupported on host for '%s'.",
1122 elf_filename.c_str());
1123 return false;
1124 }
Mathieu Chartierc7d3f4b2016-06-01 10:48:19 -07001125 MutexLock mu(Thread::Current(), *Locks::host_dlopen_handles_lock_);
Richard Uhlera206c742016-05-24 15:04:22 -07001126 dlopen_handle_ = dlopen(absolute_path.get(), RTLD_NOW);
1127 if (dlopen_handle_ != nullptr) {
Richard Uhlera206c742016-05-24 15:04:22 -07001128 if (!host_dlopen_handles_.insert(dlopen_handle_).second) {
1129 dlclose(dlopen_handle_);
1130 dlopen_handle_ = nullptr;
1131 *error_msg = StringPrintf("host dlopen re-opened '%s'", elf_filename.c_str());
1132 return false;
1133 }
1134 }
Bilyan Borisovbb661c02016-04-04 16:27:32 +01001135#endif // ART_TARGET_ANDROID
Andreas Gampe049cff02015-12-01 23:27:12 -08001136 }
1137 if (dlopen_handle_ == nullptr) {
1138 *error_msg = StringPrintf("Failed to dlopen '%s': %s", elf_filename.c_str(), dlerror());
1139 return false;
1140 }
1141 return true;
1142#endif
1143}
1144
1145void DlOpenOatFile::PreSetup(const std::string& elf_filename) {
Andreas Gampe74f07b52015-12-02 11:53:26 -08001146#ifdef __APPLE__
1147 UNUSED(elf_filename);
1148 LOG(FATAL) << "Should not reach here.";
1149 UNREACHABLE();
1150#else
Andreas Gampe049cff02015-12-01 23:27:12 -08001151 struct dl_iterate_context {
Vladimir Markoc09cd052018-08-23 16:36:36 +01001152 static int callback(dl_phdr_info* info, size_t size ATTRIBUTE_UNUSED, void* data) {
Andreas Gampe049cff02015-12-01 23:27:12 -08001153 auto* context = reinterpret_cast<dl_iterate_context*>(data);
Vladimir Markoc09cd052018-08-23 16:36:36 +01001154 static_assert(std::is_same<Elf32_Half, Elf64_Half>::value, "Half must match");
1155 using Elf_Half = Elf64_Half;
1156
Andreas Gampe4075f832016-05-18 13:09:54 -07001157 context->shared_objects_seen++;
1158 if (context->shared_objects_seen < context->shared_objects_before) {
1159 // We haven't been called yet for anything we haven't seen before. Just continue.
1160 // Note: this is aggressively optimistic. If another thread was unloading a library,
1161 // we may miss out here. However, this does not happen often in practice.
1162 return 0;
1163 }
1164
Andreas Gampe049cff02015-12-01 23:27:12 -08001165 // See whether this callback corresponds to the file which we have just loaded.
1166 bool contains_begin = false;
Vladimir Markoc09cd052018-08-23 16:36:36 +01001167 for (Elf_Half i = 0; i < info->dlpi_phnum; i++) {
Andreas Gampe049cff02015-12-01 23:27:12 -08001168 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
1169 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
1170 info->dlpi_phdr[i].p_vaddr);
1171 size_t memsz = info->dlpi_phdr[i].p_memsz;
1172 if (vaddr <= context->begin_ && context->begin_ < vaddr + memsz) {
1173 contains_begin = true;
1174 break;
1175 }
1176 }
1177 }
1178 // Add dummy mmaps for this file.
1179 if (contains_begin) {
Vladimir Markoc09cd052018-08-23 16:36:36 +01001180 for (Elf_Half i = 0; i < info->dlpi_phnum; i++) {
Andreas Gampe049cff02015-12-01 23:27:12 -08001181 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
1182 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
1183 info->dlpi_phdr[i].p_vaddr);
1184 size_t memsz = info->dlpi_phdr[i].p_memsz;
Vladimir Markoc34bebf2018-08-16 16:12:49 +01001185 MemMap mmap = MemMap::MapDummy(info->dlpi_name, vaddr, memsz);
1186 context->dlopen_mmaps_->push_back(std::move(mmap));
Andreas Gampe049cff02015-12-01 23:27:12 -08001187 }
1188 }
1189 return 1; // Stop iteration and return 1 from dl_iterate_phdr.
1190 }
1191 return 0; // Continue iteration and return 0 from dl_iterate_phdr when finished.
1192 }
1193 const uint8_t* const begin_;
Vladimir Markoc34bebf2018-08-16 16:12:49 +01001194 std::vector<MemMap>* const dlopen_mmaps_;
Andreas Gampe4075f832016-05-18 13:09:54 -07001195 const size_t shared_objects_before;
1196 size_t shared_objects_seen;
1197 };
1198 dl_iterate_context context = { Begin(), &dlopen_mmaps_, shared_objects_before_, 0};
Andreas Gampe049cff02015-12-01 23:27:12 -08001199
1200 if (dl_iterate_phdr(dl_iterate_context::callback, &context) == 0) {
Andreas Gampe4075f832016-05-18 13:09:54 -07001201 // Hm. Maybe our optimization went wrong. Try another time with shared_objects_before == 0
1202 // before giving up. This should be unusual.
1203 VLOG(oat) << "Need a second run in PreSetup, didn't find with shared_objects_before="
1204 << shared_objects_before_;
1205 dl_iterate_context context0 = { Begin(), &dlopen_mmaps_, 0, 0};
1206 if (dl_iterate_phdr(dl_iterate_context::callback, &context0) == 0) {
1207 // OK, give up and print an error.
Andreas Gampe170331f2017-12-07 18:41:03 -08001208 PrintFileToLog("/proc/self/maps", android::base::LogSeverity::WARNING);
Andreas Gampe4075f832016-05-18 13:09:54 -07001209 LOG(ERROR) << "File " << elf_filename << " loaded with dlopen but cannot find its mmaps.";
1210 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001211 }
Andreas Gampe74f07b52015-12-02 11:53:26 -08001212#endif
Andreas Gampe049cff02015-12-01 23:27:12 -08001213}
1214
1215////////////////////////////////////////////////
1216// OatFile via our own ElfFile implementation //
1217////////////////////////////////////////////////
1218
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001219class ElfOatFile final : public OatFileBase {
Andreas Gampe049cff02015-12-01 23:27:12 -08001220 public:
1221 ElfOatFile(const std::string& filename, bool executable) : OatFileBase(filename, executable) {}
1222
Nicolas Geoffray30025092018-04-19 14:43:29 +01001223 static ElfOatFile* OpenElfFile(int zip_fd,
1224 File* file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001225 const std::string& location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001226 bool writable,
1227 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001228 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001229 const char* abs_dex_location,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001230 /*inout*/MemMap* reservation, // Where to load if not null.
1231 /*out*/std::string* error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -08001232
Nicolas Geoffray30025092018-04-19 14:43:29 +01001233 bool InitializeFromElfFile(int zip_fd,
1234 ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +01001235 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001236 const char* abs_dex_location,
1237 std::string* error_msg);
1238
1239 protected:
1240 const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001241 std::string* error_msg) const override {
Andreas Gampe049cff02015-12-01 23:27:12 -08001242 const uint8_t* ptr = elf_file_->FindDynamicSymbolAddress(symbol_name);
1243 if (ptr == nullptr) {
1244 *error_msg = "(Internal implementation could not find symbol)";
1245 }
1246 return ptr;
1247 }
1248
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001249 void PreLoad() override {
Andreas Gampe4075f832016-05-18 13:09:54 -07001250 }
1251
Andreas Gampe049cff02015-12-01 23:27:12 -08001252 bool Load(const std::string& elf_filename,
Andreas Gampe049cff02015-12-01 23:27:12 -08001253 bool writable,
1254 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001255 bool low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001256 /*inout*/MemMap* reservation, // Where to load if not null.
1257 /*out*/std::string* error_msg) override;
Andreas Gampe049cff02015-12-01 23:27:12 -08001258
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001259 bool Load(int oat_fd,
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001260 bool writable,
1261 bool executable,
1262 bool low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001263 /*inout*/MemMap* reservation, // Where to load if not null.
1264 /*out*/std::string* error_msg) override;
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001265
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001266 void PreSetup(const std::string& elf_filename ATTRIBUTE_UNUSED) override {
Andreas Gampe049cff02015-12-01 23:27:12 -08001267 }
1268
1269 private:
1270 bool ElfFileOpen(File* file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001271 bool writable,
1272 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001273 bool low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001274 /*inout*/MemMap* reservation, // Where to load if not null.
1275 /*out*/std::string* error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -08001276
1277 private:
1278 // Backing memory map for oat file during cross compilation.
1279 std::unique_ptr<ElfFile> elf_file_;
1280
1281 DISALLOW_COPY_AND_ASSIGN(ElfOatFile);
1282};
1283
Nicolas Geoffray30025092018-04-19 14:43:29 +01001284ElfOatFile* ElfOatFile::OpenElfFile(int zip_fd,
1285 File* file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001286 const std::string& location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001287 bool writable,
1288 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001289 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001290 const char* abs_dex_location,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001291 /*inout*/MemMap* reservation, // Where to load if not null.
1292 /*out*/std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001293 ScopedTrace trace("Open elf file " + location);
Andreas Gampe049cff02015-12-01 23:27:12 -08001294 std::unique_ptr<ElfOatFile> oat_file(new ElfOatFile(location, executable));
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001295 bool success = oat_file->ElfFileOpen(file,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001296 writable,
1297 low_4gb,
1298 executable,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001299 reservation,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001300 error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -08001301 if (!success) {
1302 CHECK(!error_msg->empty());
1303 return nullptr;
1304 }
1305
1306 // Complete the setup.
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001307 if (!oat_file->ComputeFields(file->GetPath(), error_msg)) {
Andreas Gampe049cff02015-12-01 23:27:12 -08001308 return nullptr;
1309 }
1310
Nicolas Geoffray30025092018-04-19 14:43:29 +01001311 if (!oat_file->Setup(zip_fd, abs_dex_location, error_msg)) {
Andreas Gampe049cff02015-12-01 23:27:12 -08001312 return nullptr;
1313 }
1314
1315 return oat_file.release();
1316}
1317
Nicolas Geoffray30025092018-04-19 14:43:29 +01001318bool ElfOatFile::InitializeFromElfFile(int zip_fd,
1319 ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +01001320 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001321 const char* abs_dex_location,
1322 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001323 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -08001324 if (IsExecutable()) {
1325 *error_msg = "Cannot initialize from elf file in executable mode.";
1326 return false;
1327 }
1328 elf_file_.reset(elf_file);
David Brazdilc93b3be2016-09-12 18:49:58 +01001329 SetVdex(vdex_file);
Andreas Gampe049cff02015-12-01 23:27:12 -08001330 uint64_t offset, size;
1331 bool has_section = elf_file->GetSectionOffsetAndSize(".rodata", &offset, &size);
1332 CHECK(has_section);
1333 SetBegin(elf_file->Begin() + offset);
1334 SetEnd(elf_file->Begin() + size + offset);
1335 // Ignore the optional .bss section when opening non-executable.
Nicolas Geoffray30025092018-04-19 14:43:29 +01001336 return Setup(zip_fd, abs_dex_location, error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -08001337}
1338
1339bool ElfOatFile::Load(const std::string& elf_filename,
Andreas Gampe049cff02015-12-01 23:27:12 -08001340 bool writable,
1341 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001342 bool low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001343 /*inout*/MemMap* reservation,
1344 /*out*/std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001345 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -08001346 std::unique_ptr<File> file(OS::OpenFileForReading(elf_filename.c_str()));
1347 if (file == nullptr) {
1348 *error_msg = StringPrintf("Failed to open oat filename for reading: %s", strerror(errno));
1349 return false;
1350 }
1351 return ElfOatFile::ElfFileOpen(file.get(),
Andreas Gampe049cff02015-12-01 23:27:12 -08001352 writable,
1353 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001354 low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001355 reservation,
Andreas Gampe049cff02015-12-01 23:27:12 -08001356 error_msg);
1357}
1358
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001359bool ElfOatFile::Load(int oat_fd,
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001360 bool writable,
1361 bool executable,
1362 bool low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001363 /*inout*/MemMap* reservation,
1364 /*out*/std::string* error_msg) {
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001365 ScopedTrace trace(__PRETTY_FUNCTION__);
1366 if (oat_fd != -1) {
Josh Gaoafeec9f2018-08-30 14:05:56 -07001367 int duped_fd = DupCloexec(oat_fd);
1368 std::unique_ptr<File> file = std::make_unique<File>(duped_fd, false);
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001369 if (file == nullptr) {
1370 *error_msg = StringPrintf("Failed to open oat filename for reading: %s",
1371 strerror(errno));
1372 return false;
1373 }
1374 return ElfOatFile::ElfFileOpen(file.get(),
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001375 writable,
1376 executable,
1377 low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001378 reservation,
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001379 error_msg);
1380 }
1381 return false;
1382}
1383
Andreas Gampe049cff02015-12-01 23:27:12 -08001384bool ElfOatFile::ElfFileOpen(File* file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001385 bool writable,
1386 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001387 bool low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001388 /*inout*/MemMap* reservation,
1389 /*out*/std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001390 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -08001391 elf_file_.reset(ElfFile::Open(file,
1392 writable,
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001393 /*program_header_only=*/ true,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001394 low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001395 error_msg));
Andreas Gampe049cff02015-12-01 23:27:12 -08001396 if (elf_file_ == nullptr) {
1397 DCHECK(!error_msg->empty());
1398 return false;
1399 }
Vladimir Markoc09cd052018-08-23 16:36:36 +01001400 bool loaded = elf_file_->Load(file, executable, low_4gb, reservation, error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -08001401 DCHECK(loaded || !error_msg->empty());
1402 return loaded;
1403}
1404
David Brazdil7126c5b2019-03-05 00:02:51 +00001405class OatFileBackedByVdex final : public OatFileBase {
1406 public:
1407 explicit OatFileBackedByVdex(const std::string& filename)
1408 : OatFileBase(filename, /*executable=*/ false) {}
1409
1410 static OatFileBackedByVdex* Open(const std::vector<const DexFile*>& dex_files,
1411 std::unique_ptr<VdexFile>&& vdex_file,
1412 const std::string& location) {
1413 std::unique_ptr<OatFileBackedByVdex> oat_file(new OatFileBackedByVdex(location));
1414 oat_file->Initialize(dex_files, std::move(vdex_file));
1415 return oat_file.release();
1416 }
1417
1418 void Initialize(const std::vector<const DexFile*>& dex_files,
1419 std::unique_ptr<VdexFile>&& vdex_file) {
1420 DCHECK(!IsExecutable());
1421
1422 // SetVdex will take ownership of the VdexFile.
1423 SetVdex(vdex_file.release());
1424
1425 // Create a dummy OatHeader.
1426 std::unique_ptr<const InstructionSetFeatures> isa_features =
1427 InstructionSetFeatures::FromCppDefines();
1428 oat_header_.reset(OatHeader::Create(kRuntimeISA,
1429 isa_features.get(),
1430 dex_files.size(),
1431 nullptr));
1432 const uint8_t* begin = reinterpret_cast<const uint8_t*>(oat_header_.get());
1433 SetBegin(begin);
1434 SetEnd(begin + oat_header_->GetHeaderSize());
1435
1436 // Load VerifierDeps from VDEX and copy bit vectors of verified classes.
1437 ArrayRef<const uint8_t> deps_data = GetVdexFile()->GetVerifierDepsData();
1438 verified_classes_per_dex_ = verifier::VerifierDeps::ParseVerifiedClasses(dex_files, deps_data);
1439
1440 // Initialize OatDexFiles.
1441 Setup(dex_files);
1442 }
1443
1444 bool IsClassVerifiedInVdex(const OatDexFile& oat_dex_file, uint16_t class_def_index) const {
1445 // Determine the index of the DexFile, assuming the order of OatDexFiles
1446 // in `oat_dex_files_storage_` is the same.
1447 const std::vector<const OatDexFile*>& oat_dex_files = GetOatDexFiles();
1448 auto oat_dex_file_it = std::find(oat_dex_files.begin(), oat_dex_files.end(), &oat_dex_file);
1449 DCHECK(oat_dex_file_it != oat_dex_files.end());
1450 size_t dex_index = oat_dex_file_it - oat_dex_files.begin();
1451 // Check the bitvector of verified classes from the vdex.
1452 return verified_classes_per_dex_[dex_index][class_def_index];
1453 }
1454
1455 protected:
1456 void PreLoad() override {}
1457
1458 bool Load(const std::string& elf_filename ATTRIBUTE_UNUSED,
1459 bool writable ATTRIBUTE_UNUSED,
1460 bool executable ATTRIBUTE_UNUSED,
1461 bool low_4gb ATTRIBUTE_UNUSED,
1462 MemMap* reservation ATTRIBUTE_UNUSED,
1463 std::string* error_msg ATTRIBUTE_UNUSED) override {
1464 LOG(FATAL) << "Unsupported";
1465 UNREACHABLE();
1466 }
1467
1468 bool Load(int oat_fd ATTRIBUTE_UNUSED,
1469 bool writable ATTRIBUTE_UNUSED,
1470 bool executable ATTRIBUTE_UNUSED,
1471 bool low_4gb ATTRIBUTE_UNUSED,
1472 MemMap* reservation ATTRIBUTE_UNUSED,
1473 std::string* error_msg ATTRIBUTE_UNUSED) override {
1474 LOG(FATAL) << "Unsupported";
1475 UNREACHABLE();
1476 }
1477
1478 void PreSetup(const std::string& elf_filename ATTRIBUTE_UNUSED) override {}
1479
1480 const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name ATTRIBUTE_UNUSED,
1481 std::string* error_msg) const override {
1482 *error_msg = "Unsupported";
1483 return nullptr;
1484 }
1485
1486 private:
1487 std::unique_ptr<OatHeader> oat_header_;
1488 std::vector<std::vector<bool>> verified_classes_per_dex_;
1489
1490 DISALLOW_COPY_AND_ASSIGN(OatFileBackedByVdex);
1491};
1492
Andreas Gampe049cff02015-12-01 23:27:12 -08001493//////////////////////////
1494// General OatFile code //
1495//////////////////////////
1496
David Brazdil3e8aae02019-03-26 18:48:02 +00001497static bool IsLocationSuffix(const char* abs_dex_location, const std::string& rel_dex_location) {
1498 std::string_view abs_location(abs_dex_location);
1499 std::string target_suffix = "/" + DexFileLoader::GetBaseLocation(rel_dex_location);
1500 if (abs_location.size() <= target_suffix.size()) {
1501 return false;
1502 }
1503 size_t pos = abs_location.size() - target_suffix.size();
1504 return abs_location.compare(pos, std::string::npos, target_suffix) == 0;
1505}
1506
1507static void MaybeResolveDexPath(const char* abs_dex_location,
1508 const std::string& rel_dex_location,
1509 bool resolve,
1510 /* out */ std::string* out_location) {
1511 DCHECK(!resolve || abs_dex_location != nullptr);
1512 if (out_location != nullptr) {
1513 *out_location = resolve
1514 ? std::string(abs_dex_location) + DexFileLoader::GetMultiDexSuffix(rel_dex_location)
1515 : rel_dex_location;
1516 }
1517}
1518
1519void OatFile::ResolveRelativeEncodedDexLocation(const char* abs_dex_location,
1520 const std::string& rel_dex_location,
1521 /* out */ std::string* dex_file_location,
1522 /* out */ std::string* dex_file_name) {
1523 // Note that in this context `abs_dex_location` may not always be absolute
1524 // and `rel_dex_location` may not always be relative. It simply means that
1525 // we will try to resolve `rel_dex_location` into an absolute location using
1526 // `abs_dex_location` for the base directory if needed.
1527
1528 bool resolve_location = false;
1529 bool resolve_filename = false;
1530
Nicolas Geoffray8baa11a2019-01-24 10:30:03 +00001531 if (abs_dex_location != nullptr) {
David Brazdil3e8aae02019-03-26 18:48:02 +00001532 if (!IsAbsoluteLocation(rel_dex_location) &&
1533 IsLocationSuffix(abs_dex_location, rel_dex_location)) {
1534 // The base location (w/o multidex suffix) of the relative `rel_dex_location` is a suffix
1535 // of `abs_dex_location`. This typically happens for oat files which only encode the
1536 // basename() so the oat and dex files can move to different directories.
1537 // Example:
1538 // abs_dex_location = "/data/app/myapp/MyApplication.apk"
1539 // rel_dex_location = "MyApplication.apk!classes2.dex"
1540 resolve_location = true;
1541 resolve_filename = true;
1542 } else {
1543 // Case 1: `rel_dex_location` is absolute
1544 // On target always use `rel_dex_location` for both dex file name and dex location.
1545 // On host assume we're cross-compiling and use `abs_dex_location` as a file name
1546 // (for loading files) and `rel_dex_location` as the dex location. If we're not
1547 // cross-compiling, the two paths should be equal.
1548 // Case 2: `rel_dex_location` is relative and not suffix of `abs_location`
1549 // This should never happen outside of tests. On target always use `rel_dex_location`. On
1550 // host use `abs_dex_location` with the appropriate multidex suffix because
1551 // `rel_dex_location` might be the target path.
1552 resolve_location = false;
1553 resolve_filename = !kIsTargetBuild;
Andreas Gampe049cff02015-12-01 23:27:12 -08001554 }
1555 }
David Brazdil3e8aae02019-03-26 18:48:02 +00001556
1557 // Construct dex file location and dex file name if the correspoding out-param pointers
1558 // were provided by the caller.
1559 MaybeResolveDexPath(abs_dex_location, rel_dex_location, resolve_location, dex_file_location);
1560 MaybeResolveDexPath(abs_dex_location, rel_dex_location, resolve_filename, dex_file_name);
Andreas Gampe049cff02015-12-01 23:27:12 -08001561}
1562
1563static void CheckLocation(const std::string& location) {
1564 CHECK(!location.empty());
1565}
1566
Nicolas Geoffray30025092018-04-19 14:43:29 +01001567OatFile* OatFile::OpenWithElfFile(int zip_fd,
1568 ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +01001569 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001570 const std::string& location,
1571 const char* abs_dex_location,
1572 std::string* error_msg) {
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001573 std::unique_ptr<ElfOatFile> oat_file(new ElfOatFile(location, /*executable=*/ false));
Nicolas Geoffray30025092018-04-19 14:43:29 +01001574 return oat_file->InitializeFromElfFile(zip_fd, elf_file, vdex_file, abs_dex_location, error_msg)
Andreas Gampe049cff02015-12-01 23:27:12 -08001575 ? oat_file.release()
1576 : nullptr;
1577}
1578
Nicolas Geoffray30025092018-04-19 14:43:29 +01001579OatFile* OatFile::Open(int zip_fd,
1580 const std::string& oat_filename,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001581 const std::string& oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001582 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001583 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001584 const char* abs_dex_location,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001585 /*inout*/MemMap* reservation,
1586 /*out*/std::string* error_msg) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001587 ScopedTrace trace("Open oat file " + oat_location);
1588 CHECK(!oat_filename.empty()) << oat_location;
1589 CheckLocation(oat_location);
Andreas Gampe54315c72016-05-18 21:10:42 -07001590
Calin Juravle367b9d82017-05-15 18:18:39 -07001591 std::string vdex_filename = GetVdexFilename(oat_filename);
David Brazdil7b49e6c2016-09-01 11:06:18 +01001592
1593 // Check that the files even exist, fast-fail.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001594 if (!OS::FileExists(vdex_filename.c_str())) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001595 *error_msg = StringPrintf("File %s does not exist.", vdex_filename.c_str());
1596 return nullptr;
1597 } else if (!OS::FileExists(oat_filename.c_str())) {
1598 *error_msg = StringPrintf("File %s does not exist.", oat_filename.c_str());
Andreas Gampe54315c72016-05-18 21:10:42 -07001599 return nullptr;
1600 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001601
1602 // Try dlopen first, as it is required for native debuggability. This will fail fast if dlopen is
1603 // disabled.
Nicolas Geoffray30025092018-04-19 14:43:29 +01001604 OatFile* with_dlopen = OatFileBase::OpenOatFile<DlOpenOatFile>(zip_fd,
1605 vdex_filename,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001606 oat_filename,
1607 oat_location,
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001608 /*writable=*/ false,
Andreas Gampe049cff02015-12-01 23:27:12 -08001609 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001610 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001611 abs_dex_location,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001612 reservation,
Andreas Gampe049cff02015-12-01 23:27:12 -08001613 error_msg);
1614 if (with_dlopen != nullptr) {
1615 return with_dlopen;
1616 }
1617 if (kPrintDlOpenErrorMessage) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001618 LOG(ERROR) << "Failed to dlopen: " << oat_filename << " with error " << *error_msg;
Andreas Gampe049cff02015-12-01 23:27:12 -08001619 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001620 // If we aren't trying to execute, we just use our own ElfFile loader for a couple reasons:
1621 //
1622 // On target, dlopen may fail when compiling due to selinux restrictions on installd.
1623 //
1624 // We use our own ELF loader for Quick to deal with legacy apps that
1625 // open a generated dex file by name, remove the file, then open
1626 // another generated dex file with the same name. http://b/10614658
1627 //
1628 // On host, dlopen is expected to fail when cross compiling, so fall back to OpenElfFile.
1629 //
1630 //
1631 // Another independent reason is the absolute placement of boot.oat. dlopen on the host usually
1632 // does honor the virtual address encoded in the ELF file only for ET_EXEC files, not ET_DYN.
Nicolas Geoffray30025092018-04-19 14:43:29 +01001633 OatFile* with_internal = OatFileBase::OpenOatFile<ElfOatFile>(zip_fd,
1634 vdex_filename,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001635 oat_filename,
1636 oat_location,
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001637 /*writable=*/ false,
Andreas Gampe049cff02015-12-01 23:27:12 -08001638 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001639 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001640 abs_dex_location,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001641 reservation,
Andreas Gampe049cff02015-12-01 23:27:12 -08001642 error_msg);
1643 return with_internal;
1644}
1645
Nicolas Geoffray30025092018-04-19 14:43:29 +01001646OatFile* OatFile::Open(int zip_fd,
1647 int vdex_fd,
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001648 int oat_fd,
1649 const std::string& oat_location,
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001650 bool executable,
1651 bool low_4gb,
1652 const char* abs_dex_location,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001653 /*inout*/MemMap* reservation,
1654 /*out*/std::string* error_msg) {
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001655 CHECK(!oat_location.empty()) << oat_location;
1656
1657 std::string vdex_location = GetVdexFilename(oat_location);
1658
Nicolas Geoffray30025092018-04-19 14:43:29 +01001659 OatFile* with_internal = OatFileBase::OpenOatFile<ElfOatFile>(zip_fd,
1660 vdex_fd,
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001661 oat_fd,
1662 vdex_location,
1663 oat_location,
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001664 /*writable=*/ false,
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001665 executable,
1666 low_4gb,
1667 abs_dex_location,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001668 reservation,
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001669 error_msg);
1670 return with_internal;
1671}
1672
Nicolas Geoffray30025092018-04-19 14:43:29 +01001673OatFile* OatFile::OpenWritable(int zip_fd,
1674 File* file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001675 const std::string& location,
1676 const char* abs_dex_location,
1677 std::string* error_msg) {
1678 CheckLocation(location);
Nicolas Geoffray30025092018-04-19 14:43:29 +01001679 return ElfOatFile::OpenElfFile(zip_fd,
1680 file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001681 location,
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001682 /*writable=*/ true,
1683 /*executable=*/ false,
1684 /*low_4gb=*/false,
Andreas Gampe049cff02015-12-01 23:27:12 -08001685 abs_dex_location,
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001686 /*reservation=*/ nullptr,
Andreas Gampe049cff02015-12-01 23:27:12 -08001687 error_msg);
1688}
1689
Nicolas Geoffray30025092018-04-19 14:43:29 +01001690OatFile* OatFile::OpenReadable(int zip_fd,
1691 File* file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001692 const std::string& location,
1693 const char* abs_dex_location,
1694 std::string* error_msg) {
1695 CheckLocation(location);
Nicolas Geoffray30025092018-04-19 14:43:29 +01001696 return ElfOatFile::OpenElfFile(zip_fd,
1697 file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001698 location,
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001699 /*writable=*/ false,
1700 /*executable=*/ false,
1701 /*low_4gb=*/false,
Andreas Gampe049cff02015-12-01 23:27:12 -08001702 abs_dex_location,
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001703 /*reservation=*/ nullptr,
Andreas Gampe049cff02015-12-01 23:27:12 -08001704 error_msg);
1705}
1706
David Brazdil7126c5b2019-03-05 00:02:51 +00001707OatFile* OatFile::OpenFromVdex(const std::vector<const DexFile*>& dex_files,
1708 std::unique_ptr<VdexFile>&& vdex_file,
1709 const std::string& location) {
1710 CheckLocation(location);
1711 return OatFileBackedByVdex::Open(dex_files, std::move(vdex_file), location);
1712}
1713
Andreas Gampe049cff02015-12-01 23:27:12 -08001714OatFile::OatFile(const std::string& location, bool is_executable)
1715 : location_(location),
David Brazdil7b49e6c2016-09-01 11:06:18 +01001716 vdex_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001717 begin_(nullptr),
1718 end_(nullptr),
Vladimir Markob066d432018-01-03 13:14:37 +00001719 data_bimg_rel_ro_begin_(nullptr),
1720 data_bimg_rel_ro_end_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001721 bss_begin_(nullptr),
1722 bss_end_(nullptr),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001723 bss_methods_(nullptr),
Vladimir Markoaad75c62016-10-03 08:46:48 +00001724 bss_roots_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001725 is_executable_(is_executable),
David Srbeckyec2cdf42017-12-08 16:21:25 +00001726 vdex_begin_(nullptr),
1727 vdex_end_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001728 secondary_lookup_lock_("OatFile secondary lookup lock", kOatFileSecondaryLookupLock) {
1729 CHECK(!location_.empty());
1730}
1731
1732OatFile::~OatFile() {
1733 STLDeleteElements(&oat_dex_files_storage_);
1734}
1735
Brian Carlstrome24fa612011-09-29 00:53:55 -07001736const OatHeader& OatFile::GetOatHeader() const {
Ian Rogers30fab402012-01-23 15:43:46 -08001737 return *reinterpret_cast<const OatHeader*>(Begin());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001738}
1739
Ian Rogers13735952014-10-08 12:43:28 -07001740const uint8_t* OatFile::Begin() const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001741 CHECK(begin_ != nullptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001742 return begin_;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001743}
1744
Ian Rogers13735952014-10-08 12:43:28 -07001745const uint8_t* OatFile::End() const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001746 CHECK(end_ != nullptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001747 return end_;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001748}
1749
David Brazdil7b49e6c2016-09-01 11:06:18 +01001750const uint8_t* OatFile::DexBegin() const {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001751 return vdex_->Begin();
David Brazdil7b49e6c2016-09-01 11:06:18 +01001752}
1753
1754const uint8_t* OatFile::DexEnd() const {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001755 return vdex_->End();
David Brazdil7b49e6c2016-09-01 11:06:18 +01001756}
1757
Vladimir Markob066d432018-01-03 13:14:37 +00001758ArrayRef<const uint32_t> OatFile::GetBootImageRelocations() const {
1759 if (data_bimg_rel_ro_begin_ != nullptr) {
1760 const uint32_t* relocations = reinterpret_cast<const uint32_t*>(data_bimg_rel_ro_begin_);
1761 const uint32_t* relocations_end = reinterpret_cast<const uint32_t*>(data_bimg_rel_ro_end_);
1762 return ArrayRef<const uint32_t>(relocations, relocations_end - relocations);
1763 } else {
1764 return ArrayRef<const uint32_t>();
1765 }
1766}
1767
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001768ArrayRef<ArtMethod*> OatFile::GetBssMethods() const {
1769 if (bss_methods_ != nullptr) {
1770 ArtMethod** methods = reinterpret_cast<ArtMethod**>(bss_methods_);
1771 ArtMethod** methods_end =
1772 reinterpret_cast<ArtMethod**>(bss_roots_ != nullptr ? bss_roots_ : bss_end_);
1773 return ArrayRef<ArtMethod*>(methods, methods_end - methods);
1774 } else {
1775 return ArrayRef<ArtMethod*>();
1776 }
1777}
1778
Vladimir Markoaad75c62016-10-03 08:46:48 +00001779ArrayRef<GcRoot<mirror::Object>> OatFile::GetBssGcRoots() const {
1780 if (bss_roots_ != nullptr) {
1781 auto* roots = reinterpret_cast<GcRoot<mirror::Object>*>(bss_roots_);
1782 auto* roots_end = reinterpret_cast<GcRoot<mirror::Object>*>(bss_end_);
1783 return ArrayRef<GcRoot<mirror::Object>>(roots, roots_end - roots);
1784 } else {
1785 return ArrayRef<GcRoot<mirror::Object>>();
1786 }
1787}
1788
Andreas Gampeb40d3612018-06-26 15:49:42 -07001789const OatDexFile* OatFile::GetOatDexFile(const char* dex_location,
1790 const uint32_t* dex_location_checksum,
1791 std::string* error_msg) const {
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001792 // NOTE: We assume here that the canonical location for a given dex_location never
1793 // changes. If it does (i.e. some symlink used by the filename changes) we may return
1794 // an incorrect OatDexFile. As long as we have a checksum to check, we shall return
1795 // an identical file or fail; otherwise we may see some unpredictable failures.
Calin Juravle4e1d5792014-07-15 23:56:47 +01001796
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001797 // TODO: Additional analysis of usage patterns to see if this can be simplified
1798 // without any performance loss, for example by not doing the first lock-free lookup.
1799
Andreas Gampeb40d3612018-06-26 15:49:42 -07001800 const OatDexFile* oat_dex_file = nullptr;
Vladimir Marko59ae4f92019-02-04 14:06:02 +00001801 std::string_view key(dex_location);
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001802 // Try to find the key cheaply in the oat_dex_files_ map which holds dex locations
1803 // directly mentioned in the oat file and doesn't require locking.
1804 auto primary_it = oat_dex_files_.find(key);
1805 if (primary_it != oat_dex_files_.end()) {
1806 oat_dex_file = primary_it->second;
1807 DCHECK(oat_dex_file != nullptr);
1808 } else {
1809 // This dex_location is not one of the dex locations directly mentioned in the
1810 // oat file. The correct lookup is via the canonical location but first see in
1811 // the secondary_oat_dex_files_ whether we've looked up this location before.
1812 MutexLock mu(Thread::Current(), secondary_lookup_lock_);
1813 auto secondary_lb = secondary_oat_dex_files_.lower_bound(key);
1814 if (secondary_lb != secondary_oat_dex_files_.end() && key == secondary_lb->first) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001815 oat_dex_file = secondary_lb->second; // May be null.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001816 } else {
1817 // We haven't seen this dex_location before, we must check the canonical location.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001818 std::string dex_canonical_location = DexFileLoader::GetDexCanonicalLocation(dex_location);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001819 if (dex_canonical_location != dex_location) {
Vladimir Marko59ae4f92019-02-04 14:06:02 +00001820 std::string_view canonical_key(dex_canonical_location);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001821 auto canonical_it = oat_dex_files_.find(canonical_key);
1822 if (canonical_it != oat_dex_files_.end()) {
1823 oat_dex_file = canonical_it->second;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001824 } // else keep null.
1825 } // else keep null.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001826
1827 // Copy the key to the string_cache_ and store the result in secondary map.
1828 string_cache_.emplace_back(key.data(), key.length());
Vladimir Marko59ae4f92019-02-04 14:06:02 +00001829 std::string_view key_copy(string_cache_.back());
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001830 secondary_oat_dex_files_.PutBefore(secondary_lb, key_copy, oat_dex_file);
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001831 }
1832 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001833
1834 if (oat_dex_file == nullptr) {
1835 if (error_msg != nullptr) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001836 std::string dex_canonical_location = DexFileLoader::GetDexCanonicalLocation(dex_location);
Richard Uhler9a37efc2016-08-05 16:32:55 -07001837 *error_msg = "Failed to find OatDexFile for DexFile " + std::string(dex_location)
1838 + " (canonical path " + dex_canonical_location + ") in OatFile " + GetLocation();
1839 }
1840 return nullptr;
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001841 }
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001842
Richard Uhler9a37efc2016-08-05 16:32:55 -07001843 if (dex_location_checksum != nullptr &&
1844 oat_dex_file->GetDexFileLocationChecksum() != *dex_location_checksum) {
1845 if (error_msg != nullptr) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001846 std::string dex_canonical_location = DexFileLoader::GetDexCanonicalLocation(dex_location);
Richard Uhler9a37efc2016-08-05 16:32:55 -07001847 std::string checksum = StringPrintf("0x%08x", oat_dex_file->GetDexFileLocationChecksum());
1848 std::string required_checksum = StringPrintf("0x%08x", *dex_location_checksum);
1849 *error_msg = "OatDexFile for DexFile " + std::string(dex_location)
1850 + " (canonical path " + dex_canonical_location + ") in OatFile " + GetLocation()
1851 + " has checksum " + checksum + " but " + required_checksum + " was required";
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001852 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001853 return nullptr;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001854 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001855 return oat_dex_file;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001856}
1857
Andreas Gampeb40d3612018-06-26 15:49:42 -07001858OatDexFile::OatDexFile(const OatFile* oat_file,
1859 const std::string& dex_file_location,
1860 const std::string& canonical_dex_file_location,
1861 uint32_t dex_file_location_checksum,
1862 const uint8_t* dex_file_pointer,
1863 const uint8_t* lookup_table_data,
1864 const IndexBssMapping* method_bss_mapping_data,
1865 const IndexBssMapping* type_bss_mapping_data,
1866 const IndexBssMapping* string_bss_mapping_data,
1867 const uint32_t* oat_class_offsets_pointer,
1868 const DexLayoutSections* dex_layout_sections)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001869 : oat_file_(oat_file),
1870 dex_file_location_(dex_file_location),
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001871 canonical_dex_file_location_(canonical_dex_file_location),
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001872 dex_file_location_checksum_(dex_file_location_checksum),
Brian Carlstrom89521892011-12-07 22:05:07 -08001873 dex_file_pointer_(dex_file_pointer),
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001874 lookup_table_data_(lookup_table_data),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001875 method_bss_mapping_(method_bss_mapping_data),
Vladimir Markof3c52b42017-11-17 17:32:12 +00001876 type_bss_mapping_(type_bss_mapping_data),
1877 string_bss_mapping_(string_bss_mapping_data),
Vladimir Marko09d09432015-09-08 13:47:48 +01001878 oat_class_offsets_pointer_(oat_class_offsets_pointer),
Vladimir Markoea341d22018-05-11 10:33:37 +01001879 lookup_table_(),
Mathieu Chartier120aa282017-08-05 16:03:03 -07001880 dex_layout_sections_(dex_layout_sections) {
David Sehr9aa352e2016-09-15 18:13:52 -07001881 // Initialize TypeLookupTable.
1882 if (lookup_table_data_ != nullptr) {
1883 // Peek the number of classes from the DexFile.
1884 const DexFile::Header* dex_header = reinterpret_cast<const DexFile::Header*>(dex_file_pointer_);
1885 const uint32_t num_class_defs = dex_header->class_defs_size_;
1886 if (lookup_table_data_ + TypeLookupTable::RawDataLength(num_class_defs) > GetOatFile()->End()) {
1887 LOG(WARNING) << "found truncated lookup table in " << dex_file_location_;
1888 } else {
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08001889 const uint8_t* dex_data = dex_file_pointer_;
1890 // TODO: Clean this up to create the type lookup table after the dex file has been created?
1891 if (CompactDexFile::IsMagicValid(dex_header->magic_)) {
1892 dex_data += dex_header->data_off_;
1893 }
1894 lookup_table_ = TypeLookupTable::Open(dex_data, lookup_table_data_, num_class_defs);
David Sehr9aa352e2016-09-15 18:13:52 -07001895 }
1896 }
David Brazdil7126c5b2019-03-05 00:02:51 +00001897 DCHECK(!IsBackedByVdexOnly());
1898}
1899
1900OatDexFile::OatDexFile(const OatFile* oat_file,
1901 const DexFile* dex_file,
1902 const std::string& dex_file_location,
1903 const std::string& canonical_dex_file_location)
1904 : oat_file_(oat_file),
1905 dex_file_location_(dex_file_location),
1906 canonical_dex_file_location_(canonical_dex_file_location),
1907 dex_file_location_checksum_(dex_file->GetLocationChecksum()),
1908 dex_file_pointer_(reinterpret_cast<const uint8_t*>(dex_file)) {
1909 dex_file->SetOatDexFile(this);
1910 DCHECK(IsBackedByVdexOnly());
David Sehr9aa352e2016-09-15 18:13:52 -07001911}
Brian Carlstrome24fa612011-09-29 00:53:55 -07001912
Andreas Gampe875b4f22018-11-19 12:59:15 -08001913OatDexFile::OatDexFile(TypeLookupTable&& lookup_table) : lookup_table_(std::move(lookup_table)) {
David Srbeckyb5649f92019-05-14 15:27:52 +01001914 // Stripped-down OatDexFile only allowed in the compiler, the zygote, or the system server.
Nicolas Geoffraydc2fbb62019-04-11 22:55:50 +01001915 CHECK(Runtime::Current() == nullptr ||
1916 Runtime::Current()->IsAotCompiler() ||
David Srbeckyb5649f92019-05-14 15:27:52 +01001917 Runtime::Current()->IsZygote() ||
1918 Runtime::Current()->IsSystemServer());
Andreas Gampe875b4f22018-11-19 12:59:15 -08001919}
Mathieu Chartier1b868492016-11-16 16:22:37 -08001920
Andreas Gampeb40d3612018-06-26 15:49:42 -07001921OatDexFile::~OatDexFile() {}
Brian Carlstrome24fa612011-09-29 00:53:55 -07001922
Andreas Gampeb40d3612018-06-26 15:49:42 -07001923size_t OatDexFile::FileSize() const {
Andreas Gampe875b4f22018-11-19 12:59:15 -08001924 DCHECK(dex_file_pointer_ != nullptr);
Ian Rogers05f28c62012-10-23 18:12:13 -07001925 return reinterpret_cast<const DexFile::Header*>(dex_file_pointer_)->file_size_;
1926}
1927
Andreas Gampeb40d3612018-06-26 15:49:42 -07001928std::unique_ptr<const DexFile> OatDexFile::OpenDexFile(std::string* error_msg) const {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001929 ScopedTrace trace(__PRETTY_FUNCTION__);
Aart Bik37d6a3b2016-06-21 18:30:10 -07001930 static constexpr bool kVerify = false;
1931 static constexpr bool kVerifyChecksum = false;
David Sehr013fd802018-01-11 22:55:24 -08001932 const ArtDexFileLoader dex_file_loader;
1933 return dex_file_loader.Open(dex_file_pointer_,
1934 FileSize(),
1935 dex_file_location_,
1936 dex_file_location_checksum_,
1937 this,
1938 kVerify,
1939 kVerifyChecksum,
1940 error_msg);
Brian Carlstrom89521892011-12-07 22:05:07 -08001941}
1942
Andreas Gampeb40d3612018-06-26 15:49:42 -07001943uint32_t OatDexFile::GetOatClassOffset(uint16_t class_def_index) const {
Andreas Gampe875b4f22018-11-19 12:59:15 -08001944 DCHECK(oat_class_offsets_pointer_ != nullptr);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001945 return oat_class_offsets_pointer_[class_def_index];
1946}
1947
David Brazdil7126c5b2019-03-05 00:02:51 +00001948bool OatDexFile::IsBackedByVdexOnly() const {
1949 return oat_class_offsets_pointer_ == nullptr;
1950}
1951
Andreas Gampeb40d3612018-06-26 15:49:42 -07001952OatFile::OatClass OatDexFile::GetOatClass(uint16_t class_def_index) const {
David Brazdil7126c5b2019-03-05 00:02:51 +00001953 // If this is an OatFileBackedByVdex, initialize the OatClass using the vdex's VerifierDeps.
1954 if (IsBackedByVdexOnly()) {
1955 bool is_vdex_verified = down_cast<const OatFileBackedByVdex*>(oat_file_)->IsClassVerifiedInVdex(
1956 *this,
1957 class_def_index);
1958 return OatFile::OatClass(oat_file_,
1959 is_vdex_verified ? ClassStatus::kVerified : ClassStatus::kNotReady,
1960 /* type= */ kOatClassNoneCompiled,
1961 /* bitmap_size= */ 0u,
1962 /* bitmap_pointer= */ nullptr,
1963 /* methods_pointer= */ nullptr);
1964 }
1965
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001966 uint32_t oat_class_offset = GetOatClassOffset(class_def_index);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001967
Ian Rogers13735952014-10-08 12:43:28 -07001968 const uint8_t* oat_class_pointer = oat_file_->Begin() + oat_class_offset;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001969 CHECK_LT(oat_class_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001970
Ian Rogers13735952014-10-08 12:43:28 -07001971 const uint8_t* status_pointer = oat_class_pointer;
Brian Carlstromba150c32013-08-27 17:31:03 -07001972 CHECK_LT(status_pointer, oat_file_->End()) << oat_file_->GetLocation();
Vladimir Marko2c64a832018-01-04 11:31:56 +00001973 ClassStatus status = enum_cast<ClassStatus>(*reinterpret_cast<const int16_t*>(status_pointer));
1974 CHECK_LE(status, ClassStatus::kLast);
Brian Carlstromba150c32013-08-27 17:31:03 -07001975
Ian Rogers13735952014-10-08 12:43:28 -07001976 const uint8_t* type_pointer = status_pointer + sizeof(uint16_t);
Brian Carlstromba150c32013-08-27 17:31:03 -07001977 CHECK_LT(type_pointer, oat_file_->End()) << oat_file_->GetLocation();
1978 OatClassType type = static_cast<OatClassType>(*reinterpret_cast<const uint16_t*>(type_pointer));
1979 CHECK_LT(type, kOatClassMax);
1980
Ian Rogers13735952014-10-08 12:43:28 -07001981 const uint8_t* after_type_pointer = type_pointer + sizeof(int16_t);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001982 CHECK_LE(after_type_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07001983
Brian Carlstromcd937a92014-03-04 22:53:23 -08001984 uint32_t bitmap_size = 0;
Ian Rogers13735952014-10-08 12:43:28 -07001985 const uint8_t* bitmap_pointer = nullptr;
1986 const uint8_t* methods_pointer = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07001987 if (type != kOatClassNoneCompiled) {
1988 if (type == kOatClassSomeCompiled) {
1989 bitmap_size = static_cast<uint32_t>(*reinterpret_cast<const uint32_t*>(after_type_pointer));
1990 bitmap_pointer = after_type_pointer + sizeof(bitmap_size);
1991 CHECK_LE(bitmap_pointer, oat_file_->End()) << oat_file_->GetLocation();
1992 methods_pointer = bitmap_pointer + bitmap_size;
1993 } else {
1994 methods_pointer = after_type_pointer;
1995 }
1996 CHECK_LE(methods_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstromcd937a92014-03-04 22:53:23 -08001997 }
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001998
Richard Uhler07b3c232015-03-31 15:57:54 -07001999 return OatFile::OatClass(oat_file_,
2000 status,
2001 type,
2002 bitmap_size,
2003 reinterpret_cast<const uint32_t*>(bitmap_pointer),
2004 reinterpret_cast<const OatMethodOffsets*>(methods_pointer));
Brian Carlstrome24fa612011-09-29 00:53:55 -07002005}
2006
Hans Boehm206348c2018-12-05 11:11:33 -08002007ArrayRef<const uint8_t> OatDexFile::GetQuickenedInfoOf(const DexFile& dex_file,
2008 uint32_t dex_method_idx) const {
2009 const OatFile* oat_file = GetOatFile();
2010 if (oat_file == nullptr) {
2011 return ArrayRef<const uint8_t>();
2012 } else {
2013 return oat_file->GetVdexFile()->GetQuickenedInfoOf(dex_file, dex_method_idx);
2014 }
2015}
2016
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002017const dex::ClassDef* OatDexFile::FindClassDef(const DexFile& dex_file,
2018 const char* descriptor,
2019 size_t hash) {
Andreas Gampeb40d3612018-06-26 15:49:42 -07002020 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
David Sehr9aa352e2016-09-15 18:13:52 -07002021 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08002022 bool used_lookup_table = false;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002023 const dex::ClassDef* lookup_table_classdef = nullptr;
Vladimir Markoea341d22018-05-11 10:33:37 +01002024 if (LIKELY((oat_dex_file != nullptr) && oat_dex_file->GetTypeLookupTable().Valid())) {
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08002025 used_lookup_table = true;
Vladimir Markoea341d22018-05-11 10:33:37 +01002026 const uint32_t class_def_idx = oat_dex_file->GetTypeLookupTable().Lookup(descriptor, hash);
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08002027 lookup_table_classdef = (class_def_idx != dex::kDexNoIndex)
2028 ? &dex_file.GetClassDef(class_def_idx)
2029 : nullptr;
2030 if (!kIsDebugBuild) {
2031 return lookup_table_classdef;
2032 }
David Sehr9aa352e2016-09-15 18:13:52 -07002033 }
2034 // Fast path for rare no class defs case.
2035 const uint32_t num_class_defs = dex_file.NumClassDefs();
2036 if (num_class_defs == 0) {
Vladimir Markoea341d22018-05-11 10:33:37 +01002037 DCHECK(!used_lookup_table);
David Sehr9aa352e2016-09-15 18:13:52 -07002038 return nullptr;
2039 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002040 const dex::TypeId* type_id = dex_file.FindTypeId(descriptor);
David Sehr9aa352e2016-09-15 18:13:52 -07002041 if (type_id != nullptr) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08002042 dex::TypeIndex type_idx = dex_file.GetIndexForTypeId(*type_id);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002043 const dex::ClassDef* found_class_def = dex_file.FindClassDef(type_idx);
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08002044 if (kIsDebugBuild && used_lookup_table) {
2045 DCHECK_EQ(found_class_def, lookup_table_classdef);
2046 }
2047 return found_class_def;
David Sehr9aa352e2016-09-15 18:13:52 -07002048 }
2049 return nullptr;
2050}
2051
Mathieu Chartier120aa282017-08-05 16:03:03 -07002052// Madvise the dex file based on the state we are moving to.
2053void OatDexFile::MadviseDexFile(const DexFile& dex_file, MadviseState state) {
Mathieu Chartierc42cb0e2017-10-13 11:35:00 -07002054 Runtime* const runtime = Runtime::Current();
2055 const bool low_ram = runtime->GetHeap()->IsLowMemoryMode();
Mathieu Chartier150d25d2017-08-28 09:52:55 -07002056 // TODO: Also do madvise hints for non low ram devices.
Mathieu Chartierc42cb0e2017-10-13 11:35:00 -07002057 if (!low_ram) {
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07002058 return;
2059 }
Mathieu Chartierc42cb0e2017-10-13 11:35:00 -07002060 if (state == MadviseState::kMadviseStateAtLoad && runtime->MAdviseRandomAccess()) {
2061 // Default every dex file to MADV_RANDOM when its loaded by default for low ram devices.
2062 // Other devices have enough page cache to get performance benefits from loading more pages
2063 // into the page cache.
David Sehrc431b9d2018-03-02 12:01:51 -08002064 DexLayoutSection::MadviseLargestPageAlignedRegion(dex_file.Begin(),
2065 dex_file.Begin() + dex_file.Size(),
2066 MADV_RANDOM);
Mathieu Chartier120aa282017-08-05 16:03:03 -07002067 }
Andreas Gampeb40d3612018-06-26 15:49:42 -07002068 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Mathieu Chartier120aa282017-08-05 16:03:03 -07002069 if (oat_dex_file != nullptr) {
2070 // Should always be there.
2071 const DexLayoutSections* const sections = oat_dex_file->GetDexLayoutSections();
2072 CHECK(sections != nullptr);
2073 sections->Madvise(&dex_file, state);
2074 }
2075}
2076
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002077OatFile::OatClass::OatClass(const OatFile* oat_file,
Vladimir Marko2c64a832018-01-04 11:31:56 +00002078 ClassStatus status,
Brian Carlstromba150c32013-08-27 17:31:03 -07002079 OatClassType type,
2080 uint32_t bitmap_size,
2081 const uint32_t* bitmap_pointer,
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002082 const OatMethodOffsets* methods_pointer)
Brian Carlstromba150c32013-08-27 17:31:03 -07002083 : oat_file_(oat_file), status_(status), type_(type),
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002084 bitmap_(bitmap_pointer), methods_pointer_(methods_pointer) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002085 switch (type_) {
2086 case kOatClassAllCompiled: {
2087 CHECK_EQ(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08002088 CHECK(bitmap_pointer == nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07002089 CHECK(methods_pointer != nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07002090 break;
2091 }
2092 case kOatClassSomeCompiled: {
2093 CHECK_NE(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08002094 CHECK(bitmap_pointer != nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07002095 CHECK(methods_pointer != nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07002096 break;
2097 }
2098 case kOatClassNoneCompiled: {
2099 CHECK_EQ(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08002100 CHECK(bitmap_pointer == nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07002101 CHECK(methods_pointer_ == nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07002102 break;
2103 }
2104 case kOatClassMax: {
2105 LOG(FATAL) << "Invalid OatClassType " << type_;
Elliott Hughesc1896c92018-11-29 11:33:18 -08002106 UNREACHABLE();
Brian Carlstromba150c32013-08-27 17:31:03 -07002107 }
2108 }
2109}
Brian Carlstrome24fa612011-09-29 00:53:55 -07002110
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07002111uint32_t OatFile::OatClass::GetOatMethodOffsetsOffset(uint32_t method_index) const {
2112 const OatMethodOffsets* oat_method_offsets = GetOatMethodOffsets(method_index);
2113 if (oat_method_offsets == nullptr) {
2114 return 0u;
2115 }
2116 return reinterpret_cast<const uint8_t*>(oat_method_offsets) - oat_file_->Begin();
2117}
2118
2119const OatMethodOffsets* OatFile::OatClass::GetOatMethodOffsets(uint32_t method_index) const {
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002120 // NOTE: We don't keep the number of methods and cannot do a bounds check for method_index.
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07002121 if (methods_pointer_ == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002122 CHECK_EQ(kOatClassNoneCompiled, type_);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07002123 return nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002124 }
2125 size_t methods_pointer_index;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07002126 if (bitmap_ == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002127 CHECK_EQ(kOatClassAllCompiled, type_);
2128 methods_pointer_index = method_index;
2129 } else {
2130 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002131 if (!BitVector::IsBitSet(bitmap_, method_index)) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07002132 return nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002133 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002134 size_t num_set_bits = BitVector::NumSetBits(bitmap_, method_index);
2135 methods_pointer_index = num_set_bits;
Brian Carlstromba150c32013-08-27 17:31:03 -07002136 }
2137 const OatMethodOffsets& oat_method_offsets = methods_pointer_[methods_pointer_index];
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07002138 return &oat_method_offsets;
2139}
2140
2141const OatFile::OatMethod OatFile::OatClass::GetOatMethod(uint32_t method_index) const {
2142 const OatMethodOffsets* oat_method_offsets = GetOatMethodOffsets(method_index);
2143 if (oat_method_offsets == nullptr) {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08002144 return OatMethod(nullptr, 0);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07002145 }
2146 if (oat_file_->IsExecutable() ||
2147 Runtime::Current() == nullptr || // This case applies for oatdump.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002148 Runtime::Current()->IsAotCompiler()) {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08002149 return OatMethod(oat_file_->Begin(), oat_method_offsets->code_offset_);
Alex Light9dcc4572014-08-14 14:16:26 -07002150 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002151 // We aren't allowed to use the compiled code. We just force it down the interpreted / jit
2152 // version.
2153 return OatMethod(oat_file_->Begin(), 0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002154}
2155
Mathieu Chartiere401d142015-04-22 13:56:20 -07002156void OatFile::OatMethod::LinkMethod(ArtMethod* method) const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07002157 CHECK(method != nullptr);
Ian Rogersef7d42f2014-01-06 12:55:46 -08002158 method->SetEntryPointFromQuickCompiledCode(GetQuickCode());
Brian Carlstromae826982011-11-09 01:33:42 -08002159}
2160
Sebastien Hertz0de11332015-05-13 12:14:05 +02002161bool OatFile::IsDebuggable() const {
2162 return GetOatHeader().IsDebuggable();
2163}
2164
Andreas Gampe29d38e72016-03-23 15:31:51 +00002165CompilerFilter::Filter OatFile::GetCompilerFilter() const {
2166 return GetOatHeader().GetCompilerFilter();
Calin Juravleb077e152016-02-18 18:47:37 +00002167}
2168
Calin Juravle44e5efa2017-09-12 00:54:26 -07002169std::string OatFile::GetClassLoaderContext() const {
2170 return GetOatHeader().GetStoreValueByKey(OatHeader::kClassPathKey);
Igor Murashkin2ffb7032017-11-08 13:35:21 -08002171}
Calin Juravle44e5efa2017-09-12 00:54:26 -07002172
Calin Juravle0e09dfc2018-02-12 19:01:09 -08002173const char* OatFile::GetCompilationReason() const {
2174 return GetOatHeader().GetStoreValueByKey(OatHeader::kCompilationReasonKey);
2175}
2176
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002177OatFile::OatClass OatFile::FindOatClass(const DexFile& dex_file,
2178 uint16_t class_def_idx,
2179 bool* found) {
2180 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Andreas Gampeb40d3612018-06-26 15:49:42 -07002181 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Mathieu Chartier1b868492016-11-16 16:22:37 -08002182 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002183 *found = false;
2184 return OatFile::OatClass::Invalid();
2185 }
2186 *found = true;
2187 return oat_dex_file->GetOatClass(class_def_idx);
2188}
2189
Vladimir Marko1cedb4a2019-02-06 14:13:28 +00002190static void DCheckIndexToBssMapping(const OatFile* oat_file,
2191 uint32_t number_of_indexes,
2192 size_t slot_size,
2193 const IndexBssMapping* index_bss_mapping) {
2194 if (kIsDebugBuild && index_bss_mapping != nullptr) {
2195 size_t index_bits = IndexBssMappingEntry::IndexBits(number_of_indexes);
2196 const IndexBssMappingEntry* prev_entry = nullptr;
2197 for (const IndexBssMappingEntry& entry : *index_bss_mapping) {
2198 CHECK_ALIGNED_PARAM(entry.bss_offset, slot_size);
2199 CHECK_LT(entry.bss_offset, oat_file->BssSize());
2200 uint32_t mask = entry.GetMask(index_bits);
2201 CHECK_LE(POPCOUNT(mask) * slot_size, entry.bss_offset);
2202 size_t index_mask_span = (mask != 0u) ? 32u - index_bits - CTZ(mask) : 0u;
2203 CHECK_LE(index_mask_span, entry.GetIndex(index_bits));
2204 if (prev_entry != nullptr) {
2205 CHECK_LT(prev_entry->GetIndex(index_bits), entry.GetIndex(index_bits) - index_mask_span);
2206 }
2207 prev_entry = &entry;
2208 }
2209 CHECK(prev_entry != nullptr);
2210 CHECK_LT(prev_entry->GetIndex(index_bits), number_of_indexes);
2211 }
2212}
2213
2214void OatFile::InitializeRelocations() const {
2215 DCHECK(IsExecutable());
2216
2217 // Initialize the .data.bimg.rel.ro section.
2218 if (!GetBootImageRelocations().empty()) {
2219 uint8_t* reloc_begin = const_cast<uint8_t*>(DataBimgRelRoBegin());
2220 CheckedCall(mprotect,
2221 "un-protect boot image relocations",
2222 reloc_begin,
2223 DataBimgRelRoSize(),
2224 PROT_READ | PROT_WRITE);
Vladimir Marko7cde4582019-07-05 13:26:11 +01002225 uint32_t boot_image_begin = Runtime::Current()->GetHeap()->GetBootImagesStartAddress();
Vladimir Marko1cedb4a2019-02-06 14:13:28 +00002226 for (const uint32_t& relocation : GetBootImageRelocations()) {
2227 const_cast<uint32_t&>(relocation) += boot_image_begin;
2228 }
2229 CheckedCall(mprotect,
2230 "protect boot image relocations",
2231 reloc_begin,
2232 DataBimgRelRoSize(),
2233 PROT_READ);
2234 }
2235
2236 // Before initializing .bss, check the .bss mappings in debug mode.
2237 if (kIsDebugBuild) {
2238 PointerSize pointer_size = GetInstructionSetPointerSize(GetOatHeader().GetInstructionSet());
2239 for (const OatDexFile* odf : GetOatDexFiles()) {
2240 const DexFile::Header* header =
2241 reinterpret_cast<const DexFile::Header*>(odf->GetDexFilePointer());
2242 DCheckIndexToBssMapping(this,
2243 header->method_ids_size_,
2244 static_cast<size_t>(pointer_size),
2245 odf->GetMethodBssMapping());
2246 DCheckIndexToBssMapping(this,
2247 header->type_ids_size_,
2248 sizeof(GcRoot<mirror::Class>),
2249 odf->GetTypeBssMapping());
2250 DCheckIndexToBssMapping(this,
2251 header->string_ids_size_,
2252 sizeof(GcRoot<mirror::String>),
2253 odf->GetStringBssMapping());
2254 }
2255 }
2256
2257 // Initialize the .bss section.
2258 // TODO: Pre-initialize from boot/app image?
2259 ArtMethod* resolution_method = Runtime::Current()->GetResolutionMethod();
2260 for (ArtMethod*& entry : GetBssMethods()) {
2261 entry = resolution_method;
2262 }
2263}
2264
Andreas Gampeb40d3612018-06-26 15:49:42 -07002265void OatDexFile::AssertAotCompiler() {
Mathieu Chartier1b868492016-11-16 16:22:37 -08002266 CHECK(Runtime::Current()->IsAotCompiler());
2267}
2268
Brian Carlstrome24fa612011-09-29 00:53:55 -07002269} // namespace art