blob: 115e0eadfc47fab8d4bf5c463f0dd0d90121f7a8 [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"
Vladimir Markob7bf8432019-12-03 13:18:50 +000048#include "base/string_view_cpp20.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080049#include "base/systrace.h"
Elliott Hughes76160052012-12-12 16:31:20 -080050#include "base/unix_file/fd_file.h"
David Sehrc431b9d2018-03-02 12:01:51 -080051#include "base/utils.h"
David Sehr013fd802018-01-11 22:55:24 -080052#include "dex/art_dex_file_loader.h"
Andreas Gampe3f1dcd32018-12-28 09:39:56 -080053#include "dex/dex_file.h"
David Sehr9e734c72018-01-04 17:56:19 -080054#include "dex/dex_file_loader.h"
Andreas Gampe3f1dcd32018-12-28 09:39:56 -080055#include "dex/dex_file_structs.h"
David Sehr9e734c72018-01-04 17:56:19 -080056#include "dex/dex_file_types.h"
57#include "dex/standard_dex_file.h"
David Sehr9c4a0152018-04-05 12:23:54 -070058#include "dex/type_lookup_table.h"
David Sehr0225f8e2018-01-31 08:52:24 +000059#include "dex/utf-inl.h"
David Srbecky50928112019-03-22 17:06:28 +000060#include "elf/elf_utils.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080061#include "elf_file.h"
Vladimir Markoaad75c62016-10-03 08:46:48 +000062#include "gc_root.h"
Vladimir Marko1cedb4a2019-02-06 14:13:28 +000063#include "gc/heap.h"
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +010064#include "gc/space/image_space.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080065#include "mirror/class.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070066#include "mirror/object-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070067#include "oat.h"
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +010068#include "oat_file-inl.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070069#include "oat_file_manager.h"
Vladimir Marko1cedb4a2019-02-06 14:13:28 +000070#include "runtime-inl.h"
Vladimir Marko97d7e1c2016-10-04 14:44:28 +010071#include "vdex_file.h"
David Brazdil7126c5b2019-03-05 00:02:51 +000072#include "verifier/verifier_deps.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070073
74namespace art {
75
Andreas Gampe46ee31b2016-12-14 10:11:49 -080076using android::base::StringPrintf;
77
Andreas Gampe049cff02015-12-01 23:27:12 -080078// Whether OatFile::Open will try dlopen. Fallback is our own ELF loader.
David Srbecky1baabf02015-06-16 17:12:34 +000079static constexpr bool kUseDlopen = true;
Andreas Gampefa8429b2015-04-07 18:34:42 -070080
Andreas Gampe049cff02015-12-01 23:27:12 -080081// Whether OatFile::Open will try dlopen on the host. On the host we're not linking against
Andreas Gampefa8429b2015-04-07 18:34:42 -070082// bionic, so cannot take advantage of the support for changed semantics (loading the same soname
83// multiple times). However, if/when we switch the above, we likely want to switch this, too,
84// to get test coverage of the code paths.
David Srbecky1baabf02015-06-16 17:12:34 +000085static constexpr bool kUseDlopenOnHost = true;
Andreas Gampefa8429b2015-04-07 18:34:42 -070086
87// For debugging, Open will print DlOpen error message if set to true.
88static constexpr bool kPrintDlOpenErrorMessage = false;
89
Andreas Gampe049cff02015-12-01 23:27:12 -080090// Note for OatFileBase and descendents:
91//
92// These are used in OatFile::Open to try all our loaders.
93//
94// The process is simple:
95//
96// 1) Allocate an instance through the standard constructor (location, executable)
97// 2) Load() to try to open the file.
98// 3) ComputeFields() to populate the OatFile fields like begin_, using FindDynamicSymbolAddress.
99// 4) PreSetup() for any steps that should be done before the final setup.
100// 5) Setup() to complete the procedure.
Richard Uhlere5fed032015-03-18 08:21:11 -0700101
Andreas Gampe049cff02015-12-01 23:27:12 -0800102class OatFileBase : public OatFile {
103 public:
104 virtual ~OatFileBase() {}
Richard Uhlere5fed032015-03-18 08:21:11 -0700105
Andreas Gampe049cff02015-12-01 23:27:12 -0800106 template <typename kOatFileBaseSubType>
Nicolas Geoffray30025092018-04-19 14:43:29 +0100107 static OatFileBase* OpenOatFile(int zip_fd,
108 const std::string& vdex_filename,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100109 const std::string& elf_filename,
Alex Light84d76052014-08-22 17:49:35 -0700110 const std::string& location,
Andreas Gampe049cff02015-12-01 23:27:12 -0800111 bool writable,
112 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800113 bool low_4gb,
Vladimir Markob7bf8432019-12-03 13:18:50 +0000114 ArrayRef<const std::string> dex_filenames,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100115 /*inout*/MemMap* reservation, // Where to load if not null.
116 /*out*/std::string* error_msg);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800117
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700118 template <typename kOatFileBaseSubType>
Nicolas Geoffray30025092018-04-19 14:43:29 +0100119 static OatFileBase* OpenOatFile(int zip_fd,
120 int vdex_fd,
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700121 int oat_fd,
122 const std::string& vdex_filename,
123 const std::string& oat_filename,
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700124 bool writable,
125 bool executable,
126 bool low_4gb,
Vladimir Markob7bf8432019-12-03 13:18:50 +0000127 ArrayRef<const std::string> dex_filenames,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100128 /*inout*/MemMap* reservation, // Where to load if not null.
129 /*out*/std::string* error_msg);
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700130
Andreas Gampe049cff02015-12-01 23:27:12 -0800131 protected:
132 OatFileBase(const std::string& filename, bool executable) : OatFile(filename, executable) {}
Andreas Gampefa8429b2015-04-07 18:34:42 -0700133
Andreas Gampe049cff02015-12-01 23:27:12 -0800134 virtual const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
135 std::string* error_msg) const = 0;
136
Andreas Gampe4075f832016-05-18 13:09:54 -0700137 virtual void PreLoad() = 0;
138
David Brazdil7b49e6c2016-09-01 11:06:18 +0100139 bool LoadVdex(const std::string& vdex_filename,
140 bool writable,
141 bool low_4gb,
142 std::string* error_msg);
143
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700144 bool LoadVdex(int vdex_fd,
145 const std::string& vdex_filename,
146 bool writable,
147 bool low_4gb,
148 std::string* error_msg);
149
Andreas Gampe049cff02015-12-01 23:27:12 -0800150 virtual bool Load(const std::string& elf_filename,
Andreas Gampe049cff02015-12-01 23:27:12 -0800151 bool writable,
152 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800153 bool low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100154 /*inout*/MemMap* reservation, // Where to load if not null.
155 /*out*/std::string* error_msg) = 0;
Andreas Gampe049cff02015-12-01 23:27:12 -0800156
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700157 virtual bool Load(int oat_fd,
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700158 bool writable,
159 bool executable,
160 bool low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100161 /*inout*/MemMap* reservation, // Where to load if not null.
162 /*out*/std::string* error_msg) = 0;
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700163
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100164 bool ComputeFields(const std::string& file_path, std::string* error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -0800165
166 virtual void PreSetup(const std::string& elf_filename) = 0;
167
Vladimir Markob7bf8432019-12-03 13:18:50 +0000168 bool Setup(int zip_fd, ArrayRef<const std::string> dex_filenames, std::string* error_msg);
Nicolas Geoffray16f60dc2021-02-16 15:35:16 +0000169
170 void Setup(const std::vector<const DexFile*>& dex_files);
Andreas Gampe049cff02015-12-01 23:27:12 -0800171
172 // Setters exposed for ElfOatFile.
173
174 void SetBegin(const uint8_t* begin) {
175 begin_ = begin;
Andreas Gampefa8429b2015-04-07 18:34:42 -0700176 }
177
Andreas Gampe049cff02015-12-01 23:27:12 -0800178 void SetEnd(const uint8_t* end) {
179 end_ = end;
180 }
181
David Brazdilc93b3be2016-09-12 18:49:58 +0100182 void SetVdex(VdexFile* vdex) {
183 vdex_.reset(vdex);
184 }
185
Andreas Gampe049cff02015-12-01 23:27:12 -0800186 private:
Alex Lightabd8f052019-12-06 10:49:17 -0800187 // Returns true if we want to remove quickened opcodes before loading the VDEX file, false
188 // otherwise.
189 bool ShouldUnquickenVDex() const;
190
Andreas Gampe049cff02015-12-01 23:27:12 -0800191 DISALLOW_COPY_AND_ASSIGN(OatFileBase);
192};
193
194template <typename kOatFileBaseSubType>
Nicolas Geoffray30025092018-04-19 14:43:29 +0100195OatFileBase* OatFileBase::OpenOatFile(int zip_fd,
196 const std::string& vdex_filename,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100197 const std::string& elf_filename,
Andreas Gampe049cff02015-12-01 23:27:12 -0800198 const std::string& location,
Andreas Gampe049cff02015-12-01 23:27:12 -0800199 bool writable,
200 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800201 bool low_4gb,
Vladimir Markob7bf8432019-12-03 13:18:50 +0000202 ArrayRef<const std::string> dex_filenames,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100203 /*inout*/MemMap* reservation,
204 /*out*/std::string* error_msg) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800205 std::unique_ptr<OatFileBase> ret(new kOatFileBaseSubType(location, executable));
Andreas Gampe4075f832016-05-18 13:09:54 -0700206
207 ret->PreLoad();
208
Andreas Gampe049cff02015-12-01 23:27:12 -0800209 if (!ret->Load(elf_filename,
Andreas Gampe049cff02015-12-01 23:27:12 -0800210 writable,
211 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800212 low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100213 reservation,
Andreas Gampe049cff02015-12-01 23:27:12 -0800214 error_msg)) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800215 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800216 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800217
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100218 if (!ret->ComputeFields(elf_filename, error_msg)) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800219 return nullptr;
220 }
Andreas Gampe4075f832016-05-18 13:09:54 -0700221
David Sehr2300b2d2018-05-10 14:20:10 -0700222 ret->PreSetup(elf_filename);
223
David Srbeckyec2cdf42017-12-08 16:21:25 +0000224 if (!ret->LoadVdex(vdex_filename, writable, low_4gb, error_msg)) {
225 return nullptr;
226 }
227
Vladimir Markob7bf8432019-12-03 13:18:50 +0000228 if (!ret->Setup(zip_fd, dex_filenames, error_msg)) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800229 return nullptr;
230 }
231
Dave Allison69dfe512014-07-11 17:11:58 +0000232 return ret.release();
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800233}
234
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700235template <typename kOatFileBaseSubType>
Nicolas Geoffray30025092018-04-19 14:43:29 +0100236OatFileBase* OatFileBase::OpenOatFile(int zip_fd,
237 int vdex_fd,
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700238 int oat_fd,
239 const std::string& vdex_location,
240 const std::string& oat_location,
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700241 bool writable,
242 bool executable,
243 bool low_4gb,
Vladimir Markob7bf8432019-12-03 13:18:50 +0000244 ArrayRef<const std::string> dex_filenames,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100245 /*inout*/MemMap* reservation,
246 /*out*/std::string* error_msg) {
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700247 std::unique_ptr<OatFileBase> ret(new kOatFileBaseSubType(oat_location, executable));
248
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700249 if (!ret->Load(oat_fd,
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700250 writable,
251 executable,
252 low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +0100253 reservation,
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700254 error_msg)) {
255 return nullptr;
256 }
257
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100258 if (!ret->ComputeFields(oat_location, error_msg)) {
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700259 return nullptr;
260 }
261
David Sehr2300b2d2018-05-10 14:20:10 -0700262 ret->PreSetup(oat_location);
263
David Srbeckyec2cdf42017-12-08 16:21:25 +0000264 if (!ret->LoadVdex(vdex_fd, vdex_location, writable, low_4gb, error_msg)) {
265 return nullptr;
266 }
267
Vladimir Markob7bf8432019-12-03 13:18:50 +0000268 if (!ret->Setup(zip_fd, dex_filenames, error_msg)) {
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700269 return nullptr;
270 }
271
272 return ret.release();
273}
274
Alex Lightabd8f052019-12-06 10:49:17 -0800275bool OatFileBase::ShouldUnquickenVDex() const {
276 // We sometimes load oat files without a runtime (eg oatdump) and don't want to do anything in
277 // that case. If we are debuggable there are no -quick opcodes to unquicken. If the runtime is not
278 // debuggable we don't care whether there are -quick opcodes or not so no need to do anything.
Vladimir Markoef8c3372021-03-17 15:01:42 +0000279 Runtime* runtime = Runtime::Current();
280 return (runtime != nullptr && runtime->IsJavaDebuggable()) &&
281 // Note: This is called before `OatFileBase::Setup()` where we validate the
282 // oat file contents. Check that we have at least a valid header, including
283 // oat file version, to avoid parsing the key-value store for a different
284 // version (out-of-date oat file) which can lead to crashes. b/179221298.
285 // TODO: While this is a poor workaround and the correct solution would be
286 // to postpone the unquickening check until after `OatFileBase::Setup()`,
287 // we prefer to avoid larger rewrites because quickening is deprecated and
288 // should be removed completely anyway. b/170086509
289 (GetOatHeader().IsValid() && !IsDebuggable());
Alex Lightabd8f052019-12-06 10:49:17 -0800290}
291
David Brazdil7b49e6c2016-09-01 11:06:18 +0100292bool OatFileBase::LoadVdex(const std::string& vdex_filename,
293 bool writable,
294 bool low_4gb,
295 std::string* error_msg) {
David Srbeckyec2cdf42017-12-08 16:21:25 +0000296 vdex_ = VdexFile::OpenAtAddress(vdex_begin_,
297 vdex_end_ - vdex_begin_,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100298 /*mmap_reuse=*/ vdex_begin_ != nullptr,
David Srbeckyec2cdf42017-12-08 16:21:25 +0000299 vdex_filename,
300 writable,
301 low_4gb,
Alex Lightabd8f052019-12-06 10:49:17 -0800302 ShouldUnquickenVDex(),
David Srbeckyec2cdf42017-12-08 16:21:25 +0000303 error_msg);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100304 if (vdex_.get() == nullptr) {
305 *error_msg = StringPrintf("Failed to load vdex file '%s' %s",
306 vdex_filename.c_str(),
307 error_msg->c_str());
308 return false;
309 }
310 return true;
311}
312
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700313bool OatFileBase::LoadVdex(int vdex_fd,
314 const std::string& vdex_filename,
315 bool writable,
316 bool low_4gb,
317 std::string* error_msg) {
318 if (vdex_fd != -1) {
319 struct stat s;
320 int rc = TEMP_FAILURE_RETRY(fstat(vdex_fd, &s));
321 if (rc == -1) {
322 PLOG(WARNING) << "Failed getting length of vdex file";
323 } else {
Alex Lightabd8f052019-12-06 10:49:17 -0800324 vdex_ = VdexFile::OpenAtAddress(
325 vdex_begin_,
326 vdex_end_ - vdex_begin_,
327 /*mmap_reuse=*/ vdex_begin_ != nullptr,
328 vdex_fd,
329 s.st_size,
330 vdex_filename,
331 writable,
332 low_4gb,
333 ShouldUnquickenVDex(),
334 error_msg);
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700335 if (vdex_.get() == nullptr) {
336 *error_msg = "Failed opening vdex file.";
337 return false;
338 }
339 }
340 }
341 return true;
342}
343
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100344bool OatFileBase::ComputeFields(const std::string& file_path, std::string* error_msg) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800345 std::string symbol_error_msg;
346 begin_ = FindDynamicSymbolAddress("oatdata", &symbol_error_msg);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700347 if (begin_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800348 *error_msg = StringPrintf("Failed to find oatdata symbol in '%s' %s",
349 file_path.c_str(),
350 symbol_error_msg.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700351 return false;
352 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800353 end_ = FindDynamicSymbolAddress("oatlastword", &symbol_error_msg);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700354 if (end_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800355 *error_msg = StringPrintf("Failed to find oatlastword symbol in '%s' %s",
356 file_path.c_str(),
357 symbol_error_msg.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700358 return false;
359 }
360 // Readjust to be non-inclusive upper bound.
361 end_ += sizeof(uint32_t);
362
Vladimir Markob066d432018-01-03 13:14:37 +0000363 data_bimg_rel_ro_begin_ = FindDynamicSymbolAddress("oatdatabimgrelro", &symbol_error_msg);
364 if (data_bimg_rel_ro_begin_ != nullptr) {
365 data_bimg_rel_ro_end_ =
366 FindDynamicSymbolAddress("oatdatabimgrelrolastword", &symbol_error_msg);
367 if (data_bimg_rel_ro_end_ == nullptr) {
368 *error_msg =
369 StringPrintf("Failed to find oatdatabimgrelrolastword symbol in '%s'", file_path.c_str());
370 return false;
371 }
372 // Readjust to be non-inclusive upper bound.
373 data_bimg_rel_ro_end_ += sizeof(uint32_t);
374 }
375
Andreas Gampe049cff02015-12-01 23:27:12 -0800376 bss_begin_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbss", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700377 if (bss_begin_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800378 // No .bss section.
Andreas Gampefa8429b2015-04-07 18:34:42 -0700379 bss_end_ = nullptr;
Andreas Gampefa8429b2015-04-07 18:34:42 -0700380 } else {
Andreas Gampe049cff02015-12-01 23:27:12 -0800381 bss_end_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbsslastword", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700382 if (bss_end_ == nullptr) {
David Srbeckyec2cdf42017-12-08 16:21:25 +0000383 *error_msg = StringPrintf("Failed to find oatbsslastword symbol in '%s'", file_path.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700384 return false;
385 }
386 // Readjust to be non-inclusive upper bound.
387 bss_end_ += sizeof(uint32_t);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100388 // Find bss methods if present.
389 bss_methods_ =
390 const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbssmethods", &symbol_error_msg));
Vladimir Markoaad75c62016-10-03 08:46:48 +0000391 // Find bss roots if present.
392 bss_roots_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbssroots", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700393 }
394
David Srbeckyec2cdf42017-12-08 16:21:25 +0000395 vdex_begin_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatdex", &symbol_error_msg));
396 if (vdex_begin_ == nullptr) {
397 // No .vdex section.
398 vdex_end_ = nullptr;
399 } else {
400 vdex_end_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatdexlastword", &symbol_error_msg));
401 if (vdex_end_ == nullptr) {
402 *error_msg = StringPrintf("Failed to find oatdexlastword symbol in '%s'", file_path.c_str());
403 return false;
404 }
405 // Readjust to be non-inclusive upper bound.
406 vdex_end_ += sizeof(uint32_t);
407 }
408
Andreas Gampe049cff02015-12-01 23:27:12 -0800409 return true;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800410}
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800411
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100412// Read an unaligned entry from the OatDexFile data in OatFile and advance the read
413// position by the number of bytes read, i.e. sizeof(T).
414// Return true on success, false if the read would go beyond the end of the OatFile.
415template <typename T>
Vladimir Marko722fa982015-10-19 18:18:27 +0100416inline static bool ReadOatDexFileData(const OatFile& oat_file,
417 /*inout*/const uint8_t** oat,
418 /*out*/T* value) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100419 DCHECK(oat != nullptr);
420 DCHECK(value != nullptr);
421 DCHECK_LE(*oat, oat_file.End());
422 if (UNLIKELY(static_cast<size_t>(oat_file.End() - *oat) < sizeof(T))) {
423 return false;
424 }
425 static_assert(std::is_trivial<T>::value, "T must be a trivial type");
Andreas Gampec55bb392018-09-21 00:02:02 +0000426 using unaligned_type __attribute__((__aligned__(1))) = T;
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100427 *value = *reinterpret_cast<const unaligned_type*>(*oat);
428 *oat += sizeof(T);
429 return true;
430}
431
Vladimir Markof3c52b42017-11-17 17:32:12 +0000432static bool ReadIndexBssMapping(OatFile* oat_file,
433 /*inout*/const uint8_t** oat,
434 size_t dex_file_index,
435 const std::string& dex_file_location,
436 const char* tag,
437 /*out*/const IndexBssMapping** mapping,
438 std::string* error_msg) {
439 uint32_t index_bss_mapping_offset;
440 if (UNLIKELY(!ReadOatDexFileData(*oat_file, oat, &index_bss_mapping_offset))) {
441 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zd for '%s' truncated "
442 "after %s bss mapping offset",
443 oat_file->GetLocation().c_str(),
444 dex_file_index,
445 dex_file_location.c_str(),
446 tag);
447 return false;
448 }
449 const bool readable_index_bss_mapping_size =
450 index_bss_mapping_offset != 0u &&
451 index_bss_mapping_offset <= oat_file->Size() &&
452 IsAligned<alignof(IndexBssMapping)>(index_bss_mapping_offset) &&
453 oat_file->Size() - index_bss_mapping_offset >= IndexBssMapping::ComputeSize(0);
454 const IndexBssMapping* index_bss_mapping = readable_index_bss_mapping_size
455 ? reinterpret_cast<const IndexBssMapping*>(oat_file->Begin() + index_bss_mapping_offset)
456 : nullptr;
457 if (index_bss_mapping_offset != 0u &&
458 (UNLIKELY(index_bss_mapping == nullptr) ||
459 UNLIKELY(index_bss_mapping->size() == 0u) ||
460 UNLIKELY(oat_file->Size() - index_bss_mapping_offset <
461 IndexBssMapping::ComputeSize(index_bss_mapping->size())))) {
462 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with unaligned or "
463 " truncated %s bss mapping, offset %u of %zu, length %zu",
464 oat_file->GetLocation().c_str(),
465 dex_file_index,
466 dex_file_location.c_str(),
467 tag,
468 index_bss_mapping_offset,
469 oat_file->Size(),
470 index_bss_mapping != nullptr ? index_bss_mapping->size() : 0u);
471 return false;
472 }
473
474 *mapping = index_bss_mapping;
475 return true;
476}
477
Nicolas Geoffray16f60dc2021-02-16 15:35:16 +0000478void OatFileBase::Setup(const std::vector<const DexFile*>& dex_files) {
David Brazdil7126c5b2019-03-05 00:02:51 +0000479 for (const DexFile* dex_file : dex_files) {
480 std::string dex_location = dex_file->GetLocation();
481 std::string canonical_location = DexFileLoader::GetDexCanonicalLocation(dex_location.c_str());
482
483 // Create an OatDexFile and add it to the owning container.
Nicolas Geoffray16f60dc2021-02-16 15:35:16 +0000484 OatDexFile* oat_dex_file =
485 new OatDexFile(this, dex_file->Begin(), dex_file->GetLocationChecksum(), dex_location, canonical_location);
486 dex_file->SetOatDexFile(oat_dex_file);
David Brazdil7126c5b2019-03-05 00:02:51 +0000487 oat_dex_files_storage_.push_back(oat_dex_file);
488
489 // Add the location and canonical location (if different) to the oat_dex_files_ table.
490 std::string_view key(oat_dex_file->GetDexFileLocation());
491 oat_dex_files_.Put(key, oat_dex_file);
492 if (canonical_location != dex_location) {
493 std::string_view canonical_key(oat_dex_file->GetCanonicalDexFileLocation());
494 oat_dex_files_.Put(canonical_key, oat_dex_file);
495 }
496 }
David Brazdil7126c5b2019-03-05 00:02:51 +0000497}
498
Vladimir Markob7bf8432019-12-03 13:18:50 +0000499bool OatFileBase::Setup(int zip_fd,
500 ArrayRef<const std::string> dex_filenames,
501 std::string* error_msg) {
Brian Carlstromf1b30302013-03-28 10:35:32 -0700502 if (!GetOatHeader().IsValid()) {
Andreas Gampe2bcb3b22014-12-12 15:25:14 -0800503 std::string cause = GetOatHeader().GetValidationErrorMessage();
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100504 *error_msg = StringPrintf("Invalid oat header for '%s': %s",
505 GetLocation().c_str(),
Andreas Gampe2bcb3b22014-12-12 15:25:14 -0800506 cause.c_str());
Brian Carlstromf1b30302013-03-28 10:35:32 -0700507 return false;
508 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100509 PointerSize pointer_size = GetInstructionSetPointerSize(GetOatHeader().GetInstructionSet());
510 size_t key_value_store_size =
511 (Size() >= sizeof(OatHeader)) ? GetOatHeader().GetKeyValueStoreSize() : 0u;
512 if (Size() < sizeof(OatHeader) + key_value_store_size) {
513 *error_msg = StringPrintf("In oat file '%s' found truncated OatHeader, "
514 "size = %zu < %zu + %zu",
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100515 GetLocation().c_str(),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100516 Size(),
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100517 sizeof(OatHeader),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100518 key_value_store_size);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700519 return false;
520 }
521
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100522 size_t oat_dex_files_offset = GetOatHeader().GetOatDexFilesOffset();
523 if (oat_dex_files_offset < GetOatHeader().GetHeaderSize() || oat_dex_files_offset > Size()) {
524 *error_msg = StringPrintf("In oat file '%s' found invalid oat dex files offset: "
525 "%zu is not in [%zu, %zu]",
526 GetLocation().c_str(),
527 oat_dex_files_offset,
528 GetOatHeader().GetHeaderSize(),
529 Size());
530 return false;
531 }
532 const uint8_t* oat = Begin() + oat_dex_files_offset; // Jump to the OatDexFile records.
533
Vladimir Markob066d432018-01-03 13:14:37 +0000534 if (!IsAligned<sizeof(uint32_t)>(data_bimg_rel_ro_begin_) ||
535 !IsAligned<sizeof(uint32_t)>(data_bimg_rel_ro_end_) ||
536 data_bimg_rel_ro_begin_ > data_bimg_rel_ro_end_) {
537 *error_msg = StringPrintf("In oat file '%s' found unaligned or unordered databimgrelro "
538 "symbol(s): begin = %p, end = %p",
539 GetLocation().c_str(),
540 data_bimg_rel_ro_begin_,
541 data_bimg_rel_ro_end_);
542 return false;
543 }
544
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100545 DCHECK_GE(static_cast<size_t>(pointer_size), alignof(GcRoot<mirror::Object>));
546 if (!IsAligned<kPageSize>(bss_begin_) ||
547 !IsAlignedParam(bss_methods_, static_cast<size_t>(pointer_size)) ||
548 !IsAlignedParam(bss_roots_, static_cast<size_t>(pointer_size)) ||
Vladimir Markoaad75c62016-10-03 08:46:48 +0000549 !IsAligned<alignof(GcRoot<mirror::Object>)>(bss_end_)) {
550 *error_msg = StringPrintf("In oat file '%s' found unaligned bss symbol(s): "
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100551 "begin = %p, methods_ = %p, roots = %p, end = %p",
Vladimir Markoaad75c62016-10-03 08:46:48 +0000552 GetLocation().c_str(),
553 bss_begin_,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100554 bss_methods_,
Vladimir Markoaad75c62016-10-03 08:46:48 +0000555 bss_roots_,
556 bss_end_);
557 return false;
558 }
559
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100560 if ((bss_methods_ != nullptr && (bss_methods_ < bss_begin_ || bss_methods_ > bss_end_)) ||
561 (bss_roots_ != nullptr && (bss_roots_ < bss_begin_ || bss_roots_ > bss_end_)) ||
562 (bss_methods_ != nullptr && bss_roots_ != nullptr && bss_methods_ > bss_roots_)) {
563 *error_msg = StringPrintf("In oat file '%s' found bss symbol(s) outside .bss or unordered: "
Vladimir Marko0f3c7002017-09-07 14:15:56 +0100564 "begin = %p, methods = %p, roots = %p, end = %p",
Vladimir Markoaad75c62016-10-03 08:46:48 +0000565 GetLocation().c_str(),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000566 bss_begin_,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100567 bss_methods_,
568 bss_roots_,
Vladimir Markoaad75c62016-10-03 08:46:48 +0000569 bss_end_);
570 return false;
571 }
572
Vladimir Markoe47f60c2018-02-21 13:43:28 +0000573 if (bss_methods_ != nullptr && bss_methods_ != bss_begin_) {
574 *error_msg = StringPrintf("In oat file '%s' found unexpected .bss gap before 'oatbssmethods': "
575 "begin = %p, methods = %p",
576 GetLocation().c_str(),
577 bss_begin_,
578 bss_methods_);
579 return false;
580 }
581
Vladimir Markob7bf8432019-12-03 13:18:50 +0000582 std::string_view primary_location;
583 std::string_view primary_location_replacement;
584 size_t dex_filenames_pos = 0u;
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100585 uint32_t dex_file_count = GetOatHeader().GetDexFileCount();
586 oat_dex_files_storage_.reserve(dex_file_count);
587 for (size_t i = 0; i < dex_file_count; i++) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100588 uint32_t dex_file_location_size;
589 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_location_size))) {
590 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu truncated after dex file "
591 "location size",
592 GetLocation().c_str(),
593 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700594 return false;
595 }
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100596 if (UNLIKELY(dex_file_location_size == 0U)) {
597 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu with empty location name",
598 GetLocation().c_str(),
599 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700600 return false;
601 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000602 if (UNLIKELY(static_cast<size_t>(End() - oat) < dex_file_location_size)) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100603 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu with truncated dex file "
604 "location",
605 GetLocation().c_str(),
606 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700607 return false;
608 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000609 const char* dex_file_location_data = reinterpret_cast<const char*>(oat);
610 oat += dex_file_location_size;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700611
Vladimir Markob7bf8432019-12-03 13:18:50 +0000612 // Location encoded in the oat file. We will use this for multidex naming.
613 std::string_view oat_dex_file_location(dex_file_location_data, dex_file_location_size);
614 std::string dex_file_location(oat_dex_file_location);
615 bool is_multidex = DexFileLoader::IsMultiDexLocation(dex_file_location.c_str());
Vladimir Marko69944682019-12-09 15:16:39 +0000616 // Check that `is_multidex` does not clash with other indicators. The first dex location
617 // must be primary location and, if we're opening external dex files, the location must
618 // be multi-dex if and only if we already have a dex file opened for it.
619 if ((i == 0 && is_multidex) ||
620 (!external_dex_files_.empty() && (is_multidex != (i < external_dex_files_.size())))) {
621 *error_msg = StringPrintf("In oat file '%s' found unexpected %s location '%s'",
622 GetLocation().c_str(),
623 is_multidex ? "multi-dex" : "primary",
624 dex_file_location.c_str());
625 return false;
626 }
627 // Remember the primary location and, if provided, the replacement from `dex_filenames`.
Vladimir Markob7bf8432019-12-03 13:18:50 +0000628 if (!is_multidex) {
629 primary_location = oat_dex_file_location;
630 if (!dex_filenames.empty()) {
631 if (dex_filenames_pos == dex_filenames.size()) {
632 *error_msg = StringPrintf("In oat file '%s' found excessive primary location '%s'"
633 ", expected only %zu primary locations",
634 GetLocation().c_str(),
635 dex_file_location.c_str(),
636 dex_filenames.size());
637 return false;
638 }
639 primary_location_replacement = dex_filenames[dex_filenames_pos];
640 ++dex_filenames_pos;
641 }
642 }
Vladimir Marko69944682019-12-09 15:16:39 +0000643 // Check that the base location of a multidex location matches the last seen primary location.
Vladimir Markob7bf8432019-12-03 13:18:50 +0000644 if (is_multidex &&
645 (!StartsWith(dex_file_location, primary_location) ||
646 dex_file_location[primary_location.size()] != DexFileLoader::kMultiDexSeparator)) {
647 *error_msg = StringPrintf("In oat file '%s' found unexpected multidex location '%s',"
648 " unrelated to '%s'",
649 GetLocation().c_str(),
650 dex_file_location.c_str(),
651 std::string(primary_location).c_str());
652 return false;
653 }
654 std::string dex_file_name = dex_file_location;
655 if (!dex_filenames.empty()) {
656 dex_file_name.replace(/*pos*/ 0u, primary_location.size(), primary_location_replacement);
657 // If the location does not contain path and matches the file name component,
658 // use the provided file name also as the location.
659 // TODO: Do we need this for anything other than tests?
660 if (dex_file_location.find('/') == std::string::npos &&
661 dex_file_name.size() > dex_file_location.size() &&
662 dex_file_name[dex_file_name.size() - dex_file_location.size() - 1u] == '/' &&
663 EndsWith(dex_file_name, dex_file_location)) {
664 dex_file_location = dex_file_name;
665 }
666 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700667
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100668 uint32_t dex_file_checksum;
669 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_checksum))) {
670 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated after "
671 "dex file checksum",
672 GetLocation().c_str(),
673 i,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700674 dex_file_location.c_str());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700675 return false;
676 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700677
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100678 uint32_t dex_file_offset;
679 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_offset))) {
680 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated "
681 "after dex file offsets",
682 GetLocation().c_str(),
683 i,
684 dex_file_location.c_str());
685 return false;
686 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100687 if (UNLIKELY(dex_file_offset > DexSize())) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100688 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
689 "offset %u > %zu",
690 GetLocation().c_str(),
691 i,
692 dex_file_location.c_str(),
693 dex_file_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100694 DexSize());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700695 return false;
696 }
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000697 const uint8_t* dex_file_pointer = nullptr;
698 if (UNLIKELY(dex_file_offset == 0U)) {
Vladimir Markob7bf8432019-12-03 13:18:50 +0000699 // Do not support mixed-mode oat files.
700 if (i != 0u && external_dex_files_.empty()) {
701 *error_msg = StringPrintf("In oat file '%s', unsupported uncompressed-dex-file for dex "
702 "file %zu (%s)",
703 GetLocation().c_str(),
704 i,
705 dex_file_location.c_str());
706 return false;
707 }
708 DCHECK_LE(i, external_dex_files_.size());
709 if (i == external_dex_files_.size()) {
710 std::vector<std::unique_ptr<const DexFile>> new_dex_files;
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000711 // No dex files, load it from location.
712 const ArtDexFileLoader dex_file_loader;
Nicolas Geoffray30025092018-04-19 14:43:29 +0100713 bool loaded = false;
714 if (zip_fd != -1) {
715 loaded = dex_file_loader.OpenZip(zip_fd,
716 dex_file_location,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100717 /*verify=*/ false,
718 /*verify_checksum=*/ false,
Nicolas Geoffray30025092018-04-19 14:43:29 +0100719 error_msg,
Vladimir Markob7bf8432019-12-03 13:18:50 +0000720 &new_dex_files);
Nicolas Geoffray30025092018-04-19 14:43:29 +0100721 } else {
David Brazdil3e8aae02019-03-26 18:48:02 +0000722 loaded = dex_file_loader.Open(dex_file_name.c_str(),
Nicolas Geoffray30025092018-04-19 14:43:29 +0100723 dex_file_location,
Vladimir Markof4efa9e2018-10-17 14:12:45 +0100724 /*verify=*/ false,
725 /*verify_checksum=*/ false,
Nicolas Geoffray30025092018-04-19 14:43:29 +0100726 error_msg,
Vladimir Markob7bf8432019-12-03 13:18:50 +0000727 &new_dex_files);
Nicolas Geoffray30025092018-04-19 14:43:29 +0100728 }
729 if (!loaded) {
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000730 if (Runtime::Current() == nullptr) {
731 // If there's no runtime, we're running oatdump, so return
732 // a half constructed oat file that oatdump knows how to deal with.
733 LOG(WARNING) << "Could not find associated dex files of oat file. "
734 << "Oatdump will only dump the header.";
735 return true;
736 } else {
737 return false;
738 }
739 }
Andreas Gampefc604a72018-02-08 15:43:37 -0800740 // The oat file may be out of date wrt/ the dex-file location. We need to be defensive
741 // here and ensure that at least the number of dex files still matches.
Vladimir Markob7bf8432019-12-03 13:18:50 +0000742 // If we have a zip_fd, or reached the end of provided `dex_filenames`, we must
743 // load all dex files from that file, otherwise we may open multiple files.
Andreas Gampefc604a72018-02-08 15:43:37 -0800744 // Note: actual checksum comparisons are the duty of the OatFileAssistant and will be
745 // done after loading the OatFile.
Vladimir Markob7bf8432019-12-03 13:18:50 +0000746 size_t max_dex_files = dex_file_count - external_dex_files_.size();
747 bool expect_all =
748 (zip_fd != -1) || (!dex_filenames.empty() && dex_filenames_pos == dex_filenames.size());
749 if (expect_all ? new_dex_files.size() != max_dex_files
750 : new_dex_files.size() > max_dex_files) {
751 *error_msg = StringPrintf("In oat file '%s', expected %s%zu uncompressed dex files, but "
Andreas Gampefc604a72018-02-08 15:43:37 -0800752 "found %zu in '%s'",
753 GetLocation().c_str(),
Vladimir Markob7bf8432019-12-03 13:18:50 +0000754 (expect_all ? "" : "<="),
755 max_dex_files,
756 new_dex_files.size(),
Andreas Gampefc604a72018-02-08 15:43:37 -0800757 dex_file_location.c_str());
758 return false;
759 }
Vladimir Markob7bf8432019-12-03 13:18:50 +0000760 for (std::unique_ptr<const DexFile>& dex_file : new_dex_files) {
761 external_dex_files_.push_back(std::move(dex_file));
762 }
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000763 }
Vladimir Markob7bf8432019-12-03 13:18:50 +0000764 dex_file_pointer = external_dex_files_[i]->Begin();
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000765 } else {
Andreas Gampefc604a72018-02-08 15:43:37 -0800766 // Do not support mixed-mode oat files.
Vladimir Markob7bf8432019-12-03 13:18:50 +0000767 if (!external_dex_files_.empty()) {
Andreas Gampefc604a72018-02-08 15:43:37 -0800768 *error_msg = StringPrintf("In oat file '%s', unsupported embedded dex-file for dex file "
769 "%zu (%s)",
770 GetLocation().c_str(),
771 i,
772 dex_file_location.c_str());
773 return false;
774 }
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000775 if (UNLIKELY(DexSize() - dex_file_offset < sizeof(DexFile::Header))) {
776 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
777 "offset %u of %zu but the size of dex file header is %zu",
778 GetLocation().c_str(),
779 i,
780 dex_file_location.c_str(),
781 dex_file_offset,
782 DexSize(),
783 sizeof(DexFile::Header));
784 return false;
785 }
786 dex_file_pointer = DexBegin() + dex_file_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000787 }
Brian Carlstrom89521892011-12-07 22:05:07 -0800788
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700789 const bool valid_magic = DexFileLoader::IsMagicValid(dex_file_pointer);
Mathieu Chartier7b074bf2017-09-25 16:22:36 -0700790 if (UNLIKELY(!valid_magic)) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100791 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with invalid "
792 "dex file magic '%s'",
793 GetLocation().c_str(),
794 i,
795 dex_file_location.c_str(),
796 dex_file_pointer);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700797 return false;
798 }
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700799 if (UNLIKELY(!DexFileLoader::IsVersionAndMagicValid(dex_file_pointer))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100800 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with invalid "
801 "dex file version '%s'",
802 GetLocation().c_str(),
803 i,
804 dex_file_location.c_str(),
805 dex_file_pointer);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700806 return false;
807 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800808 const DexFile::Header* header = reinterpret_cast<const DexFile::Header*>(dex_file_pointer);
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000809 if (dex_file_offset != 0 && (DexSize() - dex_file_offset < header->file_size_)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000810 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
811 "offset %u and size %u truncated at %zu",
812 GetLocation().c_str(),
813 i,
814 dex_file_location.c_str(),
815 dex_file_offset,
816 header->file_size_,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100817 DexSize());
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000818 return false;
819 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300820
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000821 uint32_t class_offsets_offset;
822 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &class_offsets_offset))) {
823 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated "
824 "after class offsets offset",
825 GetLocation().c_str(),
826 i,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300827 dex_file_location.c_str());
828 return false;
829 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000830 if (UNLIKELY(class_offsets_offset > Size()) ||
831 UNLIKELY((Size() - class_offsets_offset) / sizeof(uint32_t) < header->class_defs_size_)) {
832 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with truncated "
833 "class offsets, offset %u of %zu, class defs %u",
834 GetLocation().c_str(),
835 i,
836 dex_file_location.c_str(),
837 class_offsets_offset,
838 Size(),
839 header->class_defs_size_);
840 return false;
841 }
842 if (UNLIKELY(!IsAligned<alignof(uint32_t)>(class_offsets_offset))) {
843 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with unaligned "
844 "class offsets, offset %u",
845 GetLocation().c_str(),
846 i,
847 dex_file_location.c_str(),
848 class_offsets_offset);
849 return false;
850 }
851 const uint32_t* class_offsets_pointer =
852 reinterpret_cast<const uint32_t*>(Begin() + class_offsets_offset);
853
854 uint32_t lookup_table_offset;
855 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &lookup_table_offset))) {
856 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zd for '%s' truncated "
857 "after lookup table offset",
858 GetLocation().c_str(),
859 i,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300860 dex_file_location.c_str());
861 return false;
862 }
863 const uint8_t* lookup_table_data = lookup_table_offset != 0u
864 ? Begin() + lookup_table_offset
865 : nullptr;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000866 if (lookup_table_offset != 0u &&
867 (UNLIKELY(lookup_table_offset > Size()) ||
868 UNLIKELY(Size() - lookup_table_offset <
869 TypeLookupTable::RawDataLength(header->class_defs_size_)))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100870 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with truncated "
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000871 "type lookup table, offset %u of %zu, class defs %u",
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100872 GetLocation().c_str(),
873 i,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000874 dex_file_location.c_str(),
875 lookup_table_offset,
876 Size(),
877 header->class_defs_size_);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700878 return false;
879 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700880
Mathieu Chartier120aa282017-08-05 16:03:03 -0700881 uint32_t dex_layout_sections_offset;
882 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_layout_sections_offset))) {
883 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zd for '%s' truncated "
884 "after dex layout sections offset",
885 GetLocation().c_str(),
886 i,
887 dex_file_location.c_str());
888 return false;
889 }
890 const DexLayoutSections* const dex_layout_sections = dex_layout_sections_offset != 0
891 ? reinterpret_cast<const DexLayoutSections*>(Begin() + dex_layout_sections_offset)
892 : nullptr;
893
Vladimir Markof3c52b42017-11-17 17:32:12 +0000894 const IndexBssMapping* method_bss_mapping;
895 const IndexBssMapping* type_bss_mapping;
Vladimir Marko8f63f102020-09-28 12:10:28 +0100896 const IndexBssMapping* public_type_bss_mapping;
897 const IndexBssMapping* package_type_bss_mapping;
Vladimir Markof3c52b42017-11-17 17:32:12 +0000898 const IndexBssMapping* string_bss_mapping;
899 if (!ReadIndexBssMapping(
900 this, &oat, i, dex_file_location, "method", &method_bss_mapping, error_msg) ||
901 !ReadIndexBssMapping(
902 this, &oat, i, dex_file_location, "type", &type_bss_mapping, error_msg) ||
903 !ReadIndexBssMapping(
Vladimir Marko8f63f102020-09-28 12:10:28 +0100904 this, &oat, i, dex_file_location, "type", &public_type_bss_mapping, error_msg) ||
905 !ReadIndexBssMapping(
906 this, &oat, i, dex_file_location, "type", &package_type_bss_mapping, error_msg) ||
907 !ReadIndexBssMapping(
Vladimir Markof3c52b42017-11-17 17:32:12 +0000908 this, &oat, i, dex_file_location, "string", &string_bss_mapping, error_msg)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100909 return false;
910 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100911
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100912 // Create the OatDexFile and add it to the owning container.
David Brazdil3e8aae02019-03-26 18:48:02 +0000913 OatDexFile* oat_dex_file = new OatDexFile(
914 this,
915 dex_file_location,
916 DexFileLoader::GetDexCanonicalLocation(dex_file_name.c_str()),
917 dex_file_checksum,
918 dex_file_pointer,
919 lookup_table_data,
920 method_bss_mapping,
921 type_bss_mapping,
Vladimir Marko8f63f102020-09-28 12:10:28 +0100922 public_type_bss_mapping,
923 package_type_bss_mapping,
David Brazdil3e8aae02019-03-26 18:48:02 +0000924 string_bss_mapping,
925 class_offsets_pointer,
926 dex_layout_sections);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100927 oat_dex_files_storage_.push_back(oat_dex_file);
928
929 // Add the location and canonical location (if different) to the oat_dex_files_ table.
Vladimir Markob7bf8432019-12-03 13:18:50 +0000930 // Note: We do not add the non-canonical `dex_file_name`. If it is different from both
931 // the location and canonical location, GetOatDexFile() shall canonicalize it when
932 // requested and match the canonical path.
933 std::string_view key = oat_dex_file_location; // References oat file data.
David Brazdil3e8aae02019-03-26 18:48:02 +0000934 std::string_view canonical_key(oat_dex_file->GetCanonicalDexFileLocation());
Vladimir Marko539690a2014-06-05 18:36:42 +0100935 oat_dex_files_.Put(key, oat_dex_file);
David Brazdil3e8aae02019-03-26 18:48:02 +0000936 if (canonical_key != key) {
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100937 oat_dex_files_.Put(canonical_key, oat_dex_file);
938 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700939 }
Vladimir Markob7bf8432019-12-03 13:18:50 +0000940 if (!dex_filenames.empty() && dex_filenames_pos != dex_filenames.size()) {
941 *error_msg = StringPrintf("Oat file '%s' contains only %zu primary dex locations, expected %zu",
942 GetLocation().c_str(),
943 dex_filenames_pos,
944 dex_filenames.size());
945 return false;
946 }
Vladimir Marko09d09432015-09-08 13:47:48 +0100947
Vladimir Markob066d432018-01-03 13:14:37 +0000948 if (DataBimgRelRoBegin() != nullptr) {
Vladimir Markoe80ecf32019-08-01 15:20:58 +0100949 // Make .data.bimg.rel.ro read only. ClassLinker shall temporarily make it writable for
950 // relocation when we register a dex file from this oat file. We do not do the relocation
951 // here to avoid dirtying the pages if the code is never actually ready to be executed.
Vladimir Markob066d432018-01-03 13:14:37 +0000952 uint8_t* reloc_begin = const_cast<uint8_t*>(DataBimgRelRoBegin());
953 CheckedCall(mprotect, "protect relocations", reloc_begin, DataBimgRelRoSize(), PROT_READ);
Vladimir Markoe80ecf32019-08-01 15:20:58 +0100954 // Make sure the file lists a boot image dependency, otherwise the .data.bimg.rel.ro
955 // section is bogus. The full dependency is checked before the code is executed.
Vladimir Marko21910692019-11-06 13:27:03 +0000956 // We cannot do this check if we do not have a key-value store, i.e. for secondary
957 // oat files for boot image extensions.
958 if (GetOatHeader().GetKeyValueStoreSize() != 0u) {
959 const char* boot_class_path_checksum =
960 GetOatHeader().GetStoreValueByKey(OatHeader::kBootClassPathChecksumsKey);
961 if (boot_class_path_checksum == nullptr ||
962 boot_class_path_checksum[0] != gc::space::ImageSpace::kImageChecksumPrefix) {
963 *error_msg = StringPrintf("Oat file '%s' contains .data.bimg.rel.ro section "
964 "without boot image dependency.",
965 GetLocation().c_str());
966 return false;
967 }
Vladimir Markob066d432018-01-03 13:14:37 +0000968 }
969 }
970
Brian Carlstromf1b30302013-03-28 10:35:32 -0700971 return true;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700972}
973
Andreas Gampe049cff02015-12-01 23:27:12 -0800974////////////////////////
975// OatFile via dlopen //
976////////////////////////
977
Roland Levillainbbc6e7e2018-08-24 16:58:47 +0100978class DlOpenOatFile final : public OatFileBase {
Andreas Gampe049cff02015-12-01 23:27:12 -0800979 public:
980 DlOpenOatFile(const std::string& filename, bool executable)
981 : OatFileBase(filename, executable),
982 dlopen_handle_(nullptr),
Richard Uhlera206c742016-05-24 15:04:22 -0700983 shared_objects_before_(0) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800984 }
985
986 ~DlOpenOatFile() {
987 if (dlopen_handle_ != nullptr) {
Richard Uhlera206c742016-05-24 15:04:22 -0700988 if (!kIsTargetBuild) {
989 MutexLock mu(Thread::Current(), *Locks::host_dlopen_handles_lock_);
990 host_dlopen_handles_.erase(dlopen_handle_);
Mathieu Chartierc7d3f4b2016-06-01 10:48:19 -0700991 dlclose(dlopen_handle_);
992 } else {
993 dlclose(dlopen_handle_);
Richard Uhlera206c742016-05-24 15:04:22 -0700994 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800995 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800996 }
997
998 protected:
999 const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001000 std::string* error_msg) const override {
Andreas Gampe049cff02015-12-01 23:27:12 -08001001 const uint8_t* ptr =
1002 reinterpret_cast<const uint8_t*>(dlsym(dlopen_handle_, symbol_name.c_str()));
1003 if (ptr == nullptr) {
1004 *error_msg = dlerror();
1005 }
1006 return ptr;
1007 }
1008
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001009 void PreLoad() override;
Andreas Gampe4075f832016-05-18 13:09:54 -07001010
Andreas Gampe049cff02015-12-01 23:27:12 -08001011 bool Load(const std::string& elf_filename,
Andreas Gampe049cff02015-12-01 23:27:12 -08001012 bool writable,
1013 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001014 bool low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001015 /*inout*/MemMap* reservation, // Where to load if not null.
1016 /*out*/std::string* error_msg) override;
Andreas Gampe049cff02015-12-01 23:27:12 -08001017
Vladimir Markoc09cd052018-08-23 16:36:36 +01001018 bool Load(int oat_fd ATTRIBUTE_UNUSED,
1019 bool writable ATTRIBUTE_UNUSED,
1020 bool executable ATTRIBUTE_UNUSED,
1021 bool low_4gb ATTRIBUTE_UNUSED,
1022 /*inout*/MemMap* reservation ATTRIBUTE_UNUSED,
1023 /*out*/std::string* error_msg ATTRIBUTE_UNUSED) override {
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001024 return false;
1025 }
1026
Andreas Gampe049cff02015-12-01 23:27:12 -08001027 // Ask the linker where it mmaped the file and notify our mmap wrapper of the regions.
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001028 void PreSetup(const std::string& elf_filename) override;
Andreas Gampe049cff02015-12-01 23:27:12 -08001029
1030 private:
1031 bool Dlopen(const std::string& elf_filename,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001032 /*inout*/MemMap* reservation, // Where to load if not null.
1033 /*out*/std::string* error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -08001034
Richard Uhlera206c742016-05-24 15:04:22 -07001035 // On the host, if the same library is loaded again with dlopen the same
1036 // file handle is returned. This differs from the behavior of dlopen on the
1037 // target, where dlopen reloads the library at a different address every
1038 // time you load it. The runtime relies on the target behavior to ensure
1039 // each instance of the loaded library has a unique dex cache. To avoid
1040 // problems, we fall back to our own linker in the case when the same
1041 // library is opened multiple times on host. dlopen_handles_ is used to
1042 // detect that case.
1043 // Guarded by host_dlopen_handles_lock_;
1044 static std::unordered_set<void*> host_dlopen_handles_;
1045
Vladimir Marko07f78902020-07-27 11:35:12 +00001046 // Reservation and placeholder memory map objects corresponding to the regions mapped by dlopen.
Vladimir Markoc09cd052018-08-23 16:36:36 +01001047 // Note: Must be destroyed after dlclose() as it can hold the owning reservation.
1048 std::vector<MemMap> dlopen_mmaps_;
1049
Andreas Gampe049cff02015-12-01 23:27:12 -08001050 // dlopen handle during runtime.
1051 void* dlopen_handle_; // TODO: Unique_ptr with custom deleter.
1052
Andreas Gampe4075f832016-05-18 13:09:54 -07001053 // The number of shared objects the linker told us about before loading. Used to
1054 // (optimistically) optimize the PreSetup stage (see comment there).
1055 size_t shared_objects_before_;
1056
Andreas Gampe049cff02015-12-01 23:27:12 -08001057 DISALLOW_COPY_AND_ASSIGN(DlOpenOatFile);
1058};
1059
Richard Uhlera206c742016-05-24 15:04:22 -07001060std::unordered_set<void*> DlOpenOatFile::host_dlopen_handles_;
1061
Andreas Gampe4075f832016-05-18 13:09:54 -07001062void DlOpenOatFile::PreLoad() {
1063#ifdef __APPLE__
Andreas Gampe39004a62016-05-18 21:27:00 -07001064 UNUSED(shared_objects_before_);
Andreas Gampe4075f832016-05-18 13:09:54 -07001065 LOG(FATAL) << "Should not reach here.";
1066 UNREACHABLE();
1067#else
1068 // Count the entries in dl_iterate_phdr we get at this point in time.
1069 struct dl_iterate_context {
Vladimir Markoc09cd052018-08-23 16:36:36 +01001070 static int callback(dl_phdr_info* info ATTRIBUTE_UNUSED,
Andreas Gampe4075f832016-05-18 13:09:54 -07001071 size_t size ATTRIBUTE_UNUSED,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001072 void* data) {
Andreas Gampe4075f832016-05-18 13:09:54 -07001073 reinterpret_cast<dl_iterate_context*>(data)->count++;
1074 return 0; // Continue iteration.
1075 }
1076 size_t count = 0;
1077 } context;
1078
1079 dl_iterate_phdr(dl_iterate_context::callback, &context);
1080 shared_objects_before_ = context.count;
1081#endif
1082}
1083
Andreas Gampe049cff02015-12-01 23:27:12 -08001084bool DlOpenOatFile::Load(const std::string& elf_filename,
Andreas Gampe049cff02015-12-01 23:27:12 -08001085 bool writable,
1086 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001087 bool low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001088 /*inout*/MemMap* reservation, // Where to load if not null.
1089 /*out*/std::string* error_msg) {
Andreas Gampe049cff02015-12-01 23:27:12 -08001090 // Use dlopen only when flagged to do so, and when it's OK to load things executable.
1091 // TODO: Also try when not executable? The issue here could be re-mapping as writable (as
1092 // !executable is a sign that we may want to patch), which may not be allowed for
1093 // various reasons.
1094 if (!kUseDlopen) {
1095 *error_msg = "DlOpen is disabled.";
1096 return false;
1097 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001098 if (low_4gb) {
1099 *error_msg = "DlOpen does not support low 4gb loading.";
1100 return false;
1101 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001102 if (writable) {
1103 *error_msg = "DlOpen does not support writable loading.";
1104 return false;
1105 }
1106 if (!executable) {
1107 *error_msg = "DlOpen does not support non-executable loading.";
1108 return false;
1109 }
1110
1111 // dlopen always returns the same library if it is already opened on the host. For this reason
1112 // we only use dlopen if we are the target or we do not already have the dex file opened. Having
1113 // the same library loaded multiple times at different addresses is required for class unloading
1114 // and for having dex caches arrays in the .bss section.
1115 if (!kIsTargetBuild) {
1116 if (!kUseDlopenOnHost) {
1117 *error_msg = "DlOpen disabled for host.";
1118 return false;
1119 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001120 }
1121
Vladimir Markoc09cd052018-08-23 16:36:36 +01001122 bool success = Dlopen(elf_filename, reservation, error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -08001123 DCHECK(dlopen_handle_ != nullptr || !success);
1124
1125 return success;
1126}
1127
1128bool DlOpenOatFile::Dlopen(const std::string& elf_filename,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001129 /*inout*/MemMap* reservation,
1130 /*out*/std::string* error_msg) {
Andreas Gampe049cff02015-12-01 23:27:12 -08001131#ifdef __APPLE__
1132 // The dl_iterate_phdr syscall is missing. There is similar API on OSX,
1133 // but let's fallback to the custom loading code for the time being.
Vladimir Marko3ec8fb62018-08-31 17:47:38 +01001134 UNUSED(elf_filename, reservation);
Andreas Gampe049cff02015-12-01 23:27:12 -08001135 *error_msg = "Dlopen unsupported on Mac.";
1136 return false;
1137#else
1138 {
1139 UniqueCPtr<char> absolute_path(realpath(elf_filename.c_str(), nullptr));
1140 if (absolute_path == nullptr) {
1141 *error_msg = StringPrintf("Failed to find absolute path for '%s'", elf_filename.c_str());
1142 return false;
1143 }
Bilyan Borisovbb661c02016-04-04 16:27:32 +01001144#ifdef ART_TARGET_ANDROID
Anton Kirilov3a2e78e2017-01-06 13:33:42 +00001145 android_dlextinfo extinfo = {};
Vladimir Markof6cfd002018-11-01 16:53:31 +00001146 extinfo.flags = ANDROID_DLEXT_FORCE_LOAD; // Force-load, don't reuse handle
1147 // (open oat files multiple times).
Vladimir Markoc09cd052018-08-23 16:36:36 +01001148 if (reservation != nullptr) {
1149 if (!reservation->IsValid()) {
1150 *error_msg = StringPrintf("Invalid reservation for %s", elf_filename.c_str());
1151 return false;
1152 }
1153 extinfo.flags |= ANDROID_DLEXT_RESERVED_ADDRESS; // Use the reserved memory range.
1154 extinfo.reserved_addr = reservation->Begin();
1155 extinfo.reserved_size = reservation->Size();
1156 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001157 dlopen_handle_ = android_dlopen_ext(absolute_path.get(), RTLD_NOW, &extinfo);
Vladimir Markoc09cd052018-08-23 16:36:36 +01001158 if (reservation != nullptr && dlopen_handle_ != nullptr) {
1159 // Find used pages from the reservation.
1160 struct dl_iterate_context {
1161 static int callback(dl_phdr_info* info, size_t size ATTRIBUTE_UNUSED, void* data) {
1162 auto* context = reinterpret_cast<dl_iterate_context*>(data);
1163 static_assert(std::is_same<Elf32_Half, Elf64_Half>::value, "Half must match");
1164 using Elf_Half = Elf64_Half;
1165
1166 // See whether this callback corresponds to the file which we have just loaded.
1167 uint8_t* reservation_begin = context->reservation->Begin();
1168 bool contained_in_reservation = false;
1169 for (Elf_Half i = 0; i < info->dlpi_phnum; i++) {
1170 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
1171 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
1172 info->dlpi_phdr[i].p_vaddr);
1173 size_t memsz = info->dlpi_phdr[i].p_memsz;
1174 size_t offset = static_cast<size_t>(vaddr - reservation_begin);
1175 if (offset < context->reservation->Size()) {
1176 contained_in_reservation = true;
1177 DCHECK_LE(memsz, context->reservation->Size() - offset);
1178 } else if (vaddr < reservation_begin) {
1179 // Check that there's no overlap with the reservation.
1180 DCHECK_LE(memsz, static_cast<size_t>(reservation_begin - vaddr));
1181 }
1182 break; // It is sufficient to check the first PT_LOAD header.
1183 }
1184 }
1185
1186 if (contained_in_reservation) {
1187 for (Elf_Half i = 0; i < info->dlpi_phnum; i++) {
1188 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
1189 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
1190 info->dlpi_phdr[i].p_vaddr);
1191 size_t memsz = info->dlpi_phdr[i].p_memsz;
1192 size_t offset = static_cast<size_t>(vaddr - reservation_begin);
1193 DCHECK_LT(offset, context->reservation->Size());
1194 DCHECK_LE(memsz, context->reservation->Size() - offset);
1195 context->max_size = std::max(context->max_size, offset + memsz);
1196 }
1197 }
1198
1199 return 1; // Stop iteration and return 1 from dl_iterate_phdr.
1200 }
1201 return 0; // Continue iteration and return 0 from dl_iterate_phdr when finished.
1202 }
1203
1204 const MemMap* const reservation;
1205 size_t max_size = 0u;
1206 };
1207 dl_iterate_context context = { reservation };
1208
1209 if (dl_iterate_phdr(dl_iterate_context::callback, &context) == 0) {
1210 LOG(FATAL) << "Could not find the shared object mmapped to the reservation.";
1211 UNREACHABLE();
1212 }
1213
1214 // Take ownership of the memory used by the shared object. dlopen() does not assume
1215 // full ownership of this memory and dlclose() shall just remap it as zero pages with
1216 // PROT_NONE. We need to unmap the memory when destroying this oat file.
1217 dlopen_mmaps_.push_back(reservation->TakeReservedMemory(context.max_size));
1218 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001219#else
Steve Austin882ed6b2018-06-08 11:40:38 -07001220 static_assert(!kIsTargetBuild || kIsTargetLinux || kIsTargetFuchsia,
1221 "host_dlopen_handles_ will leak handles");
Vladimir Markoc09cd052018-08-23 16:36:36 +01001222 if (reservation != nullptr) {
1223 *error_msg = StringPrintf("dlopen() into reserved memory is unsupported on host for '%s'.",
1224 elf_filename.c_str());
1225 return false;
1226 }
Mathieu Chartierc7d3f4b2016-06-01 10:48:19 -07001227 MutexLock mu(Thread::Current(), *Locks::host_dlopen_handles_lock_);
Richard Uhlera206c742016-05-24 15:04:22 -07001228 dlopen_handle_ = dlopen(absolute_path.get(), RTLD_NOW);
1229 if (dlopen_handle_ != nullptr) {
Richard Uhlera206c742016-05-24 15:04:22 -07001230 if (!host_dlopen_handles_.insert(dlopen_handle_).second) {
1231 dlclose(dlopen_handle_);
1232 dlopen_handle_ = nullptr;
1233 *error_msg = StringPrintf("host dlopen re-opened '%s'", elf_filename.c_str());
1234 return false;
1235 }
1236 }
Bilyan Borisovbb661c02016-04-04 16:27:32 +01001237#endif // ART_TARGET_ANDROID
Andreas Gampe049cff02015-12-01 23:27:12 -08001238 }
1239 if (dlopen_handle_ == nullptr) {
1240 *error_msg = StringPrintf("Failed to dlopen '%s': %s", elf_filename.c_str(), dlerror());
1241 return false;
1242 }
1243 return true;
1244#endif
1245}
1246
1247void DlOpenOatFile::PreSetup(const std::string& elf_filename) {
Andreas Gampe74f07b52015-12-02 11:53:26 -08001248#ifdef __APPLE__
1249 UNUSED(elf_filename);
1250 LOG(FATAL) << "Should not reach here.";
1251 UNREACHABLE();
1252#else
Vladimir Marko07f78902020-07-27 11:35:12 +00001253 struct PlaceholderMapData {
Vladimir Marko211f9d32020-05-21 16:10:44 +01001254 const char* name;
1255 uint8_t* vaddr;
1256 size_t memsz;
1257 };
Andreas Gampe049cff02015-12-01 23:27:12 -08001258 struct dl_iterate_context {
Vladimir Markoc09cd052018-08-23 16:36:36 +01001259 static int callback(dl_phdr_info* info, size_t size ATTRIBUTE_UNUSED, void* data) {
Andreas Gampe049cff02015-12-01 23:27:12 -08001260 auto* context = reinterpret_cast<dl_iterate_context*>(data);
Vladimir Markoc09cd052018-08-23 16:36:36 +01001261 static_assert(std::is_same<Elf32_Half, Elf64_Half>::value, "Half must match");
1262 using Elf_Half = Elf64_Half;
1263
Andreas Gampe4075f832016-05-18 13:09:54 -07001264 context->shared_objects_seen++;
1265 if (context->shared_objects_seen < context->shared_objects_before) {
1266 // We haven't been called yet for anything we haven't seen before. Just continue.
1267 // Note: this is aggressively optimistic. If another thread was unloading a library,
1268 // we may miss out here. However, this does not happen often in practice.
1269 return 0;
1270 }
1271
Andreas Gampe049cff02015-12-01 23:27:12 -08001272 // See whether this callback corresponds to the file which we have just loaded.
1273 bool contains_begin = false;
Vladimir Markoc09cd052018-08-23 16:36:36 +01001274 for (Elf_Half i = 0; i < info->dlpi_phnum; i++) {
Andreas Gampe049cff02015-12-01 23:27:12 -08001275 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
1276 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
1277 info->dlpi_phdr[i].p_vaddr);
1278 size_t memsz = info->dlpi_phdr[i].p_memsz;
1279 if (vaddr <= context->begin_ && context->begin_ < vaddr + memsz) {
1280 contains_begin = true;
1281 break;
1282 }
1283 }
1284 }
Vladimir Marko07f78902020-07-27 11:35:12 +00001285 // Add placeholder mmaps for this file.
Andreas Gampe049cff02015-12-01 23:27:12 -08001286 if (contains_begin) {
Vladimir Markoc09cd052018-08-23 16:36:36 +01001287 for (Elf_Half i = 0; i < info->dlpi_phnum; i++) {
Andreas Gampe049cff02015-12-01 23:27:12 -08001288 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
1289 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
1290 info->dlpi_phdr[i].p_vaddr);
1291 size_t memsz = info->dlpi_phdr[i].p_memsz;
Vladimir Marko211f9d32020-05-21 16:10:44 +01001292 size_t name_size = strlen(info->dlpi_name) + 1u;
Vladimir Marko07f78902020-07-27 11:35:12 +00001293 std::vector<char>* placeholder_maps_names = context->placeholder_maps_names_;
Vladimir Marko211f9d32020-05-21 16:10:44 +01001294 // We must not allocate any memory in the callback, see b/156312036 .
Vladimir Marko07f78902020-07-27 11:35:12 +00001295 if (name_size < placeholder_maps_names->capacity() - placeholder_maps_names->size() &&
1296 context->placeholder_maps_data_->size() <
1297 context->placeholder_maps_data_->capacity()) {
1298 placeholder_maps_names->insert(
1299 placeholder_maps_names->end(), info->dlpi_name, info->dlpi_name + name_size);
1300 const char* name =
1301 &(*placeholder_maps_names)[placeholder_maps_names->size() - name_size];
1302 context->placeholder_maps_data_->push_back({ name, vaddr, memsz });
Vladimir Marko211f9d32020-05-21 16:10:44 +01001303 }
Vladimir Marko07f78902020-07-27 11:35:12 +00001304 context->num_placeholder_maps_ += 1u;
1305 context->placeholder_maps_names_size_ += name_size;
Andreas Gampe049cff02015-12-01 23:27:12 -08001306 }
1307 }
1308 return 1; // Stop iteration and return 1 from dl_iterate_phdr.
1309 }
1310 return 0; // Continue iteration and return 0 from dl_iterate_phdr when finished.
1311 }
1312 const uint8_t* const begin_;
Vladimir Marko07f78902020-07-27 11:35:12 +00001313 std::vector<PlaceholderMapData>* placeholder_maps_data_;
1314 size_t num_placeholder_maps_;
1315 std::vector<char>* placeholder_maps_names_;
1316 size_t placeholder_maps_names_size_;
Vladimir Marko211f9d32020-05-21 16:10:44 +01001317 size_t shared_objects_before;
Andreas Gampe4075f832016-05-18 13:09:54 -07001318 size_t shared_objects_seen;
1319 };
Vladimir Marko211f9d32020-05-21 16:10:44 +01001320
1321 // We must not allocate any memory in the callback, see b/156312036 .
Vladimir Marko07f78902020-07-27 11:35:12 +00001322 // Therefore we pre-allocate storage for the data we need for creating the placeholder maps.
1323 std::vector<PlaceholderMapData> placeholder_maps_data;
1324 placeholder_maps_data.reserve(32); // 32 should be enough. If not, we'll retry.
1325 std::vector<char> placeholder_maps_names;
1326 placeholder_maps_names.reserve(4 * KB); // 4KiB should be enough. If not, we'll retry.
Vladimir Marko211f9d32020-05-21 16:10:44 +01001327
1328 dl_iterate_context context = {
1329 Begin(),
Vladimir Marko07f78902020-07-27 11:35:12 +00001330 &placeholder_maps_data,
1331 /*num_placeholder_maps_*/ 0u,
1332 &placeholder_maps_names,
1333 /*placeholder_maps_names_size_*/ 0u,
Vladimir Marko211f9d32020-05-21 16:10:44 +01001334 shared_objects_before_,
1335 /*shared_objects_seen*/ 0u
1336 };
Andreas Gampe049cff02015-12-01 23:27:12 -08001337
1338 if (dl_iterate_phdr(dl_iterate_context::callback, &context) == 0) {
Andreas Gampe4075f832016-05-18 13:09:54 -07001339 // Hm. Maybe our optimization went wrong. Try another time with shared_objects_before == 0
1340 // before giving up. This should be unusual.
1341 VLOG(oat) << "Need a second run in PreSetup, didn't find with shared_objects_before="
1342 << shared_objects_before_;
Vladimir Marko07f78902020-07-27 11:35:12 +00001343 DCHECK(placeholder_maps_data.empty());
1344 DCHECK_EQ(context.num_placeholder_maps_, 0u);
1345 DCHECK(placeholder_maps_names.empty());
1346 DCHECK_EQ(context.placeholder_maps_names_size_, 0u);
Vladimir Marko211f9d32020-05-21 16:10:44 +01001347 context.shared_objects_before = 0u;
1348 context.shared_objects_seen = 0u;
1349 if (dl_iterate_phdr(dl_iterate_context::callback, &context) == 0) {
Andreas Gampe4075f832016-05-18 13:09:54 -07001350 // OK, give up and print an error.
Andreas Gampe170331f2017-12-07 18:41:03 -08001351 PrintFileToLog("/proc/self/maps", android::base::LogSeverity::WARNING);
Andreas Gampe4075f832016-05-18 13:09:54 -07001352 LOG(ERROR) << "File " << elf_filename << " loaded with dlopen but cannot find its mmaps.";
1353 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001354 }
Vladimir Marko211f9d32020-05-21 16:10:44 +01001355
Vladimir Marko07f78902020-07-27 11:35:12 +00001356 if (placeholder_maps_data.size() < context.num_placeholder_maps_) {
Vladimir Marko211f9d32020-05-21 16:10:44 +01001357 // Insufficient capacity. Reserve more space and retry.
Vladimir Marko07f78902020-07-27 11:35:12 +00001358 placeholder_maps_data.clear();
1359 placeholder_maps_data.reserve(context.num_placeholder_maps_);
1360 context.num_placeholder_maps_ = 0u;
1361 placeholder_maps_names.clear();
1362 placeholder_maps_names.reserve(context.placeholder_maps_names_size_);
1363 context.placeholder_maps_names_size_ = 0u;
Vladimir Marko211f9d32020-05-21 16:10:44 +01001364 context.shared_objects_before = 0u;
1365 context.shared_objects_seen = 0u;
1366 bool success = (dl_iterate_phdr(dl_iterate_context::callback, &context) != 0);
1367 CHECK(success);
1368 }
1369
Vladimir Marko07f78902020-07-27 11:35:12 +00001370 CHECK_EQ(placeholder_maps_data.size(), context.num_placeholder_maps_);
1371 CHECK_EQ(placeholder_maps_names.size(), context.placeholder_maps_names_size_);
1372 DCHECK_EQ(static_cast<size_t>(std::count(placeholder_maps_names.begin(),
1373 placeholder_maps_names.end(), '\0')),
1374 context.num_placeholder_maps_);
1375 for (const PlaceholderMapData& data : placeholder_maps_data) {
1376 MemMap mmap = MemMap::MapPlaceholder(data.name, data.vaddr, data.memsz);
Vladimir Marko211f9d32020-05-21 16:10:44 +01001377 dlopen_mmaps_.push_back(std::move(mmap));
1378 }
Andreas Gampe74f07b52015-12-02 11:53:26 -08001379#endif
Andreas Gampe049cff02015-12-01 23:27:12 -08001380}
1381
1382////////////////////////////////////////////////
1383// OatFile via our own ElfFile implementation //
1384////////////////////////////////////////////////
1385
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001386class ElfOatFile final : public OatFileBase {
Andreas Gampe049cff02015-12-01 23:27:12 -08001387 public:
1388 ElfOatFile(const std::string& filename, bool executable) : OatFileBase(filename, executable) {}
1389
Nicolas Geoffray30025092018-04-19 14:43:29 +01001390 bool InitializeFromElfFile(int zip_fd,
1391 ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +01001392 VdexFile* vdex_file,
Vladimir Markob7bf8432019-12-03 13:18:50 +00001393 ArrayRef<const std::string> dex_filenames,
Andreas Gampe049cff02015-12-01 23:27:12 -08001394 std::string* error_msg);
1395
1396 protected:
1397 const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001398 std::string* error_msg) const override {
Andreas Gampe049cff02015-12-01 23:27:12 -08001399 const uint8_t* ptr = elf_file_->FindDynamicSymbolAddress(symbol_name);
1400 if (ptr == nullptr) {
1401 *error_msg = "(Internal implementation could not find symbol)";
1402 }
1403 return ptr;
1404 }
1405
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001406 void PreLoad() override {
Andreas Gampe4075f832016-05-18 13:09:54 -07001407 }
1408
Andreas Gampe049cff02015-12-01 23:27:12 -08001409 bool Load(const std::string& elf_filename,
Andreas Gampe049cff02015-12-01 23:27:12 -08001410 bool writable,
1411 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001412 bool low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001413 /*inout*/MemMap* reservation, // Where to load if not null.
1414 /*out*/std::string* error_msg) override;
Andreas Gampe049cff02015-12-01 23:27:12 -08001415
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001416 bool Load(int oat_fd,
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001417 bool writable,
1418 bool executable,
1419 bool low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001420 /*inout*/MemMap* reservation, // Where to load if not null.
1421 /*out*/std::string* error_msg) override;
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001422
Roland Levillainbbc6e7e2018-08-24 16:58:47 +01001423 void PreSetup(const std::string& elf_filename ATTRIBUTE_UNUSED) override {
Andreas Gampe049cff02015-12-01 23:27:12 -08001424 }
1425
1426 private:
1427 bool ElfFileOpen(File* file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001428 bool writable,
1429 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001430 bool low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001431 /*inout*/MemMap* reservation, // Where to load if not null.
1432 /*out*/std::string* error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -08001433
1434 private:
1435 // Backing memory map for oat file during cross compilation.
1436 std::unique_ptr<ElfFile> elf_file_;
1437
1438 DISALLOW_COPY_AND_ASSIGN(ElfOatFile);
1439};
1440
Nicolas Geoffray30025092018-04-19 14:43:29 +01001441bool ElfOatFile::InitializeFromElfFile(int zip_fd,
1442 ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +01001443 VdexFile* vdex_file,
Vladimir Markob7bf8432019-12-03 13:18:50 +00001444 ArrayRef<const std::string> dex_filenames,
Andreas Gampe049cff02015-12-01 23:27:12 -08001445 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001446 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -08001447 if (IsExecutable()) {
1448 *error_msg = "Cannot initialize from elf file in executable mode.";
1449 return false;
1450 }
1451 elf_file_.reset(elf_file);
David Brazdilc93b3be2016-09-12 18:49:58 +01001452 SetVdex(vdex_file);
Andreas Gampe049cff02015-12-01 23:27:12 -08001453 uint64_t offset, size;
1454 bool has_section = elf_file->GetSectionOffsetAndSize(".rodata", &offset, &size);
1455 CHECK(has_section);
1456 SetBegin(elf_file->Begin() + offset);
1457 SetEnd(elf_file->Begin() + size + offset);
1458 // Ignore the optional .bss section when opening non-executable.
Vladimir Markob7bf8432019-12-03 13:18:50 +00001459 return Setup(zip_fd, dex_filenames, error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -08001460}
1461
1462bool ElfOatFile::Load(const std::string& elf_filename,
Andreas Gampe049cff02015-12-01 23:27:12 -08001463 bool writable,
1464 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001465 bool low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001466 /*inout*/MemMap* reservation,
1467 /*out*/std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001468 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -08001469 std::unique_ptr<File> file(OS::OpenFileForReading(elf_filename.c_str()));
1470 if (file == nullptr) {
1471 *error_msg = StringPrintf("Failed to open oat filename for reading: %s", strerror(errno));
1472 return false;
1473 }
1474 return ElfOatFile::ElfFileOpen(file.get(),
Andreas Gampe049cff02015-12-01 23:27:12 -08001475 writable,
1476 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001477 low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001478 reservation,
Andreas Gampe049cff02015-12-01 23:27:12 -08001479 error_msg);
1480}
1481
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001482bool ElfOatFile::Load(int oat_fd,
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001483 bool writable,
1484 bool executable,
1485 bool low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001486 /*inout*/MemMap* reservation,
1487 /*out*/std::string* error_msg) {
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001488 ScopedTrace trace(__PRETTY_FUNCTION__);
1489 if (oat_fd != -1) {
Josh Gaoafeec9f2018-08-30 14:05:56 -07001490 int duped_fd = DupCloexec(oat_fd);
1491 std::unique_ptr<File> file = std::make_unique<File>(duped_fd, false);
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001492 if (file == nullptr) {
1493 *error_msg = StringPrintf("Failed to open oat filename for reading: %s",
1494 strerror(errno));
1495 return false;
1496 }
1497 return ElfOatFile::ElfFileOpen(file.get(),
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001498 writable,
1499 executable,
1500 low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001501 reservation,
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001502 error_msg);
1503 }
1504 return false;
1505}
1506
Andreas Gampe049cff02015-12-01 23:27:12 -08001507bool ElfOatFile::ElfFileOpen(File* file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001508 bool writable,
1509 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001510 bool low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001511 /*inout*/MemMap* reservation,
1512 /*out*/std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001513 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -08001514 elf_file_.reset(ElfFile::Open(file,
1515 writable,
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001516 /*program_header_only=*/ true,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001517 low_4gb,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001518 error_msg));
Andreas Gampe049cff02015-12-01 23:27:12 -08001519 if (elf_file_ == nullptr) {
1520 DCHECK(!error_msg->empty());
1521 return false;
1522 }
Vladimir Markoc09cd052018-08-23 16:36:36 +01001523 bool loaded = elf_file_->Load(file, executable, low_4gb, reservation, error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -08001524 DCHECK(loaded || !error_msg->empty());
1525 return loaded;
1526}
1527
David Brazdil7126c5b2019-03-05 00:02:51 +00001528class OatFileBackedByVdex final : public OatFileBase {
1529 public:
1530 explicit OatFileBackedByVdex(const std::string& filename)
1531 : OatFileBase(filename, /*executable=*/ false) {}
1532
1533 static OatFileBackedByVdex* Open(const std::vector<const DexFile*>& dex_files,
1534 std::unique_ptr<VdexFile>&& vdex_file,
1535 const std::string& location) {
1536 std::unique_ptr<OatFileBackedByVdex> oat_file(new OatFileBackedByVdex(location));
Nicolas Geoffray16f60dc2021-02-16 15:35:16 +00001537 // SetVdex will take ownership of the VdexFile.
1538 oat_file->SetVdex(vdex_file.release());
1539 oat_file->SetupHeader(dex_files.size());
1540 // Initialize OatDexFiles.
1541 oat_file->Setup(dex_files);
David Brazdil7126c5b2019-03-05 00:02:51 +00001542 return oat_file.release();
1543 }
1544
Nicolas Geoffray16f60dc2021-02-16 15:35:16 +00001545 static OatFileBackedByVdex* Open(int zip_fd,
1546 std::unique_ptr<VdexFile>&& vdex_file,
1547 const std::string& dex_location,
1548 std::string* error_msg) {
1549 std::unique_ptr<OatFileBackedByVdex> oat_file(new OatFileBackedByVdex(vdex_file->GetName()));
1550 if (vdex_file->HasDexSection()) {
1551 uint32_t i = 0;
Nicolas Geoffraya129d8a2021-03-18 22:23:04 +00001552 for (const uint8_t* dex_file_start = vdex_file->GetNextDexFileData(nullptr, i);
Nicolas Geoffray16f60dc2021-02-16 15:35:16 +00001553 dex_file_start != nullptr;
Nicolas Geoffraya129d8a2021-03-18 22:23:04 +00001554 dex_file_start = vdex_file->GetNextDexFileData(dex_file_start, ++i)) {
Nicolas Geoffray16f60dc2021-02-16 15:35:16 +00001555 // Create the OatDexFile and add it to the owning container.
1556 std::string location = DexFileLoader::GetMultiDexLocation(i, dex_location.c_str());
1557 std::string canonical_location = DexFileLoader::GetDexCanonicalLocation(location.c_str());
1558 OatDexFile* oat_dex_file = new OatDexFile(oat_file.get(),
1559 dex_file_start,
1560 vdex_file->GetLocationChecksum(i),
1561 location,
1562 canonical_location);
1563 oat_file->oat_dex_files_storage_.push_back(oat_dex_file);
1564
1565 std::string_view key(oat_dex_file->GetDexFileLocation());
1566 oat_file->oat_dex_files_.Put(key, oat_dex_file);
1567 if (canonical_location != location) {
1568 std::string_view canonical_key(oat_dex_file->GetCanonicalDexFileLocation());
1569 oat_file->oat_dex_files_.Put(canonical_key, oat_dex_file);
1570 }
1571 }
1572 oat_file->SetupHeader(oat_file->oat_dex_files_storage_.size());
1573 } else {
1574 // No need for any verification when loading dex files as we already have
1575 // a vdex file.
1576 const ArtDexFileLoader dex_file_loader;
1577 bool loaded = false;
1578 if (zip_fd != -1) {
1579 loaded = dex_file_loader.OpenZip(zip_fd,
1580 dex_location,
1581 /*verify=*/ false,
1582 /*verify_checksum=*/ false,
1583 error_msg,
1584 &oat_file->external_dex_files_);
1585 } else {
1586 loaded = dex_file_loader.Open(dex_location.c_str(),
1587 dex_location,
1588 /*verify=*/ false,
1589 /*verify_checksum=*/ false,
1590 error_msg,
1591 &oat_file->external_dex_files_);
1592 }
1593 if (!loaded) {
1594 return nullptr;
1595 }
1596 oat_file->SetupHeader(oat_file->external_dex_files_.size());
1597 oat_file->Setup(MakeNonOwningPointerVector(oat_file->external_dex_files_));
1598 }
David Brazdil7126c5b2019-03-05 00:02:51 +00001599
1600 // SetVdex will take ownership of the VdexFile.
Nicolas Geoffray16f60dc2021-02-16 15:35:16 +00001601 oat_file->SetVdex(vdex_file.release());
1602 return oat_file.release();
1603 }
1604
1605 void SetupHeader(size_t number_of_dex_files) {
1606 DCHECK(!IsExecutable());
David Brazdil7126c5b2019-03-05 00:02:51 +00001607
Vladimir Marko07f78902020-07-27 11:35:12 +00001608 // Create a fake OatHeader with a key store containing only the compiler
Nicolas Geoffraydee09f92019-10-23 15:18:20 +01001609 // filter (it helps debugging and is required by
1610 // OatHeader::GetCompilerFilter).
David Brazdil7126c5b2019-03-05 00:02:51 +00001611 std::unique_ptr<const InstructionSetFeatures> isa_features =
1612 InstructionSetFeatures::FromCppDefines();
Nicolas Geoffraydee09f92019-10-23 15:18:20 +01001613 SafeMap<std::string, std::string> store;
1614 store.Put(OatHeader::kCompilerFilter, CompilerFilter::NameOfFilter(CompilerFilter::kVerify));
Nicolas Geoffray16f60dc2021-02-16 15:35:16 +00001615 store.Put(OatHeader::kConcurrentCopying,
1616 kUseReadBarrier ? OatHeader::kTrueValue : OatHeader::kFalseValue);
David Brazdil7126c5b2019-03-05 00:02:51 +00001617 oat_header_.reset(OatHeader::Create(kRuntimeISA,
1618 isa_features.get(),
Nicolas Geoffray16f60dc2021-02-16 15:35:16 +00001619 number_of_dex_files,
Nicolas Geoffraydee09f92019-10-23 15:18:20 +01001620 &store));
David Brazdil7126c5b2019-03-05 00:02:51 +00001621 const uint8_t* begin = reinterpret_cast<const uint8_t*>(oat_header_.get());
1622 SetBegin(begin);
1623 SetEnd(begin + oat_header_->GetHeaderSize());
David Brazdil7126c5b2019-03-05 00:02:51 +00001624 }
1625
1626 protected:
1627 void PreLoad() override {}
1628
1629 bool Load(const std::string& elf_filename ATTRIBUTE_UNUSED,
1630 bool writable ATTRIBUTE_UNUSED,
1631 bool executable ATTRIBUTE_UNUSED,
1632 bool low_4gb ATTRIBUTE_UNUSED,
1633 MemMap* reservation ATTRIBUTE_UNUSED,
1634 std::string* error_msg ATTRIBUTE_UNUSED) override {
1635 LOG(FATAL) << "Unsupported";
1636 UNREACHABLE();
1637 }
1638
1639 bool Load(int oat_fd ATTRIBUTE_UNUSED,
1640 bool writable ATTRIBUTE_UNUSED,
1641 bool executable ATTRIBUTE_UNUSED,
1642 bool low_4gb ATTRIBUTE_UNUSED,
1643 MemMap* reservation ATTRIBUTE_UNUSED,
1644 std::string* error_msg ATTRIBUTE_UNUSED) override {
1645 LOG(FATAL) << "Unsupported";
1646 UNREACHABLE();
1647 }
1648
1649 void PreSetup(const std::string& elf_filename ATTRIBUTE_UNUSED) override {}
1650
1651 const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name ATTRIBUTE_UNUSED,
1652 std::string* error_msg) const override {
1653 *error_msg = "Unsupported";
1654 return nullptr;
1655 }
1656
1657 private:
1658 std::unique_ptr<OatHeader> oat_header_;
David Brazdil7126c5b2019-03-05 00:02:51 +00001659
1660 DISALLOW_COPY_AND_ASSIGN(OatFileBackedByVdex);
1661};
1662
Andreas Gampe049cff02015-12-01 23:27:12 -08001663//////////////////////////
1664// General OatFile code //
1665//////////////////////////
1666
Andreas Gampe049cff02015-12-01 23:27:12 -08001667static void CheckLocation(const std::string& location) {
1668 CHECK(!location.empty());
1669}
1670
Nicolas Geoffray30025092018-04-19 14:43:29 +01001671OatFile* OatFile::Open(int zip_fd,
1672 const std::string& oat_filename,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001673 const std::string& oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001674 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001675 bool low_4gb,
Vladimir Markob7bf8432019-12-03 13:18:50 +00001676 ArrayRef<const std::string> dex_filenames,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001677 /*inout*/MemMap* reservation,
1678 /*out*/std::string* error_msg) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001679 ScopedTrace trace("Open oat file " + oat_location);
1680 CHECK(!oat_filename.empty()) << oat_location;
1681 CheckLocation(oat_location);
Andreas Gampe54315c72016-05-18 21:10:42 -07001682
Calin Juravle367b9d82017-05-15 18:18:39 -07001683 std::string vdex_filename = GetVdexFilename(oat_filename);
David Brazdil7b49e6c2016-09-01 11:06:18 +01001684
Nicolas Geoffray16f60dc2021-02-16 15:35:16 +00001685 // Check that the vdex file even exists, fast-fail. We don't check the odex
1686 // file as we use the absence of an odex file for test the functionality of
1687 // vdex-only.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001688 if (!OS::FileExists(vdex_filename.c_str())) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001689 *error_msg = StringPrintf("File %s does not exist.", vdex_filename.c_str());
1690 return nullptr;
Andreas Gampe54315c72016-05-18 21:10:42 -07001691 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001692
1693 // Try dlopen first, as it is required for native debuggability. This will fail fast if dlopen is
1694 // disabled.
Nicolas Geoffray30025092018-04-19 14:43:29 +01001695 OatFile* with_dlopen = OatFileBase::OpenOatFile<DlOpenOatFile>(zip_fd,
1696 vdex_filename,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001697 oat_filename,
1698 oat_location,
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001699 /*writable=*/ false,
Andreas Gampe049cff02015-12-01 23:27:12 -08001700 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001701 low_4gb,
Vladimir Markob7bf8432019-12-03 13:18:50 +00001702 dex_filenames,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001703 reservation,
Andreas Gampe049cff02015-12-01 23:27:12 -08001704 error_msg);
1705 if (with_dlopen != nullptr) {
Jagadeesh Pakaravoor06541532021-02-22 21:19:09 -08001706 Runtime* runtime = Runtime::Current();
1707 // The runtime might not be available at this point if we're running
1708 // dex2oat or oatdump.
1709 if (runtime != nullptr) {
1710 size_t madvise_size_limit = runtime->GetMadviseWillNeedSizeOdex();
1711 Runtime::MadviseFileForRange(madvise_size_limit,
1712 with_dlopen->Size(),
1713 with_dlopen->Begin(),
1714 with_dlopen->End(),
1715 oat_location);
1716 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001717 return with_dlopen;
1718 }
1719 if (kPrintDlOpenErrorMessage) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001720 LOG(ERROR) << "Failed to dlopen: " << oat_filename << " with error " << *error_msg;
Andreas Gampe049cff02015-12-01 23:27:12 -08001721 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001722 // If we aren't trying to execute, we just use our own ElfFile loader for a couple reasons:
1723 //
1724 // On target, dlopen may fail when compiling due to selinux restrictions on installd.
1725 //
1726 // We use our own ELF loader for Quick to deal with legacy apps that
1727 // open a generated dex file by name, remove the file, then open
1728 // another generated dex file with the same name. http://b/10614658
1729 //
Vladimir Marko13fcc3e2020-01-24 12:40:56 +00001730 // On host, dlopen is expected to fail when cross compiling, so fall back to ElfOatFile.
Andreas Gampe049cff02015-12-01 23:27:12 -08001731 //
1732 //
1733 // Another independent reason is the absolute placement of boot.oat. dlopen on the host usually
1734 // 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 +01001735 OatFile* with_internal = OatFileBase::OpenOatFile<ElfOatFile>(zip_fd,
1736 vdex_filename,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001737 oat_filename,
1738 oat_location,
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001739 /*writable=*/ false,
Andreas Gampe049cff02015-12-01 23:27:12 -08001740 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001741 low_4gb,
Vladimir Markob7bf8432019-12-03 13:18:50 +00001742 dex_filenames,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001743 reservation,
Andreas Gampe049cff02015-12-01 23:27:12 -08001744 error_msg);
1745 return with_internal;
1746}
1747
Nicolas Geoffray30025092018-04-19 14:43:29 +01001748OatFile* OatFile::Open(int zip_fd,
1749 int vdex_fd,
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001750 int oat_fd,
1751 const std::string& oat_location,
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001752 bool executable,
1753 bool low_4gb,
Vladimir Markob7bf8432019-12-03 13:18:50 +00001754 ArrayRef<const std::string> dex_filenames,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001755 /*inout*/MemMap* reservation,
1756 /*out*/std::string* error_msg) {
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001757 CHECK(!oat_location.empty()) << oat_location;
1758
1759 std::string vdex_location = GetVdexFilename(oat_location);
1760
Nicolas Geoffray30025092018-04-19 14:43:29 +01001761 OatFile* with_internal = OatFileBase::OpenOatFile<ElfOatFile>(zip_fd,
1762 vdex_fd,
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001763 oat_fd,
1764 vdex_location,
1765 oat_location,
Vladimir Markof4efa9e2018-10-17 14:12:45 +01001766 /*writable=*/ false,
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001767 executable,
1768 low_4gb,
Vladimir Markob7bf8432019-12-03 13:18:50 +00001769 dex_filenames,
Vladimir Markoc09cd052018-08-23 16:36:36 +01001770 reservation,
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001771 error_msg);
1772 return with_internal;
1773}
1774
David Brazdil7126c5b2019-03-05 00:02:51 +00001775OatFile* OatFile::OpenFromVdex(const std::vector<const DexFile*>& dex_files,
1776 std::unique_ptr<VdexFile>&& vdex_file,
1777 const std::string& location) {
1778 CheckLocation(location);
1779 return OatFileBackedByVdex::Open(dex_files, std::move(vdex_file), location);
1780}
1781
Nicolas Geoffray16f60dc2021-02-16 15:35:16 +00001782OatFile* OatFile::OpenFromVdex(int zip_fd,
1783 std::unique_ptr<VdexFile>&& vdex_file,
1784 const std::string& location,
1785 std::string* error_msg) {
1786 CheckLocation(location);
1787 return OatFileBackedByVdex::Open(zip_fd, std::move(vdex_file), location, error_msg);
1788}
1789
Andreas Gampe049cff02015-12-01 23:27:12 -08001790OatFile::OatFile(const std::string& location, bool is_executable)
1791 : location_(location),
David Brazdil7b49e6c2016-09-01 11:06:18 +01001792 vdex_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001793 begin_(nullptr),
1794 end_(nullptr),
Vladimir Markob066d432018-01-03 13:14:37 +00001795 data_bimg_rel_ro_begin_(nullptr),
1796 data_bimg_rel_ro_end_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001797 bss_begin_(nullptr),
1798 bss_end_(nullptr),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001799 bss_methods_(nullptr),
Vladimir Markoaad75c62016-10-03 08:46:48 +00001800 bss_roots_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001801 is_executable_(is_executable),
David Srbeckyec2cdf42017-12-08 16:21:25 +00001802 vdex_begin_(nullptr),
1803 vdex_end_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001804 secondary_lookup_lock_("OatFile secondary lookup lock", kOatFileSecondaryLookupLock) {
1805 CHECK(!location_.empty());
1806}
1807
1808OatFile::~OatFile() {
1809 STLDeleteElements(&oat_dex_files_storage_);
1810}
1811
Brian Carlstrome24fa612011-09-29 00:53:55 -07001812const OatHeader& OatFile::GetOatHeader() const {
Ian Rogers30fab402012-01-23 15:43:46 -08001813 return *reinterpret_cast<const OatHeader*>(Begin());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001814}
1815
Ian Rogers13735952014-10-08 12:43:28 -07001816const uint8_t* OatFile::Begin() const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001817 CHECK(begin_ != nullptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001818 return begin_;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001819}
1820
Ian Rogers13735952014-10-08 12:43:28 -07001821const uint8_t* OatFile::End() const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001822 CHECK(end_ != nullptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001823 return end_;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001824}
1825
David Brazdil7b49e6c2016-09-01 11:06:18 +01001826const uint8_t* OatFile::DexBegin() const {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001827 return vdex_->Begin();
David Brazdil7b49e6c2016-09-01 11:06:18 +01001828}
1829
1830const uint8_t* OatFile::DexEnd() const {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001831 return vdex_->End();
David Brazdil7b49e6c2016-09-01 11:06:18 +01001832}
1833
Vladimir Markob066d432018-01-03 13:14:37 +00001834ArrayRef<const uint32_t> OatFile::GetBootImageRelocations() const {
1835 if (data_bimg_rel_ro_begin_ != nullptr) {
1836 const uint32_t* relocations = reinterpret_cast<const uint32_t*>(data_bimg_rel_ro_begin_);
1837 const uint32_t* relocations_end = reinterpret_cast<const uint32_t*>(data_bimg_rel_ro_end_);
1838 return ArrayRef<const uint32_t>(relocations, relocations_end - relocations);
1839 } else {
1840 return ArrayRef<const uint32_t>();
1841 }
1842}
1843
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001844ArrayRef<ArtMethod*> OatFile::GetBssMethods() const {
1845 if (bss_methods_ != nullptr) {
1846 ArtMethod** methods = reinterpret_cast<ArtMethod**>(bss_methods_);
1847 ArtMethod** methods_end =
1848 reinterpret_cast<ArtMethod**>(bss_roots_ != nullptr ? bss_roots_ : bss_end_);
1849 return ArrayRef<ArtMethod*>(methods, methods_end - methods);
1850 } else {
1851 return ArrayRef<ArtMethod*>();
1852 }
1853}
1854
Vladimir Markoaad75c62016-10-03 08:46:48 +00001855ArrayRef<GcRoot<mirror::Object>> OatFile::GetBssGcRoots() const {
1856 if (bss_roots_ != nullptr) {
1857 auto* roots = reinterpret_cast<GcRoot<mirror::Object>*>(bss_roots_);
1858 auto* roots_end = reinterpret_cast<GcRoot<mirror::Object>*>(bss_end_);
1859 return ArrayRef<GcRoot<mirror::Object>>(roots, roots_end - roots);
1860 } else {
1861 return ArrayRef<GcRoot<mirror::Object>>();
1862 }
1863}
1864
Andreas Gampeb40d3612018-06-26 15:49:42 -07001865const OatDexFile* OatFile::GetOatDexFile(const char* dex_location,
1866 const uint32_t* dex_location_checksum,
1867 std::string* error_msg) const {
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001868 // NOTE: We assume here that the canonical location for a given dex_location never
1869 // changes. If it does (i.e. some symlink used by the filename changes) we may return
1870 // an incorrect OatDexFile. As long as we have a checksum to check, we shall return
1871 // an identical file or fail; otherwise we may see some unpredictable failures.
Calin Juravle4e1d5792014-07-15 23:56:47 +01001872
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001873 // TODO: Additional analysis of usage patterns to see if this can be simplified
1874 // without any performance loss, for example by not doing the first lock-free lookup.
1875
Andreas Gampeb40d3612018-06-26 15:49:42 -07001876 const OatDexFile* oat_dex_file = nullptr;
Vladimir Marko59ae4f92019-02-04 14:06:02 +00001877 std::string_view key(dex_location);
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001878 // Try to find the key cheaply in the oat_dex_files_ map which holds dex locations
1879 // directly mentioned in the oat file and doesn't require locking.
1880 auto primary_it = oat_dex_files_.find(key);
1881 if (primary_it != oat_dex_files_.end()) {
1882 oat_dex_file = primary_it->second;
1883 DCHECK(oat_dex_file != nullptr);
1884 } else {
1885 // This dex_location is not one of the dex locations directly mentioned in the
1886 // oat file. The correct lookup is via the canonical location but first see in
1887 // the secondary_oat_dex_files_ whether we've looked up this location before.
1888 MutexLock mu(Thread::Current(), secondary_lookup_lock_);
1889 auto secondary_lb = secondary_oat_dex_files_.lower_bound(key);
1890 if (secondary_lb != secondary_oat_dex_files_.end() && key == secondary_lb->first) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001891 oat_dex_file = secondary_lb->second; // May be null.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001892 } else {
1893 // We haven't seen this dex_location before, we must check the canonical location.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001894 std::string dex_canonical_location = DexFileLoader::GetDexCanonicalLocation(dex_location);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001895 if (dex_canonical_location != dex_location) {
Vladimir Marko59ae4f92019-02-04 14:06:02 +00001896 std::string_view canonical_key(dex_canonical_location);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001897 auto canonical_it = oat_dex_files_.find(canonical_key);
1898 if (canonical_it != oat_dex_files_.end()) {
1899 oat_dex_file = canonical_it->second;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001900 } // else keep null.
1901 } // else keep null.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001902
1903 // Copy the key to the string_cache_ and store the result in secondary map.
1904 string_cache_.emplace_back(key.data(), key.length());
Vladimir Marko59ae4f92019-02-04 14:06:02 +00001905 std::string_view key_copy(string_cache_.back());
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001906 secondary_oat_dex_files_.PutBefore(secondary_lb, key_copy, oat_dex_file);
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001907 }
1908 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001909
1910 if (oat_dex_file == nullptr) {
1911 if (error_msg != nullptr) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001912 std::string dex_canonical_location = DexFileLoader::GetDexCanonicalLocation(dex_location);
Richard Uhler9a37efc2016-08-05 16:32:55 -07001913 *error_msg = "Failed to find OatDexFile for DexFile " + std::string(dex_location)
1914 + " (canonical path " + dex_canonical_location + ") in OatFile " + GetLocation();
1915 }
1916 return nullptr;
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001917 }
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001918
Richard Uhler9a37efc2016-08-05 16:32:55 -07001919 if (dex_location_checksum != nullptr &&
1920 oat_dex_file->GetDexFileLocationChecksum() != *dex_location_checksum) {
1921 if (error_msg != nullptr) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001922 std::string dex_canonical_location = DexFileLoader::GetDexCanonicalLocation(dex_location);
Richard Uhler9a37efc2016-08-05 16:32:55 -07001923 std::string checksum = StringPrintf("0x%08x", oat_dex_file->GetDexFileLocationChecksum());
1924 std::string required_checksum = StringPrintf("0x%08x", *dex_location_checksum);
1925 *error_msg = "OatDexFile for DexFile " + std::string(dex_location)
1926 + " (canonical path " + dex_canonical_location + ") in OatFile " + GetLocation()
1927 + " has checksum " + checksum + " but " + required_checksum + " was required";
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001928 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001929 return nullptr;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001930 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001931 return oat_dex_file;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001932}
1933
Andreas Gampeb40d3612018-06-26 15:49:42 -07001934OatDexFile::OatDexFile(const OatFile* oat_file,
1935 const std::string& dex_file_location,
1936 const std::string& canonical_dex_file_location,
1937 uint32_t dex_file_location_checksum,
1938 const uint8_t* dex_file_pointer,
1939 const uint8_t* lookup_table_data,
1940 const IndexBssMapping* method_bss_mapping_data,
1941 const IndexBssMapping* type_bss_mapping_data,
Vladimir Marko8f63f102020-09-28 12:10:28 +01001942 const IndexBssMapping* public_type_bss_mapping_data,
1943 const IndexBssMapping* package_type_bss_mapping_data,
Andreas Gampeb40d3612018-06-26 15:49:42 -07001944 const IndexBssMapping* string_bss_mapping_data,
1945 const uint32_t* oat_class_offsets_pointer,
1946 const DexLayoutSections* dex_layout_sections)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001947 : oat_file_(oat_file),
1948 dex_file_location_(dex_file_location),
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001949 canonical_dex_file_location_(canonical_dex_file_location),
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001950 dex_file_location_checksum_(dex_file_location_checksum),
Brian Carlstrom89521892011-12-07 22:05:07 -08001951 dex_file_pointer_(dex_file_pointer),
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001952 lookup_table_data_(lookup_table_data),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001953 method_bss_mapping_(method_bss_mapping_data),
Vladimir Markof3c52b42017-11-17 17:32:12 +00001954 type_bss_mapping_(type_bss_mapping_data),
Vladimir Marko8f63f102020-09-28 12:10:28 +01001955 public_type_bss_mapping_(public_type_bss_mapping_data),
1956 package_type_bss_mapping_(package_type_bss_mapping_data),
Vladimir Markof3c52b42017-11-17 17:32:12 +00001957 string_bss_mapping_(string_bss_mapping_data),
Vladimir Marko09d09432015-09-08 13:47:48 +01001958 oat_class_offsets_pointer_(oat_class_offsets_pointer),
Vladimir Markoea341d22018-05-11 10:33:37 +01001959 lookup_table_(),
Mathieu Chartier120aa282017-08-05 16:03:03 -07001960 dex_layout_sections_(dex_layout_sections) {
David Sehr9aa352e2016-09-15 18:13:52 -07001961 // Initialize TypeLookupTable.
1962 if (lookup_table_data_ != nullptr) {
1963 // Peek the number of classes from the DexFile.
1964 const DexFile::Header* dex_header = reinterpret_cast<const DexFile::Header*>(dex_file_pointer_);
1965 const uint32_t num_class_defs = dex_header->class_defs_size_;
1966 if (lookup_table_data_ + TypeLookupTable::RawDataLength(num_class_defs) > GetOatFile()->End()) {
1967 LOG(WARNING) << "found truncated lookup table in " << dex_file_location_;
1968 } else {
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08001969 const uint8_t* dex_data = dex_file_pointer_;
1970 // TODO: Clean this up to create the type lookup table after the dex file has been created?
1971 if (CompactDexFile::IsMagicValid(dex_header->magic_)) {
1972 dex_data += dex_header->data_off_;
1973 }
1974 lookup_table_ = TypeLookupTable::Open(dex_data, lookup_table_data_, num_class_defs);
David Sehr9aa352e2016-09-15 18:13:52 -07001975 }
1976 }
David Brazdil7126c5b2019-03-05 00:02:51 +00001977 DCHECK(!IsBackedByVdexOnly());
1978}
1979
1980OatDexFile::OatDexFile(const OatFile* oat_file,
Nicolas Geoffray16f60dc2021-02-16 15:35:16 +00001981 const uint8_t* dex_file_pointer,
1982 uint32_t dex_file_location_checksum,
David Brazdil7126c5b2019-03-05 00:02:51 +00001983 const std::string& dex_file_location,
1984 const std::string& canonical_dex_file_location)
1985 : oat_file_(oat_file),
1986 dex_file_location_(dex_file_location),
1987 canonical_dex_file_location_(canonical_dex_file_location),
Nicolas Geoffray16f60dc2021-02-16 15:35:16 +00001988 dex_file_location_checksum_(dex_file_location_checksum),
1989 dex_file_pointer_(dex_file_pointer) {
David Brazdil7126c5b2019-03-05 00:02:51 +00001990 DCHECK(IsBackedByVdexOnly());
David Sehr9aa352e2016-09-15 18:13:52 -07001991}
Brian Carlstrome24fa612011-09-29 00:53:55 -07001992
Andreas Gampe875b4f22018-11-19 12:59:15 -08001993OatDexFile::OatDexFile(TypeLookupTable&& lookup_table) : lookup_table_(std::move(lookup_table)) {
David Srbeckyb5649f92019-05-14 15:27:52 +01001994 // Stripped-down OatDexFile only allowed in the compiler, the zygote, or the system server.
Nicolas Geoffraydc2fbb62019-04-11 22:55:50 +01001995 CHECK(Runtime::Current() == nullptr ||
1996 Runtime::Current()->IsAotCompiler() ||
David Srbeckyb5649f92019-05-14 15:27:52 +01001997 Runtime::Current()->IsZygote() ||
1998 Runtime::Current()->IsSystemServer());
Andreas Gampe875b4f22018-11-19 12:59:15 -08001999}
Mathieu Chartier1b868492016-11-16 16:22:37 -08002000
Andreas Gampeb40d3612018-06-26 15:49:42 -07002001OatDexFile::~OatDexFile() {}
Brian Carlstrome24fa612011-09-29 00:53:55 -07002002
Andreas Gampeb40d3612018-06-26 15:49:42 -07002003size_t OatDexFile::FileSize() const {
Andreas Gampe875b4f22018-11-19 12:59:15 -08002004 DCHECK(dex_file_pointer_ != nullptr);
Ian Rogers05f28c62012-10-23 18:12:13 -07002005 return reinterpret_cast<const DexFile::Header*>(dex_file_pointer_)->file_size_;
2006}
2007
Andreas Gampeb40d3612018-06-26 15:49:42 -07002008std::unique_ptr<const DexFile> OatDexFile::OpenDexFile(std::string* error_msg) const {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08002009 ScopedTrace trace(__PRETTY_FUNCTION__);
Aart Bik37d6a3b2016-06-21 18:30:10 -07002010 static constexpr bool kVerify = false;
2011 static constexpr bool kVerifyChecksum = false;
David Sehr013fd802018-01-11 22:55:24 -08002012 const ArtDexFileLoader dex_file_loader;
2013 return dex_file_loader.Open(dex_file_pointer_,
2014 FileSize(),
2015 dex_file_location_,
2016 dex_file_location_checksum_,
2017 this,
2018 kVerify,
2019 kVerifyChecksum,
2020 error_msg);
Brian Carlstrom89521892011-12-07 22:05:07 -08002021}
2022
Andreas Gampeb40d3612018-06-26 15:49:42 -07002023uint32_t OatDexFile::GetOatClassOffset(uint16_t class_def_index) const {
Andreas Gampe875b4f22018-11-19 12:59:15 -08002024 DCHECK(oat_class_offsets_pointer_ != nullptr);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07002025 return oat_class_offsets_pointer_[class_def_index];
2026}
2027
David Brazdil7126c5b2019-03-05 00:02:51 +00002028bool OatDexFile::IsBackedByVdexOnly() const {
2029 return oat_class_offsets_pointer_ == nullptr;
2030}
2031
Andreas Gampeb40d3612018-06-26 15:49:42 -07002032OatFile::OatClass OatDexFile::GetOatClass(uint16_t class_def_index) const {
David Brazdil7126c5b2019-03-05 00:02:51 +00002033 if (IsBackedByVdexOnly()) {
Nicolas Geoffray16f60dc2021-02-16 15:35:16 +00002034 // If there is only a vdex file, return that the class is not ready. The
2035 // caller will have to call `VdexFile::ComputeClassStatus` to compute the
2036 // actual class status, because we need to do the assignability type checks.
David Brazdil7126c5b2019-03-05 00:02:51 +00002037 return OatFile::OatClass(oat_file_,
Nicolas Geoffray16f60dc2021-02-16 15:35:16 +00002038 ClassStatus::kNotReady,
David Brazdil7126c5b2019-03-05 00:02:51 +00002039 /* type= */ kOatClassNoneCompiled,
2040 /* bitmap_size= */ 0u,
2041 /* bitmap_pointer= */ nullptr,
2042 /* methods_pointer= */ nullptr);
2043 }
2044
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07002045 uint32_t oat_class_offset = GetOatClassOffset(class_def_index);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002046
Ian Rogers13735952014-10-08 12:43:28 -07002047 const uint8_t* oat_class_pointer = oat_file_->Begin() + oat_class_offset;
Mathieu Chartier2a530562020-08-04 16:56:18 -07002048 CHECK_LT(reinterpret_cast<const void*>(oat_class_pointer),
2049 reinterpret_cast<const void*>(oat_file_->End())) << oat_file_->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002050
Ian Rogers13735952014-10-08 12:43:28 -07002051 const uint8_t* status_pointer = oat_class_pointer;
Brian Carlstromba150c32013-08-27 17:31:03 -07002052 CHECK_LT(status_pointer, oat_file_->End()) << oat_file_->GetLocation();
Vladimir Marko2c64a832018-01-04 11:31:56 +00002053 ClassStatus status = enum_cast<ClassStatus>(*reinterpret_cast<const int16_t*>(status_pointer));
Mathieu Chartier69828ac2020-03-09 14:11:02 -07002054 CHECK_LE(status, ClassStatus::kLast) << static_cast<uint32_t>(status)
2055 << " at " << oat_file_->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002056
Ian Rogers13735952014-10-08 12:43:28 -07002057 const uint8_t* type_pointer = status_pointer + sizeof(uint16_t);
Brian Carlstromba150c32013-08-27 17:31:03 -07002058 CHECK_LT(type_pointer, oat_file_->End()) << oat_file_->GetLocation();
2059 OatClassType type = static_cast<OatClassType>(*reinterpret_cast<const uint16_t*>(type_pointer));
Mathieu Chartier69828ac2020-03-09 14:11:02 -07002060 CHECK_LT(type, kOatClassMax) << oat_file_->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002061
Ian Rogers13735952014-10-08 12:43:28 -07002062 const uint8_t* after_type_pointer = type_pointer + sizeof(int16_t);
Brian Carlstromcd937a92014-03-04 22:53:23 -08002063 CHECK_LE(after_type_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002064
Brian Carlstromcd937a92014-03-04 22:53:23 -08002065 uint32_t bitmap_size = 0;
Ian Rogers13735952014-10-08 12:43:28 -07002066 const uint8_t* bitmap_pointer = nullptr;
2067 const uint8_t* methods_pointer = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07002068 if (type != kOatClassNoneCompiled) {
2069 if (type == kOatClassSomeCompiled) {
2070 bitmap_size = static_cast<uint32_t>(*reinterpret_cast<const uint32_t*>(after_type_pointer));
2071 bitmap_pointer = after_type_pointer + sizeof(bitmap_size);
2072 CHECK_LE(bitmap_pointer, oat_file_->End()) << oat_file_->GetLocation();
2073 methods_pointer = bitmap_pointer + bitmap_size;
2074 } else {
2075 methods_pointer = after_type_pointer;
2076 }
2077 CHECK_LE(methods_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstromcd937a92014-03-04 22:53:23 -08002078 }
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002079
Richard Uhler07b3c232015-03-31 15:57:54 -07002080 return OatFile::OatClass(oat_file_,
2081 status,
2082 type,
2083 bitmap_size,
2084 reinterpret_cast<const uint32_t*>(bitmap_pointer),
2085 reinterpret_cast<const OatMethodOffsets*>(methods_pointer));
Brian Carlstrome24fa612011-09-29 00:53:55 -07002086}
2087
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002088const dex::ClassDef* OatDexFile::FindClassDef(const DexFile& dex_file,
2089 const char* descriptor,
2090 size_t hash) {
Andreas Gampeb40d3612018-06-26 15:49:42 -07002091 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
David Sehr9aa352e2016-09-15 18:13:52 -07002092 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08002093 bool used_lookup_table = false;
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002094 const dex::ClassDef* lookup_table_classdef = nullptr;
Vladimir Markoea341d22018-05-11 10:33:37 +01002095 if (LIKELY((oat_dex_file != nullptr) && oat_dex_file->GetTypeLookupTable().Valid())) {
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08002096 used_lookup_table = true;
Vladimir Markoea341d22018-05-11 10:33:37 +01002097 const uint32_t class_def_idx = oat_dex_file->GetTypeLookupTable().Lookup(descriptor, hash);
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08002098 lookup_table_classdef = (class_def_idx != dex::kDexNoIndex)
2099 ? &dex_file.GetClassDef(class_def_idx)
2100 : nullptr;
2101 if (!kIsDebugBuild) {
2102 return lookup_table_classdef;
2103 }
David Sehr9aa352e2016-09-15 18:13:52 -07002104 }
2105 // Fast path for rare no class defs case.
2106 const uint32_t num_class_defs = dex_file.NumClassDefs();
2107 if (num_class_defs == 0) {
Vladimir Markoea341d22018-05-11 10:33:37 +01002108 DCHECK(!used_lookup_table);
David Sehr9aa352e2016-09-15 18:13:52 -07002109 return nullptr;
2110 }
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002111 const dex::TypeId* type_id = dex_file.FindTypeId(descriptor);
David Sehr9aa352e2016-09-15 18:13:52 -07002112 if (type_id != nullptr) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08002113 dex::TypeIndex type_idx = dex_file.GetIndexForTypeId(*type_id);
Andreas Gampe3f1dcd32018-12-28 09:39:56 -08002114 const dex::ClassDef* found_class_def = dex_file.FindClassDef(type_idx);
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08002115 if (kIsDebugBuild && used_lookup_table) {
2116 DCHECK_EQ(found_class_def, lookup_table_classdef);
2117 }
2118 return found_class_def;
David Sehr9aa352e2016-09-15 18:13:52 -07002119 }
2120 return nullptr;
2121}
2122
Mathieu Chartier120aa282017-08-05 16:03:03 -07002123// Madvise the dex file based on the state we are moving to.
2124void OatDexFile::MadviseDexFile(const DexFile& dex_file, MadviseState state) {
Mathieu Chartierc42cb0e2017-10-13 11:35:00 -07002125 Runtime* const runtime = Runtime::Current();
2126 const bool low_ram = runtime->GetHeap()->IsLowMemoryMode();
Mathieu Chartier150d25d2017-08-28 09:52:55 -07002127 // TODO: Also do madvise hints for non low ram devices.
Mathieu Chartierc42cb0e2017-10-13 11:35:00 -07002128 if (!low_ram) {
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07002129 return;
2130 }
Mathieu Chartierc42cb0e2017-10-13 11:35:00 -07002131 if (state == MadviseState::kMadviseStateAtLoad && runtime->MAdviseRandomAccess()) {
2132 // Default every dex file to MADV_RANDOM when its loaded by default for low ram devices.
2133 // Other devices have enough page cache to get performance benefits from loading more pages
2134 // into the page cache.
David Sehrc431b9d2018-03-02 12:01:51 -08002135 DexLayoutSection::MadviseLargestPageAlignedRegion(dex_file.Begin(),
2136 dex_file.Begin() + dex_file.Size(),
2137 MADV_RANDOM);
Mathieu Chartier120aa282017-08-05 16:03:03 -07002138 }
Andreas Gampeb40d3612018-06-26 15:49:42 -07002139 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Mathieu Chartier120aa282017-08-05 16:03:03 -07002140 if (oat_dex_file != nullptr) {
2141 // Should always be there.
2142 const DexLayoutSections* const sections = oat_dex_file->GetDexLayoutSections();
2143 CHECK(sections != nullptr);
2144 sections->Madvise(&dex_file, state);
2145 }
2146}
2147
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002148OatFile::OatClass::OatClass(const OatFile* oat_file,
Vladimir Marko2c64a832018-01-04 11:31:56 +00002149 ClassStatus status,
Brian Carlstromba150c32013-08-27 17:31:03 -07002150 OatClassType type,
2151 uint32_t bitmap_size,
2152 const uint32_t* bitmap_pointer,
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002153 const OatMethodOffsets* methods_pointer)
Brian Carlstromba150c32013-08-27 17:31:03 -07002154 : oat_file_(oat_file), status_(status), type_(type),
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002155 bitmap_(bitmap_pointer), methods_pointer_(methods_pointer) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002156 switch (type_) {
2157 case kOatClassAllCompiled: {
2158 CHECK_EQ(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08002159 CHECK(bitmap_pointer == nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07002160 CHECK(methods_pointer != nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07002161 break;
2162 }
2163 case kOatClassSomeCompiled: {
2164 CHECK_NE(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08002165 CHECK(bitmap_pointer != nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07002166 CHECK(methods_pointer != nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07002167 break;
2168 }
2169 case kOatClassNoneCompiled: {
2170 CHECK_EQ(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08002171 CHECK(bitmap_pointer == nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07002172 CHECK(methods_pointer_ == nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07002173 break;
2174 }
2175 case kOatClassMax: {
2176 LOG(FATAL) << "Invalid OatClassType " << type_;
Elliott Hughesc1896c92018-11-29 11:33:18 -08002177 UNREACHABLE();
Brian Carlstromba150c32013-08-27 17:31:03 -07002178 }
2179 }
2180}
Brian Carlstrome24fa612011-09-29 00:53:55 -07002181
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07002182uint32_t OatFile::OatClass::GetOatMethodOffsetsOffset(uint32_t method_index) const {
2183 const OatMethodOffsets* oat_method_offsets = GetOatMethodOffsets(method_index);
2184 if (oat_method_offsets == nullptr) {
2185 return 0u;
2186 }
2187 return reinterpret_cast<const uint8_t*>(oat_method_offsets) - oat_file_->Begin();
2188}
2189
2190const OatMethodOffsets* OatFile::OatClass::GetOatMethodOffsets(uint32_t method_index) const {
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002191 // 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 -07002192 if (methods_pointer_ == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002193 CHECK_EQ(kOatClassNoneCompiled, type_);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07002194 return nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002195 }
2196 size_t methods_pointer_index;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07002197 if (bitmap_ == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07002198 CHECK_EQ(kOatClassAllCompiled, type_);
2199 methods_pointer_index = method_index;
2200 } else {
2201 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002202 if (!BitVector::IsBitSet(bitmap_, method_index)) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07002203 return nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07002204 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01002205 size_t num_set_bits = BitVector::NumSetBits(bitmap_, method_index);
2206 methods_pointer_index = num_set_bits;
Brian Carlstromba150c32013-08-27 17:31:03 -07002207 }
2208 const OatMethodOffsets& oat_method_offsets = methods_pointer_[methods_pointer_index];
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07002209 return &oat_method_offsets;
2210}
2211
2212const OatFile::OatMethod OatFile::OatClass::GetOatMethod(uint32_t method_index) const {
2213 const OatMethodOffsets* oat_method_offsets = GetOatMethodOffsets(method_index);
2214 if (oat_method_offsets == nullptr) {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08002215 return OatMethod(nullptr, 0);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07002216 }
2217 if (oat_file_->IsExecutable() ||
2218 Runtime::Current() == nullptr || // This case applies for oatdump.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002219 Runtime::Current()->IsAotCompiler()) {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08002220 return OatMethod(oat_file_->Begin(), oat_method_offsets->code_offset_);
Alex Light9dcc4572014-08-14 14:16:26 -07002221 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08002222 // We aren't allowed to use the compiled code. We just force it down the interpreted / jit
2223 // version.
2224 return OatMethod(oat_file_->Begin(), 0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07002225}
2226
Sebastien Hertz0de11332015-05-13 12:14:05 +02002227bool OatFile::IsDebuggable() const {
2228 return GetOatHeader().IsDebuggable();
2229}
2230
Andreas Gampe29d38e72016-03-23 15:31:51 +00002231CompilerFilter::Filter OatFile::GetCompilerFilter() const {
2232 return GetOatHeader().GetCompilerFilter();
Calin Juravleb077e152016-02-18 18:47:37 +00002233}
2234
Calin Juravle44e5efa2017-09-12 00:54:26 -07002235std::string OatFile::GetClassLoaderContext() const {
2236 return GetOatHeader().GetStoreValueByKey(OatHeader::kClassPathKey);
Igor Murashkin2ffb7032017-11-08 13:35:21 -08002237}
Calin Juravle44e5efa2017-09-12 00:54:26 -07002238
Calin Juravle0e09dfc2018-02-12 19:01:09 -08002239const char* OatFile::GetCompilationReason() const {
2240 return GetOatHeader().GetStoreValueByKey(OatHeader::kCompilationReasonKey);
2241}
2242
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002243OatFile::OatClass OatFile::FindOatClass(const DexFile& dex_file,
2244 uint16_t class_def_idx,
2245 bool* found) {
2246 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
Andreas Gampeb40d3612018-06-26 15:49:42 -07002247 const OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Mathieu Chartier1b868492016-11-16 16:22:37 -08002248 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01002249 *found = false;
2250 return OatFile::OatClass::Invalid();
2251 }
2252 *found = true;
2253 return oat_dex_file->GetOatClass(class_def_idx);
2254}
2255
Eric Holkbc89ed42020-04-29 19:59:24 +00002256bool OatFile::RequiresImage() const { return GetOatHeader().RequiresImage(); }
2257
Vladimir Marko1cedb4a2019-02-06 14:13:28 +00002258static void DCheckIndexToBssMapping(const OatFile* oat_file,
2259 uint32_t number_of_indexes,
2260 size_t slot_size,
2261 const IndexBssMapping* index_bss_mapping) {
2262 if (kIsDebugBuild && index_bss_mapping != nullptr) {
2263 size_t index_bits = IndexBssMappingEntry::IndexBits(number_of_indexes);
2264 const IndexBssMappingEntry* prev_entry = nullptr;
2265 for (const IndexBssMappingEntry& entry : *index_bss_mapping) {
2266 CHECK_ALIGNED_PARAM(entry.bss_offset, slot_size);
2267 CHECK_LT(entry.bss_offset, oat_file->BssSize());
2268 uint32_t mask = entry.GetMask(index_bits);
2269 CHECK_LE(POPCOUNT(mask) * slot_size, entry.bss_offset);
2270 size_t index_mask_span = (mask != 0u) ? 32u - index_bits - CTZ(mask) : 0u;
2271 CHECK_LE(index_mask_span, entry.GetIndex(index_bits));
2272 if (prev_entry != nullptr) {
2273 CHECK_LT(prev_entry->GetIndex(index_bits), entry.GetIndex(index_bits) - index_mask_span);
2274 }
2275 prev_entry = &entry;
2276 }
2277 CHECK(prev_entry != nullptr);
2278 CHECK_LT(prev_entry->GetIndex(index_bits), number_of_indexes);
2279 }
2280}
2281
2282void OatFile::InitializeRelocations() const {
2283 DCHECK(IsExecutable());
2284
2285 // Initialize the .data.bimg.rel.ro section.
2286 if (!GetBootImageRelocations().empty()) {
2287 uint8_t* reloc_begin = const_cast<uint8_t*>(DataBimgRelRoBegin());
2288 CheckedCall(mprotect,
2289 "un-protect boot image relocations",
2290 reloc_begin,
2291 DataBimgRelRoSize(),
2292 PROT_READ | PROT_WRITE);
Vladimir Marko7cde4582019-07-05 13:26:11 +01002293 uint32_t boot_image_begin = Runtime::Current()->GetHeap()->GetBootImagesStartAddress();
Vladimir Marko1cedb4a2019-02-06 14:13:28 +00002294 for (const uint32_t& relocation : GetBootImageRelocations()) {
2295 const_cast<uint32_t&>(relocation) += boot_image_begin;
2296 }
2297 CheckedCall(mprotect,
2298 "protect boot image relocations",
2299 reloc_begin,
2300 DataBimgRelRoSize(),
2301 PROT_READ);
2302 }
2303
2304 // Before initializing .bss, check the .bss mappings in debug mode.
2305 if (kIsDebugBuild) {
2306 PointerSize pointer_size = GetInstructionSetPointerSize(GetOatHeader().GetInstructionSet());
2307 for (const OatDexFile* odf : GetOatDexFiles()) {
2308 const DexFile::Header* header =
2309 reinterpret_cast<const DexFile::Header*>(odf->GetDexFilePointer());
2310 DCheckIndexToBssMapping(this,
2311 header->method_ids_size_,
2312 static_cast<size_t>(pointer_size),
2313 odf->GetMethodBssMapping());
2314 DCheckIndexToBssMapping(this,
2315 header->type_ids_size_,
2316 sizeof(GcRoot<mirror::Class>),
2317 odf->GetTypeBssMapping());
2318 DCheckIndexToBssMapping(this,
2319 header->string_ids_size_,
2320 sizeof(GcRoot<mirror::String>),
2321 odf->GetStringBssMapping());
2322 }
2323 }
2324
2325 // Initialize the .bss section.
2326 // TODO: Pre-initialize from boot/app image?
2327 ArtMethod* resolution_method = Runtime::Current()->GetResolutionMethod();
2328 for (ArtMethod*& entry : GetBssMethods()) {
2329 entry = resolution_method;
2330 }
2331}
2332
Andreas Gampeb40d3612018-06-26 15:49:42 -07002333void OatDexFile::AssertAotCompiler() {
Mathieu Chartier1b868492016-11-16 16:22:37 -08002334 CHECK(Runtime::Current()->IsAotCompiler());
2335}
2336
Nicolas Geoffray16f60dc2021-02-16 15:35:16 +00002337bool OatFile::IsBackedByVdexOnly() const {
2338 return oat_dex_files_storage_.size() >= 1 && oat_dex_files_storage_[0]->IsBackedByVdexOnly();
2339}
2340
Brian Carlstrome24fa612011-09-29 00:53:55 -07002341} // namespace art