blob: c6664411e4c93812e1edf840c49d791649cd7d45 [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 Gampe46ee31b2016-12-14 10:11:49 -080036#include "android-base/stringprintf.h"
37
Andreas Gampec6ea7d02017-02-01 16:46:28 -080038#include "art_method.h"
Brian Carlstromba150c32013-08-27 17:31:03 -070039#include "base/bit_vector.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070040#include "base/enums.h"
David Sehr891a50e2017-10-27 17:01:07 -070041#include "base/file_utils.h"
Andreas Gampe170331f2017-12-07 18:41:03 -080042#include "base/logging.h" // For VLOG_IS_ON.
Elliott Hughes1aa246d2012-12-13 09:29:36 -080043#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080044#include "base/systrace.h"
Elliott Hughes76160052012-12-12 16:31:20 -080045#include "base/unix_file/fd_file.h"
David Sehr9e734c72018-01-04 17:56:19 -080046#include "dex/dex_file_loader.h"
47#include "dex/dex_file_types.h"
48#include "dex/standard_dex_file.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080049#include "elf_file.h"
Alex Light84d76052014-08-22 17:49:35 -070050#include "elf_utils.h"
Vladimir Markoaad75c62016-10-03 08:46:48 +000051#include "gc_root.h"
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +010052#include "gc/space/image_space.h"
David Srbecky1baabf02015-06-16 17:12:34 +000053#include "mem_map.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080054#include "mirror/class.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070055#include "mirror/object-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070056#include "oat.h"
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +010057#include "oat_file-inl.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070058#include "oat_file_manager.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070059#include "os.h"
Andreas Gampe22f8e5c2014-07-09 11:38:21 -070060#include "runtime.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000061#include "type_lookup_table.h"
David Sehr9aa352e2016-09-15 18:13:52 -070062#include "utf-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080063#include "utils.h"
Vladimir Marko97d7e1c2016-10-04 14:44:28 +010064#include "vdex_file.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070065
66namespace art {
67
Andreas Gampe46ee31b2016-12-14 10:11:49 -080068using android::base::StringPrintf;
69
Andreas Gampe049cff02015-12-01 23:27:12 -080070// Whether OatFile::Open will try dlopen. Fallback is our own ELF loader.
David Srbecky1baabf02015-06-16 17:12:34 +000071static constexpr bool kUseDlopen = true;
Andreas Gampefa8429b2015-04-07 18:34:42 -070072
Andreas Gampe049cff02015-12-01 23:27:12 -080073// Whether OatFile::Open will try dlopen on the host. On the host we're not linking against
Andreas Gampefa8429b2015-04-07 18:34:42 -070074// bionic, so cannot take advantage of the support for changed semantics (loading the same soname
75// multiple times). However, if/when we switch the above, we likely want to switch this, too,
76// to get test coverage of the code paths.
David Srbecky1baabf02015-06-16 17:12:34 +000077static constexpr bool kUseDlopenOnHost = true;
Andreas Gampefa8429b2015-04-07 18:34:42 -070078
79// For debugging, Open will print DlOpen error message if set to true.
80static constexpr bool kPrintDlOpenErrorMessage = false;
81
Andreas Gampe049cff02015-12-01 23:27:12 -080082// Note for OatFileBase and descendents:
83//
84// These are used in OatFile::Open to try all our loaders.
85//
86// The process is simple:
87//
88// 1) Allocate an instance through the standard constructor (location, executable)
89// 2) Load() to try to open the file.
90// 3) ComputeFields() to populate the OatFile fields like begin_, using FindDynamicSymbolAddress.
91// 4) PreSetup() for any steps that should be done before the final setup.
92// 5) Setup() to complete the procedure.
Richard Uhlere5fed032015-03-18 08:21:11 -070093
Andreas Gampe049cff02015-12-01 23:27:12 -080094class OatFileBase : public OatFile {
95 public:
96 virtual ~OatFileBase() {}
Richard Uhlere5fed032015-03-18 08:21:11 -070097
Andreas Gampe049cff02015-12-01 23:27:12 -080098 template <typename kOatFileBaseSubType>
David Brazdil7b49e6c2016-09-01 11:06:18 +010099 static OatFileBase* OpenOatFile(const std::string& vdex_filename,
100 const std::string& elf_filename,
Alex Light84d76052014-08-22 17:49:35 -0700101 const std::string& location,
Andreas Gampe049cff02015-12-01 23:27:12 -0800102 uint8_t* requested_base,
103 uint8_t* oat_file_begin,
104 bool writable,
105 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800106 bool low_4gb,
Richard Uhlere5fed032015-03-18 08:21:11 -0700107 const char* abs_dex_location,
Andreas Gampe049cff02015-12-01 23:27:12 -0800108 std::string* error_msg);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800109
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700110 template <typename kOatFileBaseSubType>
111 static OatFileBase* OpenOatFile(int vdex_fd,
112 int oat_fd,
113 const std::string& vdex_filename,
114 const std::string& oat_filename,
115 uint8_t* requested_base,
116 uint8_t* oat_file_begin,
117 bool writable,
118 bool executable,
119 bool low_4gb,
120 const char* abs_dex_location,
121 std::string* error_msg);
122
Andreas Gampe049cff02015-12-01 23:27:12 -0800123 protected:
124 OatFileBase(const std::string& filename, bool executable) : OatFile(filename, executable) {}
Andreas Gampefa8429b2015-04-07 18:34:42 -0700125
Andreas Gampe049cff02015-12-01 23:27:12 -0800126 virtual const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
127 std::string* error_msg) const = 0;
128
Andreas Gampe4075f832016-05-18 13:09:54 -0700129 virtual void PreLoad() = 0;
130
David Brazdil7b49e6c2016-09-01 11:06:18 +0100131 bool LoadVdex(const std::string& vdex_filename,
132 bool writable,
133 bool low_4gb,
134 std::string* error_msg);
135
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700136 bool LoadVdex(int vdex_fd,
137 const std::string& vdex_filename,
138 bool writable,
139 bool low_4gb,
140 std::string* error_msg);
141
Andreas Gampe049cff02015-12-01 23:27:12 -0800142 virtual bool Load(const std::string& elf_filename,
143 uint8_t* oat_file_begin,
144 bool writable,
145 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800146 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800147 std::string* error_msg) = 0;
148
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700149 virtual bool Load(int oat_fd,
150 uint8_t* oat_file_begin,
151 bool writable,
152 bool executable,
153 bool low_4gb,
154 std::string* error_msg) = 0;
155
Andreas Gampe049cff02015-12-01 23:27:12 -0800156 bool ComputeFields(uint8_t* requested_base,
157 const std::string& file_path,
158 std::string* error_msg);
159
160 virtual void PreSetup(const std::string& elf_filename) = 0;
161
162 bool Setup(const char* abs_dex_location, std::string* error_msg);
163
164 // Setters exposed for ElfOatFile.
165
166 void SetBegin(const uint8_t* begin) {
167 begin_ = begin;
Andreas Gampefa8429b2015-04-07 18:34:42 -0700168 }
169
Andreas Gampe049cff02015-12-01 23:27:12 -0800170 void SetEnd(const uint8_t* end) {
171 end_ = end;
172 }
173
David Brazdilc93b3be2016-09-12 18:49:58 +0100174 void SetVdex(VdexFile* vdex) {
175 vdex_.reset(vdex);
176 }
177
Andreas Gampe049cff02015-12-01 23:27:12 -0800178 private:
179 DISALLOW_COPY_AND_ASSIGN(OatFileBase);
180};
181
182template <typename kOatFileBaseSubType>
David Brazdil7b49e6c2016-09-01 11:06:18 +0100183OatFileBase* OatFileBase::OpenOatFile(const std::string& vdex_filename,
184 const std::string& elf_filename,
Andreas Gampe049cff02015-12-01 23:27:12 -0800185 const std::string& location,
186 uint8_t* requested_base,
187 uint8_t* oat_file_begin,
188 bool writable,
189 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800190 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800191 const char* abs_dex_location,
192 std::string* error_msg) {
193 std::unique_ptr<OatFileBase> ret(new kOatFileBaseSubType(location, executable));
Andreas Gampe4075f832016-05-18 13:09:54 -0700194
195 ret->PreLoad();
196
Andreas Gampe049cff02015-12-01 23:27:12 -0800197 if (!ret->Load(elf_filename,
198 oat_file_begin,
199 writable,
200 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800201 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800202 error_msg)) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800203 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800204 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800205
Andreas Gampe049cff02015-12-01 23:27:12 -0800206 if (!ret->ComputeFields(requested_base, elf_filename, error_msg)) {
207 return nullptr;
208 }
Andreas Gampe4075f832016-05-18 13:09:54 -0700209
David Srbeckyec2cdf42017-12-08 16:21:25 +0000210 if (!ret->LoadVdex(vdex_filename, writable, low_4gb, error_msg)) {
211 return nullptr;
212 }
213
Andreas Gampe049cff02015-12-01 23:27:12 -0800214 ret->PreSetup(elf_filename);
215
216 if (!ret->Setup(abs_dex_location, error_msg)) {
217 return nullptr;
218 }
219
Dave Allison69dfe512014-07-11 17:11:58 +0000220 return ret.release();
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800221}
222
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700223template <typename kOatFileBaseSubType>
224OatFileBase* OatFileBase::OpenOatFile(int vdex_fd,
225 int oat_fd,
226 const std::string& vdex_location,
227 const std::string& oat_location,
228 uint8_t* requested_base,
229 uint8_t* oat_file_begin,
230 bool writable,
231 bool executable,
232 bool low_4gb,
233 const char* abs_dex_location,
234 std::string* error_msg) {
235 std::unique_ptr<OatFileBase> ret(new kOatFileBaseSubType(oat_location, executable));
236
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700237 if (!ret->Load(oat_fd,
238 oat_file_begin,
239 writable,
240 executable,
241 low_4gb,
242 error_msg)) {
243 return nullptr;
244 }
245
246 if (!ret->ComputeFields(requested_base, oat_location, error_msg)) {
247 return nullptr;
248 }
249
David Srbeckyec2cdf42017-12-08 16:21:25 +0000250 if (!ret->LoadVdex(vdex_fd, vdex_location, writable, low_4gb, error_msg)) {
251 return nullptr;
252 }
253
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700254 ret->PreSetup(oat_location);
255
256 if (!ret->Setup(abs_dex_location, error_msg)) {
257 return nullptr;
258 }
259
260 return ret.release();
261}
262
David Brazdil7b49e6c2016-09-01 11:06:18 +0100263bool OatFileBase::LoadVdex(const std::string& vdex_filename,
264 bool writable,
265 bool low_4gb,
266 std::string* error_msg) {
David Srbeckyec2cdf42017-12-08 16:21:25 +0000267 vdex_ = VdexFile::OpenAtAddress(vdex_begin_,
268 vdex_end_ - vdex_begin_,
Andreas Gampec1fc4492018-01-10 14:19:36 -0800269 vdex_begin_ != nullptr /* mmap_reuse */,
David Srbeckyec2cdf42017-12-08 16:21:25 +0000270 vdex_filename,
271 writable,
272 low_4gb,
273 /* unquicken*/ false,
274 error_msg);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100275 if (vdex_.get() == nullptr) {
276 *error_msg = StringPrintf("Failed to load vdex file '%s' %s",
277 vdex_filename.c_str(),
278 error_msg->c_str());
279 return false;
280 }
281 return true;
282}
283
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700284bool OatFileBase::LoadVdex(int vdex_fd,
285 const std::string& vdex_filename,
286 bool writable,
287 bool low_4gb,
288 std::string* error_msg) {
289 if (vdex_fd != -1) {
290 struct stat s;
291 int rc = TEMP_FAILURE_RETRY(fstat(vdex_fd, &s));
292 if (rc == -1) {
293 PLOG(WARNING) << "Failed getting length of vdex file";
294 } else {
David Srbeckyec2cdf42017-12-08 16:21:25 +0000295 vdex_ = VdexFile::OpenAtAddress(vdex_begin_,
296 vdex_end_ - vdex_begin_,
Andreas Gampec1fc4492018-01-10 14:19:36 -0800297 vdex_begin_ != nullptr /* mmap_reuse */,
David Srbeckyec2cdf42017-12-08 16:21:25 +0000298 vdex_fd,
299 s.st_size,
300 vdex_filename,
301 writable,
302 low_4gb,
303 false /* unquicken */,
304 error_msg);
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700305 if (vdex_.get() == nullptr) {
306 *error_msg = "Failed opening vdex file.";
307 return false;
308 }
309 }
310 }
311 return true;
312}
313
Andreas Gampe049cff02015-12-01 23:27:12 -0800314bool OatFileBase::ComputeFields(uint8_t* requested_base,
315 const std::string& file_path,
316 std::string* error_msg) {
317 std::string symbol_error_msg;
318 begin_ = FindDynamicSymbolAddress("oatdata", &symbol_error_msg);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700319 if (begin_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800320 *error_msg = StringPrintf("Failed to find oatdata symbol in '%s' %s",
321 file_path.c_str(),
322 symbol_error_msg.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700323 return false;
324 }
325 if (requested_base != nullptr && begin_ != requested_base) {
Nicolas Geoffrayf97cf2a2016-03-09 15:36:23 +0000326 // Host can fail this check. Do not dump there to avoid polluting the output.
Andreas Gampe7ec09042016-04-01 17:20:49 -0700327 if (kIsTargetBuild && (kIsDebugBuild || VLOG_IS_ON(oat))) {
Andreas Gampe170331f2017-12-07 18:41:03 -0800328 PrintFileToLog("/proc/self/maps", android::base::LogSeverity::WARNING);
Nicolas Geoffrayf97cf2a2016-03-09 15:36:23 +0000329 }
Andreas Gampefa8429b2015-04-07 18:34:42 -0700330 *error_msg = StringPrintf("Failed to find oatdata symbol at expected address: "
Andreas Gampe049cff02015-12-01 23:27:12 -0800331 "oatdata=%p != expected=%p. See process maps in the log.",
332 begin_, requested_base);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700333 return false;
334 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800335 end_ = FindDynamicSymbolAddress("oatlastword", &symbol_error_msg);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700336 if (end_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800337 *error_msg = StringPrintf("Failed to find oatlastword symbol in '%s' %s",
338 file_path.c_str(),
339 symbol_error_msg.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700340 return false;
341 }
342 // Readjust to be non-inclusive upper bound.
343 end_ += sizeof(uint32_t);
344
Andreas Gampe049cff02015-12-01 23:27:12 -0800345 bss_begin_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbss", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700346 if (bss_begin_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800347 // No .bss section.
Andreas Gampefa8429b2015-04-07 18:34:42 -0700348 bss_end_ = nullptr;
Andreas Gampefa8429b2015-04-07 18:34:42 -0700349 } else {
Andreas Gampe049cff02015-12-01 23:27:12 -0800350 bss_end_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbsslastword", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700351 if (bss_end_ == nullptr) {
David Srbeckyec2cdf42017-12-08 16:21:25 +0000352 *error_msg = StringPrintf("Failed to find oatbsslastword symbol in '%s'", file_path.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700353 return false;
354 }
355 // Readjust to be non-inclusive upper bound.
356 bss_end_ += sizeof(uint32_t);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100357 // Find bss methods if present.
358 bss_methods_ =
359 const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbssmethods", &symbol_error_msg));
Vladimir Markoaad75c62016-10-03 08:46:48 +0000360 // Find bss roots if present.
361 bss_roots_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbssroots", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700362 }
363
David Srbeckyec2cdf42017-12-08 16:21:25 +0000364 vdex_begin_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatdex", &symbol_error_msg));
365 if (vdex_begin_ == nullptr) {
366 // No .vdex section.
367 vdex_end_ = nullptr;
368 } else {
369 vdex_end_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatdexlastword", &symbol_error_msg));
370 if (vdex_end_ == nullptr) {
371 *error_msg = StringPrintf("Failed to find oatdexlastword symbol in '%s'", file_path.c_str());
372 return false;
373 }
374 // Readjust to be non-inclusive upper bound.
375 vdex_end_ += sizeof(uint32_t);
376 }
377
Andreas Gampe049cff02015-12-01 23:27:12 -0800378 return true;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800379}
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800380
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100381// Read an unaligned entry from the OatDexFile data in OatFile and advance the read
382// position by the number of bytes read, i.e. sizeof(T).
383// Return true on success, false if the read would go beyond the end of the OatFile.
384template <typename T>
Vladimir Marko722fa982015-10-19 18:18:27 +0100385inline static bool ReadOatDexFileData(const OatFile& oat_file,
386 /*inout*/const uint8_t** oat,
387 /*out*/T* value) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100388 DCHECK(oat != nullptr);
389 DCHECK(value != nullptr);
390 DCHECK_LE(*oat, oat_file.End());
391 if (UNLIKELY(static_cast<size_t>(oat_file.End() - *oat) < sizeof(T))) {
392 return false;
393 }
394 static_assert(std::is_trivial<T>::value, "T must be a trivial type");
395 typedef __attribute__((__aligned__(1))) T unaligned_type;
396 *value = *reinterpret_cast<const unaligned_type*>(*oat);
397 *oat += sizeof(T);
398 return true;
399}
400
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100401static inline bool MapConstantTables(const gc::space::ImageSpace* space,
402 uint8_t* address) {
403 // If MREMAP_DUP is ever merged to Linux kernel, use it to avoid the unnecessary open()/close().
404 // Note: The current approach relies on the filename still referencing the same inode.
405
406 File file(space->GetImageFilename(), O_RDONLY, /* checkUsage */ false);
407 if (!file.IsOpened()) {
408 LOG(ERROR) << "Failed to open boot image file " << space->GetImageFilename();
409 return false;
410 }
411
412 uint32_t offset = space->GetImageHeader().GetBootImageConstantTablesOffset();
413 uint32_t size = space->GetImageHeader().GetBootImageConstantTablesSize();
414 std::string error_msg;
415 std::unique_ptr<MemMap> mem_map(MemMap::MapFileAtAddress(address,
416 size,
417 PROT_READ,
418 MAP_PRIVATE,
419 file.Fd(),
420 offset,
421 /* low_4gb */ false,
422 /* reuse */ true,
423 file.GetPath().c_str(),
424 &error_msg));
425 if (mem_map == nullptr) {
426 LOG(ERROR) << "Failed to mmap boot image tables from file " << space->GetImageFilename();
427 return false;
428 }
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
478static void DCheckIndexToBssMapping(OatFile* oat_file,
479 uint32_t number_of_indexes,
480 size_t slot_size,
481 const IndexBssMapping* index_bss_mapping) {
482 if (kIsDebugBuild && index_bss_mapping != nullptr) {
483 size_t index_bits = IndexBssMappingEntry::IndexBits(number_of_indexes);
484 const IndexBssMappingEntry* prev_entry = nullptr;
485 for (const IndexBssMappingEntry& entry : *index_bss_mapping) {
486 CHECK_ALIGNED_PARAM(entry.bss_offset, slot_size);
487 // When loading a non-executable ElfOatFile, .bss symbols are not even
488 // looked up, so we cannot verify the offset against BssSize().
489 if (oat_file->IsExecutable()) {
490 CHECK_LT(entry.bss_offset, oat_file->BssSize());
491 }
492 uint32_t mask = entry.GetMask(index_bits);
493 CHECK_LE(POPCOUNT(mask) * slot_size, entry.bss_offset);
494 size_t index_mask_span = (mask != 0u) ? 32u - index_bits - CTZ(mask) : 0u;
495 CHECK_LE(index_mask_span, entry.GetIndex(index_bits));
496 if (prev_entry != nullptr) {
497 CHECK_LT(prev_entry->GetIndex(index_bits), entry.GetIndex(index_bits) - index_mask_span);
498 }
499 prev_entry = &entry;
500 }
501 CHECK_LT(prev_entry->GetIndex(index_bits), number_of_indexes);
502 }
503}
504
Andreas Gampe049cff02015-12-01 23:27:12 -0800505bool OatFileBase::Setup(const char* abs_dex_location, std::string* error_msg) {
Brian Carlstromf1b30302013-03-28 10:35:32 -0700506 if (!GetOatHeader().IsValid()) {
Andreas Gampe2bcb3b22014-12-12 15:25:14 -0800507 std::string cause = GetOatHeader().GetValidationErrorMessage();
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100508 *error_msg = StringPrintf("Invalid oat header for '%s': %s",
509 GetLocation().c_str(),
Andreas Gampe2bcb3b22014-12-12 15:25:14 -0800510 cause.c_str());
Brian Carlstromf1b30302013-03-28 10:35:32 -0700511 return false;
512 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100513 PointerSize pointer_size = GetInstructionSetPointerSize(GetOatHeader().GetInstructionSet());
514 size_t key_value_store_size =
515 (Size() >= sizeof(OatHeader)) ? GetOatHeader().GetKeyValueStoreSize() : 0u;
516 if (Size() < sizeof(OatHeader) + key_value_store_size) {
517 *error_msg = StringPrintf("In oat file '%s' found truncated OatHeader, "
518 "size = %zu < %zu + %zu",
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100519 GetLocation().c_str(),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100520 Size(),
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100521 sizeof(OatHeader),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100522 key_value_store_size);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700523 return false;
524 }
525
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100526 size_t oat_dex_files_offset = GetOatHeader().GetOatDexFilesOffset();
527 if (oat_dex_files_offset < GetOatHeader().GetHeaderSize() || oat_dex_files_offset > Size()) {
528 *error_msg = StringPrintf("In oat file '%s' found invalid oat dex files offset: "
529 "%zu is not in [%zu, %zu]",
530 GetLocation().c_str(),
531 oat_dex_files_offset,
532 GetOatHeader().GetHeaderSize(),
533 Size());
534 return false;
535 }
536 const uint8_t* oat = Begin() + oat_dex_files_offset; // Jump to the OatDexFile records.
537
538 DCHECK_GE(static_cast<size_t>(pointer_size), alignof(GcRoot<mirror::Object>));
539 if (!IsAligned<kPageSize>(bss_begin_) ||
540 !IsAlignedParam(bss_methods_, static_cast<size_t>(pointer_size)) ||
541 !IsAlignedParam(bss_roots_, static_cast<size_t>(pointer_size)) ||
Vladimir Markoaad75c62016-10-03 08:46:48 +0000542 !IsAligned<alignof(GcRoot<mirror::Object>)>(bss_end_)) {
543 *error_msg = StringPrintf("In oat file '%s' found unaligned bss symbol(s): "
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100544 "begin = %p, methods_ = %p, roots = %p, end = %p",
Vladimir Markoaad75c62016-10-03 08:46:48 +0000545 GetLocation().c_str(),
546 bss_begin_,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100547 bss_methods_,
Vladimir Markoaad75c62016-10-03 08:46:48 +0000548 bss_roots_,
549 bss_end_);
550 return false;
551 }
552
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100553 if ((bss_methods_ != nullptr && (bss_methods_ < bss_begin_ || bss_methods_ > bss_end_)) ||
554 (bss_roots_ != nullptr && (bss_roots_ < bss_begin_ || bss_roots_ > bss_end_)) ||
555 (bss_methods_ != nullptr && bss_roots_ != nullptr && bss_methods_ > bss_roots_)) {
556 *error_msg = StringPrintf("In oat file '%s' found bss symbol(s) outside .bss or unordered: "
Vladimir Marko0f3c7002017-09-07 14:15:56 +0100557 "begin = %p, methods = %p, roots = %p, end = %p",
Vladimir Markoaad75c62016-10-03 08:46:48 +0000558 GetLocation().c_str(),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000559 bss_begin_,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100560 bss_methods_,
561 bss_roots_,
Vladimir Markoaad75c62016-10-03 08:46:48 +0000562 bss_end_);
563 return false;
564 }
565
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100566 uint8_t* after_tables =
567 (bss_methods_ != nullptr) ? bss_methods_ : bss_roots_; // May be null.
568 uint8_t* boot_image_tables = (bss_begin_ == after_tables) ? nullptr : bss_begin_;
569 uint8_t* boot_image_tables_end =
570 (bss_begin_ == after_tables) ? nullptr : (after_tables != nullptr) ? after_tables : bss_end_;
571 DCHECK_EQ(boot_image_tables != nullptr, boot_image_tables_end != nullptr);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100572 uint32_t dex_file_count = GetOatHeader().GetDexFileCount();
573 oat_dex_files_storage_.reserve(dex_file_count);
574 for (size_t i = 0; i < dex_file_count; i++) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100575 uint32_t dex_file_location_size;
576 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_location_size))) {
577 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu truncated after dex file "
578 "location size",
579 GetLocation().c_str(),
580 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700581 return false;
582 }
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100583 if (UNLIKELY(dex_file_location_size == 0U)) {
584 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu with empty location name",
585 GetLocation().c_str(),
586 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700587 return false;
588 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000589 if (UNLIKELY(static_cast<size_t>(End() - oat) < dex_file_location_size)) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100590 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu with truncated dex file "
591 "location",
592 GetLocation().c_str(),
593 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700594 return false;
595 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000596 const char* dex_file_location_data = reinterpret_cast<const char*>(oat);
597 oat += dex_file_location_size;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700598
Richard Uhlere5fed032015-03-18 08:21:11 -0700599 std::string dex_file_location = ResolveRelativeEncodedDexLocation(
600 abs_dex_location,
601 std::string(dex_file_location_data, dex_file_location_size));
Brian Carlstrome24fa612011-09-29 00:53:55 -0700602
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100603 uint32_t dex_file_checksum;
604 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_checksum))) {
605 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated after "
606 "dex file checksum",
607 GetLocation().c_str(),
608 i,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700609 dex_file_location.c_str());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700610 return false;
611 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700612
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100613 uint32_t dex_file_offset;
614 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_offset))) {
615 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated "
616 "after dex file offsets",
617 GetLocation().c_str(),
618 i,
619 dex_file_location.c_str());
620 return false;
621 }
Andreas Gampee166e672017-12-19 18:59:29 +0000622 if (UNLIKELY(dex_file_offset == 0U)) {
623 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with zero dex "
624 "file offset",
625 GetLocation().c_str(),
626 i,
627 dex_file_location.c_str());
628 return false;
629 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100630 if (UNLIKELY(dex_file_offset > DexSize())) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100631 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
632 "offset %u > %zu",
633 GetLocation().c_str(),
634 i,
635 dex_file_location.c_str(),
636 dex_file_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100637 DexSize());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700638 return false;
639 }
Andreas Gampee166e672017-12-19 18:59:29 +0000640 if (UNLIKELY(DexSize() - dex_file_offset < sizeof(DexFile::Header))) {
641 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
642 "offset %u of %zu but the size of dex file header is %zu",
643 GetLocation().c_str(),
644 i,
645 dex_file_location.c_str(),
646 dex_file_offset,
647 DexSize(),
648 sizeof(DexFile::Header));
649 return false;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000650 }
Brian Carlstrom89521892011-12-07 22:05:07 -0800651
Andreas Gampee166e672017-12-19 18:59:29 +0000652 const uint8_t* dex_file_pointer = DexBegin() + dex_file_offset;
653
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700654 const bool valid_magic = DexFileLoader::IsMagicValid(dex_file_pointer);
Mathieu Chartier7b074bf2017-09-25 16:22:36 -0700655 if (UNLIKELY(!valid_magic)) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100656 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with invalid "
657 "dex file magic '%s'",
658 GetLocation().c_str(),
659 i,
660 dex_file_location.c_str(),
661 dex_file_pointer);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700662 return false;
663 }
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700664 if (UNLIKELY(!DexFileLoader::IsVersionAndMagicValid(dex_file_pointer))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100665 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with invalid "
666 "dex file version '%s'",
667 GetLocation().c_str(),
668 i,
669 dex_file_location.c_str(),
670 dex_file_pointer);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700671 return false;
672 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800673 const DexFile::Header* header = reinterpret_cast<const DexFile::Header*>(dex_file_pointer);
Andreas Gampee166e672017-12-19 18:59:29 +0000674 if (DexSize() - dex_file_offset < header->file_size_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000675 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
676 "offset %u and size %u truncated at %zu",
677 GetLocation().c_str(),
678 i,
679 dex_file_location.c_str(),
680 dex_file_offset,
681 header->file_size_,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100682 DexSize());
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000683 return false;
684 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300685
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000686 uint32_t class_offsets_offset;
687 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &class_offsets_offset))) {
688 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated "
689 "after class offsets offset",
690 GetLocation().c_str(),
691 i,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300692 dex_file_location.c_str());
693 return false;
694 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000695 if (UNLIKELY(class_offsets_offset > Size()) ||
696 UNLIKELY((Size() - class_offsets_offset) / sizeof(uint32_t) < header->class_defs_size_)) {
697 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with truncated "
698 "class offsets, offset %u of %zu, class defs %u",
699 GetLocation().c_str(),
700 i,
701 dex_file_location.c_str(),
702 class_offsets_offset,
703 Size(),
704 header->class_defs_size_);
705 return false;
706 }
707 if (UNLIKELY(!IsAligned<alignof(uint32_t)>(class_offsets_offset))) {
708 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with unaligned "
709 "class offsets, offset %u",
710 GetLocation().c_str(),
711 i,
712 dex_file_location.c_str(),
713 class_offsets_offset);
714 return false;
715 }
716 const uint32_t* class_offsets_pointer =
717 reinterpret_cast<const uint32_t*>(Begin() + class_offsets_offset);
718
719 uint32_t lookup_table_offset;
720 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &lookup_table_offset))) {
721 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zd for '%s' truncated "
722 "after lookup table offset",
723 GetLocation().c_str(),
724 i,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300725 dex_file_location.c_str());
726 return false;
727 }
728 const uint8_t* lookup_table_data = lookup_table_offset != 0u
729 ? Begin() + lookup_table_offset
730 : nullptr;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000731 if (lookup_table_offset != 0u &&
732 (UNLIKELY(lookup_table_offset > Size()) ||
733 UNLIKELY(Size() - lookup_table_offset <
734 TypeLookupTable::RawDataLength(header->class_defs_size_)))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100735 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with truncated "
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000736 "type lookup table, offset %u of %zu, class defs %u",
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100737 GetLocation().c_str(),
738 i,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000739 dex_file_location.c_str(),
740 lookup_table_offset,
741 Size(),
742 header->class_defs_size_);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700743 return false;
744 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700745
Mathieu Chartier120aa282017-08-05 16:03:03 -0700746 uint32_t dex_layout_sections_offset;
747 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_layout_sections_offset))) {
748 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zd for '%s' truncated "
749 "after dex layout sections offset",
750 GetLocation().c_str(),
751 i,
752 dex_file_location.c_str());
753 return false;
754 }
755 const DexLayoutSections* const dex_layout_sections = dex_layout_sections_offset != 0
756 ? reinterpret_cast<const DexLayoutSections*>(Begin() + dex_layout_sections_offset)
757 : nullptr;
758
Vladimir Markof3c52b42017-11-17 17:32:12 +0000759 const IndexBssMapping* method_bss_mapping;
760 const IndexBssMapping* type_bss_mapping;
761 const IndexBssMapping* string_bss_mapping;
762 if (!ReadIndexBssMapping(
763 this, &oat, i, dex_file_location, "method", &method_bss_mapping, error_msg) ||
764 !ReadIndexBssMapping(
765 this, &oat, i, dex_file_location, "type", &type_bss_mapping, error_msg) ||
766 !ReadIndexBssMapping(
767 this, &oat, i, dex_file_location, "string", &string_bss_mapping, error_msg)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100768 return false;
769 }
Vladimir Markof3c52b42017-11-17 17:32:12 +0000770 DCheckIndexToBssMapping(
771 this, header->method_ids_size_, static_cast<size_t>(pointer_size), method_bss_mapping);
772 DCheckIndexToBssMapping(
773 this, header->type_ids_size_, sizeof(GcRoot<mirror::Class>), type_bss_mapping);
774 DCheckIndexToBssMapping(
775 this, header->string_ids_size_, sizeof(GcRoot<mirror::String>), string_bss_mapping);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100776
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700777 std::string canonical_location =
778 DexFileLoader::GetDexCanonicalLocation(dex_file_location.c_str());
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100779
780 // Create the OatDexFile and add it to the owning container.
Vladimir Marko539690a2014-06-05 18:36:42 +0100781 OatDexFile* oat_dex_file = new OatDexFile(this,
782 dex_file_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100783 canonical_location,
Vladimir Marko539690a2014-06-05 18:36:42 +0100784 dex_file_checksum,
785 dex_file_pointer,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300786 lookup_table_data,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100787 method_bss_mapping,
Vladimir Markof3c52b42017-11-17 17:32:12 +0000788 type_bss_mapping,
789 string_bss_mapping,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000790 class_offsets_pointer,
Mathieu Chartier120aa282017-08-05 16:03:03 -0700791 dex_layout_sections);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100792 oat_dex_files_storage_.push_back(oat_dex_file);
793
794 // Add the location and canonical location (if different) to the oat_dex_files_ table.
Vladimir Marko3f5838d2014-08-07 18:07:18 +0100795 StringPiece key(oat_dex_file->GetDexFileLocation());
Vladimir Marko539690a2014-06-05 18:36:42 +0100796 oat_dex_files_.Put(key, oat_dex_file);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100797 if (canonical_location != dex_file_location) {
798 StringPiece canonical_key(oat_dex_file->GetCanonicalDexFileLocation());
799 oat_dex_files_.Put(canonical_key, oat_dex_file);
800 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700801 }
Vladimir Marko09d09432015-09-08 13:47:48 +0100802
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100803 if (boot_image_tables != nullptr) {
Vladimir Marko667585a2017-09-29 10:42:31 +0100804 Runtime* runtime = Runtime::Current();
805 if (UNLIKELY(runtime == nullptr)) {
806 // This must be oatdump without boot image. Make sure the .bss is inaccessible.
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700807 CheckedCall(mprotect, "protect bss", const_cast<uint8_t*>(BssBegin()), BssSize(), PROT_NONE);
Vladimir Marko667585a2017-09-29 10:42:31 +0100808 } else {
809 // Map boot image tables into the .bss. The reserved size must match size of the tables.
810 size_t reserved_size = static_cast<size_t>(boot_image_tables_end - boot_image_tables);
811 size_t tables_size = 0u;
812 for (gc::space::ImageSpace* space : runtime->GetHeap()->GetBootImageSpaces()) {
813 tables_size += space->GetImageHeader().GetBootImageConstantTablesSize();
814 DCHECK_ALIGNED(tables_size, kPageSize);
815 }
816 if (tables_size != reserved_size) {
817 *error_msg = StringPrintf("In oat file '%s' found unexpected boot image table sizes, "
818 " %zu bytes, should be %zu.",
819 GetLocation().c_str(),
820 reserved_size,
821 tables_size);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100822 return false;
823 }
Vladimir Marko667585a2017-09-29 10:42:31 +0100824 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
825 uint32_t current_tables_size = space->GetImageHeader().GetBootImageConstantTablesSize();
826 if (current_tables_size != 0u && !MapConstantTables(space, boot_image_tables)) {
827 return false;
828 }
829 boot_image_tables += current_tables_size;
830 }
831 DCHECK(boot_image_tables == boot_image_tables_end);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100832 }
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100833 }
Brian Carlstromf1b30302013-03-28 10:35:32 -0700834 return true;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700835}
836
Andreas Gampe049cff02015-12-01 23:27:12 -0800837////////////////////////
838// OatFile via dlopen //
839////////////////////////
840
Andreas Gampe049cff02015-12-01 23:27:12 -0800841class DlOpenOatFile FINAL : public OatFileBase {
842 public:
843 DlOpenOatFile(const std::string& filename, bool executable)
844 : OatFileBase(filename, executable),
845 dlopen_handle_(nullptr),
Richard Uhlera206c742016-05-24 15:04:22 -0700846 shared_objects_before_(0) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800847 }
848
849 ~DlOpenOatFile() {
850 if (dlopen_handle_ != nullptr) {
Richard Uhlera206c742016-05-24 15:04:22 -0700851 if (!kIsTargetBuild) {
852 MutexLock mu(Thread::Current(), *Locks::host_dlopen_handles_lock_);
853 host_dlopen_handles_.erase(dlopen_handle_);
Mathieu Chartierc7d3f4b2016-06-01 10:48:19 -0700854 dlclose(dlopen_handle_);
855 } else {
856 dlclose(dlopen_handle_);
Richard Uhlera206c742016-05-24 15:04:22 -0700857 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800858 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800859 }
860
861 protected:
862 const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
863 std::string* error_msg) const OVERRIDE {
864 const uint8_t* ptr =
865 reinterpret_cast<const uint8_t*>(dlsym(dlopen_handle_, symbol_name.c_str()));
866 if (ptr == nullptr) {
867 *error_msg = dlerror();
868 }
869 return ptr;
870 }
871
Andreas Gampe4075f832016-05-18 13:09:54 -0700872 void PreLoad() OVERRIDE;
873
Andreas Gampe049cff02015-12-01 23:27:12 -0800874 bool Load(const std::string& elf_filename,
875 uint8_t* oat_file_begin,
876 bool writable,
877 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800878 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800879 std::string* error_msg) OVERRIDE;
880
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700881 bool Load(int, uint8_t*, bool, bool, bool, std::string*) {
882 return false;
883 }
884
Andreas Gampe049cff02015-12-01 23:27:12 -0800885 // Ask the linker where it mmaped the file and notify our mmap wrapper of the regions.
886 void PreSetup(const std::string& elf_filename) OVERRIDE;
887
888 private:
889 bool Dlopen(const std::string& elf_filename,
890 uint8_t* oat_file_begin,
891 std::string* error_msg);
892
Richard Uhlera206c742016-05-24 15:04:22 -0700893 // On the host, if the same library is loaded again with dlopen the same
894 // file handle is returned. This differs from the behavior of dlopen on the
895 // target, where dlopen reloads the library at a different address every
896 // time you load it. The runtime relies on the target behavior to ensure
897 // each instance of the loaded library has a unique dex cache. To avoid
898 // problems, we fall back to our own linker in the case when the same
899 // library is opened multiple times on host. dlopen_handles_ is used to
900 // detect that case.
901 // Guarded by host_dlopen_handles_lock_;
902 static std::unordered_set<void*> host_dlopen_handles_;
903
Andreas Gampe049cff02015-12-01 23:27:12 -0800904 // dlopen handle during runtime.
905 void* dlopen_handle_; // TODO: Unique_ptr with custom deleter.
906
907 // Dummy memory map objects corresponding to the regions mapped by dlopen.
908 std::vector<std::unique_ptr<MemMap>> dlopen_mmaps_;
909
Andreas Gampe4075f832016-05-18 13:09:54 -0700910 // The number of shared objects the linker told us about before loading. Used to
911 // (optimistically) optimize the PreSetup stage (see comment there).
912 size_t shared_objects_before_;
913
Andreas Gampe049cff02015-12-01 23:27:12 -0800914 DISALLOW_COPY_AND_ASSIGN(DlOpenOatFile);
915};
916
Richard Uhlera206c742016-05-24 15:04:22 -0700917std::unordered_set<void*> DlOpenOatFile::host_dlopen_handles_;
918
Andreas Gampe4075f832016-05-18 13:09:54 -0700919void DlOpenOatFile::PreLoad() {
920#ifdef __APPLE__
Andreas Gampe39004a62016-05-18 21:27:00 -0700921 UNUSED(shared_objects_before_);
Andreas Gampe4075f832016-05-18 13:09:54 -0700922 LOG(FATAL) << "Should not reach here.";
923 UNREACHABLE();
924#else
925 // Count the entries in dl_iterate_phdr we get at this point in time.
926 struct dl_iterate_context {
927 static int callback(struct dl_phdr_info *info ATTRIBUTE_UNUSED,
928 size_t size ATTRIBUTE_UNUSED,
929 void *data) {
930 reinterpret_cast<dl_iterate_context*>(data)->count++;
931 return 0; // Continue iteration.
932 }
933 size_t count = 0;
934 } context;
935
936 dl_iterate_phdr(dl_iterate_context::callback, &context);
937 shared_objects_before_ = context.count;
938#endif
939}
940
Andreas Gampe049cff02015-12-01 23:27:12 -0800941bool DlOpenOatFile::Load(const std::string& elf_filename,
942 uint8_t* oat_file_begin,
943 bool writable,
944 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800945 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800946 std::string* error_msg) {
947 // Use dlopen only when flagged to do so, and when it's OK to load things executable.
948 // TODO: Also try when not executable? The issue here could be re-mapping as writable (as
949 // !executable is a sign that we may want to patch), which may not be allowed for
950 // various reasons.
951 if (!kUseDlopen) {
952 *error_msg = "DlOpen is disabled.";
953 return false;
954 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800955 if (low_4gb) {
956 *error_msg = "DlOpen does not support low 4gb loading.";
957 return false;
958 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800959 if (writable) {
960 *error_msg = "DlOpen does not support writable loading.";
961 return false;
962 }
963 if (!executable) {
964 *error_msg = "DlOpen does not support non-executable loading.";
965 return false;
966 }
967
968 // dlopen always returns the same library if it is already opened on the host. For this reason
969 // we only use dlopen if we are the target or we do not already have the dex file opened. Having
970 // the same library loaded multiple times at different addresses is required for class unloading
971 // and for having dex caches arrays in the .bss section.
972 if (!kIsTargetBuild) {
973 if (!kUseDlopenOnHost) {
974 *error_msg = "DlOpen disabled for host.";
975 return false;
976 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800977 }
978
979 bool success = Dlopen(elf_filename, oat_file_begin, error_msg);
980 DCHECK(dlopen_handle_ != nullptr || !success);
981
982 return success;
983}
984
985bool DlOpenOatFile::Dlopen(const std::string& elf_filename,
986 uint8_t* oat_file_begin,
987 std::string* error_msg) {
988#ifdef __APPLE__
989 // The dl_iterate_phdr syscall is missing. There is similar API on OSX,
990 // but let's fallback to the custom loading code for the time being.
991 UNUSED(elf_filename, oat_file_begin);
992 *error_msg = "Dlopen unsupported on Mac.";
993 return false;
994#else
995 {
996 UniqueCPtr<char> absolute_path(realpath(elf_filename.c_str(), nullptr));
997 if (absolute_path == nullptr) {
998 *error_msg = StringPrintf("Failed to find absolute path for '%s'", elf_filename.c_str());
999 return false;
1000 }
Bilyan Borisovbb661c02016-04-04 16:27:32 +01001001#ifdef ART_TARGET_ANDROID
Anton Kirilov3a2e78e2017-01-06 13:33:42 +00001002 android_dlextinfo extinfo = {};
Andreas Gampe049cff02015-12-01 23:27:12 -08001003 extinfo.flags = ANDROID_DLEXT_FORCE_LOAD | // Force-load, don't reuse handle
1004 // (open oat files multiple
1005 // times).
1006 ANDROID_DLEXT_FORCE_FIXED_VADDR; // Take a non-zero vaddr as absolute
1007 // (non-pic boot image).
Andreas Gampe226b91e2015-12-02 10:29:33 -08001008 if (oat_file_begin != nullptr) { //
1009 extinfo.flags |= ANDROID_DLEXT_LOAD_AT_FIXED_ADDRESS; // Use the requested addr if
1010 extinfo.reserved_addr = oat_file_begin; // vaddr = 0.
1011 } // (pic boot image).
Andreas Gampe049cff02015-12-01 23:27:12 -08001012 dlopen_handle_ = android_dlopen_ext(absolute_path.get(), RTLD_NOW, &extinfo);
1013#else
Andreas Gampe049cff02015-12-01 23:27:12 -08001014 UNUSED(oat_file_begin);
Julien Duraj1af0c4f2016-11-16 14:05:48 +00001015 static_assert(!kIsTargetBuild || kIsTargetLinux, "host_dlopen_handles_ will leak handles");
Mathieu Chartierc7d3f4b2016-06-01 10:48:19 -07001016 MutexLock mu(Thread::Current(), *Locks::host_dlopen_handles_lock_);
Richard Uhlera206c742016-05-24 15:04:22 -07001017 dlopen_handle_ = dlopen(absolute_path.get(), RTLD_NOW);
1018 if (dlopen_handle_ != nullptr) {
Richard Uhlera206c742016-05-24 15:04:22 -07001019 if (!host_dlopen_handles_.insert(dlopen_handle_).second) {
1020 dlclose(dlopen_handle_);
1021 dlopen_handle_ = nullptr;
1022 *error_msg = StringPrintf("host dlopen re-opened '%s'", elf_filename.c_str());
1023 return false;
1024 }
1025 }
Bilyan Borisovbb661c02016-04-04 16:27:32 +01001026#endif // ART_TARGET_ANDROID
Andreas Gampe049cff02015-12-01 23:27:12 -08001027 }
1028 if (dlopen_handle_ == nullptr) {
1029 *error_msg = StringPrintf("Failed to dlopen '%s': %s", elf_filename.c_str(), dlerror());
1030 return false;
1031 }
1032 return true;
1033#endif
1034}
1035
1036void DlOpenOatFile::PreSetup(const std::string& elf_filename) {
Andreas Gampe74f07b52015-12-02 11:53:26 -08001037#ifdef __APPLE__
1038 UNUSED(elf_filename);
1039 LOG(FATAL) << "Should not reach here.";
1040 UNREACHABLE();
1041#else
Andreas Gampe049cff02015-12-01 23:27:12 -08001042 struct dl_iterate_context {
1043 static int callback(struct dl_phdr_info *info, size_t /* size */, void *data) {
1044 auto* context = reinterpret_cast<dl_iterate_context*>(data);
Andreas Gampe4075f832016-05-18 13:09:54 -07001045 context->shared_objects_seen++;
1046 if (context->shared_objects_seen < context->shared_objects_before) {
1047 // We haven't been called yet for anything we haven't seen before. Just continue.
1048 // Note: this is aggressively optimistic. If another thread was unloading a library,
1049 // we may miss out here. However, this does not happen often in practice.
1050 return 0;
1051 }
1052
Andreas Gampe049cff02015-12-01 23:27:12 -08001053 // See whether this callback corresponds to the file which we have just loaded.
1054 bool contains_begin = false;
1055 for (int i = 0; i < info->dlpi_phnum; i++) {
1056 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
1057 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
1058 info->dlpi_phdr[i].p_vaddr);
1059 size_t memsz = info->dlpi_phdr[i].p_memsz;
1060 if (vaddr <= context->begin_ && context->begin_ < vaddr + memsz) {
1061 contains_begin = true;
1062 break;
1063 }
1064 }
1065 }
1066 // Add dummy mmaps for this file.
1067 if (contains_begin) {
1068 for (int i = 0; i < info->dlpi_phnum; i++) {
1069 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
1070 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
1071 info->dlpi_phdr[i].p_vaddr);
1072 size_t memsz = info->dlpi_phdr[i].p_memsz;
1073 MemMap* mmap = MemMap::MapDummy(info->dlpi_name, vaddr, memsz);
1074 context->dlopen_mmaps_->push_back(std::unique_ptr<MemMap>(mmap));
1075 }
1076 }
1077 return 1; // Stop iteration and return 1 from dl_iterate_phdr.
1078 }
1079 return 0; // Continue iteration and return 0 from dl_iterate_phdr when finished.
1080 }
1081 const uint8_t* const begin_;
1082 std::vector<std::unique_ptr<MemMap>>* const dlopen_mmaps_;
Andreas Gampe4075f832016-05-18 13:09:54 -07001083 const size_t shared_objects_before;
1084 size_t shared_objects_seen;
1085 };
1086 dl_iterate_context context = { Begin(), &dlopen_mmaps_, shared_objects_before_, 0};
Andreas Gampe049cff02015-12-01 23:27:12 -08001087
1088 if (dl_iterate_phdr(dl_iterate_context::callback, &context) == 0) {
Andreas Gampe4075f832016-05-18 13:09:54 -07001089 // Hm. Maybe our optimization went wrong. Try another time with shared_objects_before == 0
1090 // before giving up. This should be unusual.
1091 VLOG(oat) << "Need a second run in PreSetup, didn't find with shared_objects_before="
1092 << shared_objects_before_;
1093 dl_iterate_context context0 = { Begin(), &dlopen_mmaps_, 0, 0};
1094 if (dl_iterate_phdr(dl_iterate_context::callback, &context0) == 0) {
1095 // OK, give up and print an error.
Andreas Gampe170331f2017-12-07 18:41:03 -08001096 PrintFileToLog("/proc/self/maps", android::base::LogSeverity::WARNING);
Andreas Gampe4075f832016-05-18 13:09:54 -07001097 LOG(ERROR) << "File " << elf_filename << " loaded with dlopen but cannot find its mmaps.";
1098 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001099 }
Andreas Gampe74f07b52015-12-02 11:53:26 -08001100#endif
Andreas Gampe049cff02015-12-01 23:27:12 -08001101}
1102
1103////////////////////////////////////////////////
1104// OatFile via our own ElfFile implementation //
1105////////////////////////////////////////////////
1106
1107class ElfOatFile FINAL : public OatFileBase {
1108 public:
1109 ElfOatFile(const std::string& filename, bool executable) : OatFileBase(filename, executable) {}
1110
1111 static ElfOatFile* OpenElfFile(File* file,
1112 const std::string& location,
1113 uint8_t* requested_base,
1114 uint8_t* oat_file_begin, // Override base if not null
1115 bool writable,
1116 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001117 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001118 const char* abs_dex_location,
1119 std::string* error_msg);
1120
1121 bool InitializeFromElfFile(ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +01001122 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001123 const char* abs_dex_location,
1124 std::string* error_msg);
1125
1126 protected:
1127 const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
1128 std::string* error_msg) const OVERRIDE {
1129 const uint8_t* ptr = elf_file_->FindDynamicSymbolAddress(symbol_name);
1130 if (ptr == nullptr) {
1131 *error_msg = "(Internal implementation could not find symbol)";
1132 }
1133 return ptr;
1134 }
1135
Andreas Gampe4075f832016-05-18 13:09:54 -07001136 void PreLoad() OVERRIDE {
1137 }
1138
Andreas Gampe049cff02015-12-01 23:27:12 -08001139 bool Load(const std::string& elf_filename,
1140 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1141 bool writable,
1142 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001143 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001144 std::string* error_msg) OVERRIDE;
1145
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001146 bool Load(int oat_fd,
1147 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1148 bool writable,
1149 bool executable,
1150 bool low_4gb,
1151 std::string* error_msg) OVERRIDE;
1152
Andreas Gampe049cff02015-12-01 23:27:12 -08001153 void PreSetup(const std::string& elf_filename ATTRIBUTE_UNUSED) OVERRIDE {
1154 }
1155
1156 private:
1157 bool ElfFileOpen(File* file,
1158 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1159 bool writable,
1160 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001161 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001162 std::string* error_msg);
1163
1164 private:
1165 // Backing memory map for oat file during cross compilation.
1166 std::unique_ptr<ElfFile> elf_file_;
1167
1168 DISALLOW_COPY_AND_ASSIGN(ElfOatFile);
1169};
1170
1171ElfOatFile* ElfOatFile::OpenElfFile(File* file,
1172 const std::string& location,
1173 uint8_t* requested_base,
1174 uint8_t* oat_file_begin, // Override base if not null
1175 bool writable,
1176 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001177 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001178 const char* abs_dex_location,
1179 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001180 ScopedTrace trace("Open elf file " + location);
Andreas Gampe049cff02015-12-01 23:27:12 -08001181 std::unique_ptr<ElfOatFile> oat_file(new ElfOatFile(location, executable));
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001182 bool success = oat_file->ElfFileOpen(file,
1183 oat_file_begin,
1184 writable,
1185 low_4gb,
1186 executable,
1187 error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -08001188 if (!success) {
1189 CHECK(!error_msg->empty());
1190 return nullptr;
1191 }
1192
1193 // Complete the setup.
1194 if (!oat_file->ComputeFields(requested_base, file->GetPath(), error_msg)) {
1195 return nullptr;
1196 }
1197
1198 if (!oat_file->Setup(abs_dex_location, error_msg)) {
1199 return nullptr;
1200 }
1201
1202 return oat_file.release();
1203}
1204
1205bool ElfOatFile::InitializeFromElfFile(ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +01001206 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001207 const char* abs_dex_location,
1208 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001209 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -08001210 if (IsExecutable()) {
1211 *error_msg = "Cannot initialize from elf file in executable mode.";
1212 return false;
1213 }
1214 elf_file_.reset(elf_file);
David Brazdilc93b3be2016-09-12 18:49:58 +01001215 SetVdex(vdex_file);
Andreas Gampe049cff02015-12-01 23:27:12 -08001216 uint64_t offset, size;
1217 bool has_section = elf_file->GetSectionOffsetAndSize(".rodata", &offset, &size);
1218 CHECK(has_section);
1219 SetBegin(elf_file->Begin() + offset);
1220 SetEnd(elf_file->Begin() + size + offset);
1221 // Ignore the optional .bss section when opening non-executable.
1222 return Setup(abs_dex_location, error_msg);
1223}
1224
1225bool ElfOatFile::Load(const std::string& elf_filename,
1226 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1227 bool writable,
1228 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001229 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001230 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001231 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -08001232 std::unique_ptr<File> file(OS::OpenFileForReading(elf_filename.c_str()));
1233 if (file == nullptr) {
1234 *error_msg = StringPrintf("Failed to open oat filename for reading: %s", strerror(errno));
1235 return false;
1236 }
1237 return ElfOatFile::ElfFileOpen(file.get(),
1238 oat_file_begin,
1239 writable,
1240 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001241 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001242 error_msg);
1243}
1244
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001245bool ElfOatFile::Load(int oat_fd,
1246 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1247 bool writable,
1248 bool executable,
1249 bool low_4gb,
1250 std::string* error_msg) {
1251 ScopedTrace trace(__PRETTY_FUNCTION__);
1252 if (oat_fd != -1) {
1253 std::unique_ptr<File> file = std::make_unique<File>(oat_fd, false);
1254 file->DisableAutoClose();
1255 if (file == nullptr) {
1256 *error_msg = StringPrintf("Failed to open oat filename for reading: %s",
1257 strerror(errno));
1258 return false;
1259 }
1260 return ElfOatFile::ElfFileOpen(file.get(),
1261 oat_file_begin,
1262 writable,
1263 executable,
1264 low_4gb,
1265 error_msg);
1266 }
1267 return false;
1268}
1269
Andreas Gampe049cff02015-12-01 23:27:12 -08001270bool ElfOatFile::ElfFileOpen(File* file,
1271 uint8_t* oat_file_begin,
1272 bool writable,
1273 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001274 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001275 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001276 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -08001277 // TODO: rename requested_base to oat_data_begin
1278 elf_file_.reset(ElfFile::Open(file,
1279 writable,
1280 /*program_header_only*/true,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001281 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001282 error_msg,
1283 oat_file_begin));
1284 if (elf_file_ == nullptr) {
1285 DCHECK(!error_msg->empty());
1286 return false;
1287 }
Brian Carlstromf5b0f2c2016-10-14 01:04:26 -07001288 bool loaded = elf_file_->Load(file, executable, low_4gb, error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -08001289 DCHECK(loaded || !error_msg->empty());
1290 return loaded;
1291}
1292
1293//////////////////////////
1294// General OatFile code //
1295//////////////////////////
1296
1297std::string OatFile::ResolveRelativeEncodedDexLocation(
1298 const char* abs_dex_location, const std::string& rel_dex_location) {
1299 if (abs_dex_location != nullptr && rel_dex_location[0] != '/') {
1300 // Strip :classes<N>.dex used for secondary multidex files.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001301 std::string base = DexFileLoader::GetBaseLocation(rel_dex_location);
1302 std::string multidex_suffix = DexFileLoader::GetMultiDexSuffix(rel_dex_location);
Andreas Gampe049cff02015-12-01 23:27:12 -08001303
1304 // Check if the base is a suffix of the provided abs_dex_location.
1305 std::string target_suffix = "/" + base;
1306 std::string abs_location(abs_dex_location);
1307 if (abs_location.size() > target_suffix.size()) {
1308 size_t pos = abs_location.size() - target_suffix.size();
1309 if (abs_location.compare(pos, std::string::npos, target_suffix) == 0) {
1310 return abs_location + multidex_suffix;
1311 }
1312 }
1313 }
1314 return rel_dex_location;
1315}
1316
1317static void CheckLocation(const std::string& location) {
1318 CHECK(!location.empty());
1319}
1320
1321OatFile* OatFile::OpenWithElfFile(ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +01001322 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001323 const std::string& location,
1324 const char* abs_dex_location,
1325 std::string* error_msg) {
1326 std::unique_ptr<ElfOatFile> oat_file(new ElfOatFile(location, false /* executable */));
David Brazdilc93b3be2016-09-12 18:49:58 +01001327 return oat_file->InitializeFromElfFile(elf_file, vdex_file, abs_dex_location, error_msg)
Andreas Gampe049cff02015-12-01 23:27:12 -08001328 ? oat_file.release()
1329 : nullptr;
1330}
1331
David Brazdil7b49e6c2016-09-01 11:06:18 +01001332OatFile* OatFile::Open(const std::string& oat_filename,
1333 const std::string& oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001334 uint8_t* requested_base,
1335 uint8_t* oat_file_begin,
1336 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001337 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001338 const char* abs_dex_location,
1339 std::string* error_msg) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001340 ScopedTrace trace("Open oat file " + oat_location);
1341 CHECK(!oat_filename.empty()) << oat_location;
1342 CheckLocation(oat_location);
Andreas Gampe54315c72016-05-18 21:10:42 -07001343
Calin Juravle367b9d82017-05-15 18:18:39 -07001344 std::string vdex_filename = GetVdexFilename(oat_filename);
David Brazdil7b49e6c2016-09-01 11:06:18 +01001345
1346 // Check that the files even exist, fast-fail.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001347 if (!OS::FileExists(vdex_filename.c_str())) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001348 *error_msg = StringPrintf("File %s does not exist.", vdex_filename.c_str());
1349 return nullptr;
1350 } else if (!OS::FileExists(oat_filename.c_str())) {
1351 *error_msg = StringPrintf("File %s does not exist.", oat_filename.c_str());
Andreas Gampe54315c72016-05-18 21:10:42 -07001352 return nullptr;
1353 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001354
1355 // Try dlopen first, as it is required for native debuggability. This will fail fast if dlopen is
1356 // disabled.
David Brazdil7b49e6c2016-09-01 11:06:18 +01001357 OatFile* with_dlopen = OatFileBase::OpenOatFile<DlOpenOatFile>(vdex_filename,
1358 oat_filename,
1359 oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001360 requested_base,
1361 oat_file_begin,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001362 false /* writable */,
Andreas Gampe049cff02015-12-01 23:27:12 -08001363 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001364 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001365 abs_dex_location,
1366 error_msg);
1367 if (with_dlopen != nullptr) {
1368 return with_dlopen;
1369 }
1370 if (kPrintDlOpenErrorMessage) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001371 LOG(ERROR) << "Failed to dlopen: " << oat_filename << " with error " << *error_msg;
Andreas Gampe049cff02015-12-01 23:27:12 -08001372 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001373 // If we aren't trying to execute, we just use our own ElfFile loader for a couple reasons:
1374 //
1375 // On target, dlopen may fail when compiling due to selinux restrictions on installd.
1376 //
1377 // We use our own ELF loader for Quick to deal with legacy apps that
1378 // open a generated dex file by name, remove the file, then open
1379 // another generated dex file with the same name. http://b/10614658
1380 //
1381 // On host, dlopen is expected to fail when cross compiling, so fall back to OpenElfFile.
1382 //
1383 //
1384 // Another independent reason is the absolute placement of boot.oat. dlopen on the host usually
1385 // does honor the virtual address encoded in the ELF file only for ET_EXEC files, not ET_DYN.
David Brazdil7b49e6c2016-09-01 11:06:18 +01001386 OatFile* with_internal = OatFileBase::OpenOatFile<ElfOatFile>(vdex_filename,
1387 oat_filename,
1388 oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001389 requested_base,
1390 oat_file_begin,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001391 false /* writable */,
Andreas Gampe049cff02015-12-01 23:27:12 -08001392 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001393 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001394 abs_dex_location,
1395 error_msg);
1396 return with_internal;
1397}
1398
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001399OatFile* OatFile::Open(int vdex_fd,
1400 int oat_fd,
1401 const std::string& oat_location,
1402 uint8_t* requested_base,
1403 uint8_t* oat_file_begin,
1404 bool executable,
1405 bool low_4gb,
1406 const char* abs_dex_location,
1407 std::string* error_msg) {
1408 CHECK(!oat_location.empty()) << oat_location;
1409
1410 std::string vdex_location = GetVdexFilename(oat_location);
1411
1412 OatFile* with_internal = OatFileBase::OpenOatFile<ElfOatFile>(vdex_fd,
1413 oat_fd,
1414 vdex_location,
1415 oat_location,
1416 requested_base,
1417 oat_file_begin,
1418 false /* writable */,
1419 executable,
1420 low_4gb,
1421 abs_dex_location,
1422 error_msg);
1423 return with_internal;
1424}
1425
Andreas Gampe049cff02015-12-01 23:27:12 -08001426OatFile* OatFile::OpenWritable(File* file,
1427 const std::string& location,
1428 const char* abs_dex_location,
1429 std::string* error_msg) {
1430 CheckLocation(location);
1431 return ElfOatFile::OpenElfFile(file,
1432 location,
1433 nullptr,
1434 nullptr,
1435 true,
1436 false,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001437 /*low_4gb*/false,
Andreas Gampe049cff02015-12-01 23:27:12 -08001438 abs_dex_location,
1439 error_msg);
1440}
1441
1442OatFile* OatFile::OpenReadable(File* file,
1443 const std::string& location,
1444 const char* abs_dex_location,
1445 std::string* error_msg) {
1446 CheckLocation(location);
1447 return ElfOatFile::OpenElfFile(file,
1448 location,
1449 nullptr,
1450 nullptr,
1451 false,
1452 false,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001453 /*low_4gb*/false,
Andreas Gampe049cff02015-12-01 23:27:12 -08001454 abs_dex_location,
1455 error_msg);
1456}
1457
1458OatFile::OatFile(const std::string& location, bool is_executable)
1459 : location_(location),
David Brazdil7b49e6c2016-09-01 11:06:18 +01001460 vdex_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001461 begin_(nullptr),
1462 end_(nullptr),
1463 bss_begin_(nullptr),
1464 bss_end_(nullptr),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001465 bss_methods_(nullptr),
Vladimir Markoaad75c62016-10-03 08:46:48 +00001466 bss_roots_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001467 is_executable_(is_executable),
David Srbeckyec2cdf42017-12-08 16:21:25 +00001468 vdex_begin_(nullptr),
1469 vdex_end_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001470 secondary_lookup_lock_("OatFile secondary lookup lock", kOatFileSecondaryLookupLock) {
1471 CHECK(!location_.empty());
1472}
1473
1474OatFile::~OatFile() {
1475 STLDeleteElements(&oat_dex_files_storage_);
1476}
1477
Brian Carlstrome24fa612011-09-29 00:53:55 -07001478const OatHeader& OatFile::GetOatHeader() const {
Ian Rogers30fab402012-01-23 15:43:46 -08001479 return *reinterpret_cast<const OatHeader*>(Begin());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001480}
1481
Ian Rogers13735952014-10-08 12:43:28 -07001482const uint8_t* OatFile::Begin() const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001483 CHECK(begin_ != nullptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001484 return begin_;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001485}
1486
Ian Rogers13735952014-10-08 12:43:28 -07001487const uint8_t* OatFile::End() const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001488 CHECK(end_ != nullptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001489 return end_;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001490}
1491
Vladimir Marko5c42c292015-02-25 12:02:49 +00001492const uint8_t* OatFile::BssBegin() const {
1493 return bss_begin_;
1494}
1495
1496const uint8_t* OatFile::BssEnd() const {
1497 return bss_end_;
1498}
1499
David Srbeckyec2cdf42017-12-08 16:21:25 +00001500const uint8_t* OatFile::VdexBegin() const {
1501 return vdex_begin_;
1502}
1503
1504const uint8_t* OatFile::VdexEnd() const {
1505 return vdex_end_;
1506}
1507
David Brazdil7b49e6c2016-09-01 11:06:18 +01001508const uint8_t* OatFile::DexBegin() const {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001509 return vdex_->Begin();
David Brazdil7b49e6c2016-09-01 11:06:18 +01001510}
1511
1512const uint8_t* OatFile::DexEnd() const {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001513 return vdex_->End();
David Brazdil7b49e6c2016-09-01 11:06:18 +01001514}
1515
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001516ArrayRef<ArtMethod*> OatFile::GetBssMethods() const {
1517 if (bss_methods_ != nullptr) {
1518 ArtMethod** methods = reinterpret_cast<ArtMethod**>(bss_methods_);
1519 ArtMethod** methods_end =
1520 reinterpret_cast<ArtMethod**>(bss_roots_ != nullptr ? bss_roots_ : bss_end_);
1521 return ArrayRef<ArtMethod*>(methods, methods_end - methods);
1522 } else {
1523 return ArrayRef<ArtMethod*>();
1524 }
1525}
1526
Vladimir Markoaad75c62016-10-03 08:46:48 +00001527ArrayRef<GcRoot<mirror::Object>> OatFile::GetBssGcRoots() const {
1528 if (bss_roots_ != nullptr) {
1529 auto* roots = reinterpret_cast<GcRoot<mirror::Object>*>(bss_roots_);
1530 auto* roots_end = reinterpret_cast<GcRoot<mirror::Object>*>(bss_end_);
1531 return ArrayRef<GcRoot<mirror::Object>>(roots, roots_end - roots);
1532 } else {
1533 return ArrayRef<GcRoot<mirror::Object>>();
1534 }
1535}
1536
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001537uint32_t OatFile::GetDebugInfoOffset(const DexFile& dex_file, uint32_t debug_info_off) {
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00001538 // Note that although the specification says that 0 should be used if there
1539 // is no debug information, some applications incorrectly use 0xFFFFFFFF.
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001540 // The following check also handles debug_info_off == 0.
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00001541 if (debug_info_off < dex_file.Size() || debug_info_off == 0xFFFFFFFF) {
1542 return debug_info_off;
1543 }
1544 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1545 if (oat_dex_file == nullptr || (oat_dex_file->GetOatFile() == nullptr)) {
1546 return debug_info_off;
1547 }
1548 return oat_dex_file->GetOatFile()->GetVdexFile()->GetDebugInfoOffset(
1549 dex_file, debug_info_off);
Nicolas Geoffray58cc1cb2017-11-20 13:27:29 +00001550}
1551
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001552const OatFile::OatDexFile* OatFile::GetOatDexFile(const char* dex_location,
1553 const uint32_t* dex_location_checksum,
Richard Uhler9a37efc2016-08-05 16:32:55 -07001554 std::string* error_msg) const {
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001555 // NOTE: We assume here that the canonical location for a given dex_location never
1556 // changes. If it does (i.e. some symlink used by the filename changes) we may return
1557 // an incorrect OatDexFile. As long as we have a checksum to check, we shall return
1558 // an identical file or fail; otherwise we may see some unpredictable failures.
Calin Juravle4e1d5792014-07-15 23:56:47 +01001559
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001560 // TODO: Additional analysis of usage patterns to see if this can be simplified
1561 // without any performance loss, for example by not doing the first lock-free lookup.
1562
1563 const OatFile::OatDexFile* oat_dex_file = nullptr;
1564 StringPiece key(dex_location);
1565 // Try to find the key cheaply in the oat_dex_files_ map which holds dex locations
1566 // directly mentioned in the oat file and doesn't require locking.
1567 auto primary_it = oat_dex_files_.find(key);
1568 if (primary_it != oat_dex_files_.end()) {
1569 oat_dex_file = primary_it->second;
1570 DCHECK(oat_dex_file != nullptr);
1571 } else {
1572 // This dex_location is not one of the dex locations directly mentioned in the
1573 // oat file. The correct lookup is via the canonical location but first see in
1574 // the secondary_oat_dex_files_ whether we've looked up this location before.
1575 MutexLock mu(Thread::Current(), secondary_lookup_lock_);
1576 auto secondary_lb = secondary_oat_dex_files_.lower_bound(key);
1577 if (secondary_lb != secondary_oat_dex_files_.end() && key == secondary_lb->first) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001578 oat_dex_file = secondary_lb->second; // May be null.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001579 } else {
1580 // We haven't seen this dex_location before, we must check the canonical location.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001581 std::string dex_canonical_location = DexFileLoader::GetDexCanonicalLocation(dex_location);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001582 if (dex_canonical_location != dex_location) {
1583 StringPiece canonical_key(dex_canonical_location);
1584 auto canonical_it = oat_dex_files_.find(canonical_key);
1585 if (canonical_it != oat_dex_files_.end()) {
1586 oat_dex_file = canonical_it->second;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001587 } // else keep null.
1588 } // else keep null.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001589
1590 // Copy the key to the string_cache_ and store the result in secondary map.
1591 string_cache_.emplace_back(key.data(), key.length());
1592 StringPiece key_copy(string_cache_.back());
1593 secondary_oat_dex_files_.PutBefore(secondary_lb, key_copy, oat_dex_file);
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001594 }
1595 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001596
1597 if (oat_dex_file == nullptr) {
1598 if (error_msg != nullptr) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001599 std::string dex_canonical_location = DexFileLoader::GetDexCanonicalLocation(dex_location);
Richard Uhler9a37efc2016-08-05 16:32:55 -07001600 *error_msg = "Failed to find OatDexFile for DexFile " + std::string(dex_location)
1601 + " (canonical path " + dex_canonical_location + ") in OatFile " + GetLocation();
1602 }
1603 return nullptr;
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001604 }
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001605
Richard Uhler9a37efc2016-08-05 16:32:55 -07001606 if (dex_location_checksum != nullptr &&
1607 oat_dex_file->GetDexFileLocationChecksum() != *dex_location_checksum) {
1608 if (error_msg != nullptr) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001609 std::string dex_canonical_location = DexFileLoader::GetDexCanonicalLocation(dex_location);
Richard Uhler9a37efc2016-08-05 16:32:55 -07001610 std::string checksum = StringPrintf("0x%08x", oat_dex_file->GetDexFileLocationChecksum());
1611 std::string required_checksum = StringPrintf("0x%08x", *dex_location_checksum);
1612 *error_msg = "OatDexFile for DexFile " + std::string(dex_location)
1613 + " (canonical path " + dex_canonical_location + ") in OatFile " + GetLocation()
1614 + " has checksum " + checksum + " but " + required_checksum + " was required";
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001615 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001616 return nullptr;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001617 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001618 return oat_dex_file;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001619}
1620
Brian Carlstrome24fa612011-09-29 00:53:55 -07001621OatFile::OatDexFile::OatDexFile(const OatFile* oat_file,
Elliott Hughesaa6a5882012-01-13 19:39:16 -08001622 const std::string& dex_file_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001623 const std::string& canonical_dex_file_location,
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001624 uint32_t dex_file_location_checksum,
Ian Rogers13735952014-10-08 12:43:28 -07001625 const uint8_t* dex_file_pointer,
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001626 const uint8_t* lookup_table_data,
Vladimir Markof3c52b42017-11-17 17:32:12 +00001627 const IndexBssMapping* method_bss_mapping_data,
1628 const IndexBssMapping* type_bss_mapping_data,
1629 const IndexBssMapping* string_bss_mapping_data,
Vladimir Marko09d09432015-09-08 13:47:48 +01001630 const uint32_t* oat_class_offsets_pointer,
Mathieu Chartier120aa282017-08-05 16:03:03 -07001631 const DexLayoutSections* dex_layout_sections)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001632 : oat_file_(oat_file),
1633 dex_file_location_(dex_file_location),
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001634 canonical_dex_file_location_(canonical_dex_file_location),
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001635 dex_file_location_checksum_(dex_file_location_checksum),
Brian Carlstrom89521892011-12-07 22:05:07 -08001636 dex_file_pointer_(dex_file_pointer),
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001637 lookup_table_data_(lookup_table_data),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001638 method_bss_mapping_(method_bss_mapping_data),
Vladimir Markof3c52b42017-11-17 17:32:12 +00001639 type_bss_mapping_(type_bss_mapping_data),
1640 string_bss_mapping_(string_bss_mapping_data),
Vladimir Marko09d09432015-09-08 13:47:48 +01001641 oat_class_offsets_pointer_(oat_class_offsets_pointer),
Mathieu Chartier120aa282017-08-05 16:03:03 -07001642 dex_layout_sections_(dex_layout_sections) {
David Sehr9aa352e2016-09-15 18:13:52 -07001643 // Initialize TypeLookupTable.
1644 if (lookup_table_data_ != nullptr) {
1645 // Peek the number of classes from the DexFile.
1646 const DexFile::Header* dex_header = reinterpret_cast<const DexFile::Header*>(dex_file_pointer_);
1647 const uint32_t num_class_defs = dex_header->class_defs_size_;
1648 if (lookup_table_data_ + TypeLookupTable::RawDataLength(num_class_defs) > GetOatFile()->End()) {
1649 LOG(WARNING) << "found truncated lookup table in " << dex_file_location_;
1650 } else {
Mathieu Chartier1b868492016-11-16 16:22:37 -08001651 lookup_table_ = TypeLookupTable::Open(dex_file_pointer_, lookup_table_data_, num_class_defs);
David Sehr9aa352e2016-09-15 18:13:52 -07001652 }
1653 }
1654}
Brian Carlstrome24fa612011-09-29 00:53:55 -07001655
Mathieu Chartier1b868492016-11-16 16:22:37 -08001656OatFile::OatDexFile::OatDexFile(std::unique_ptr<TypeLookupTable>&& lookup_table)
1657 : lookup_table_(std::move(lookup_table)) {}
1658
Brian Carlstrome24fa612011-09-29 00:53:55 -07001659OatFile::OatDexFile::~OatDexFile() {}
1660
Ian Rogers05f28c62012-10-23 18:12:13 -07001661size_t OatFile::OatDexFile::FileSize() const {
1662 return reinterpret_cast<const DexFile::Header*>(dex_file_pointer_)->file_size_;
1663}
1664
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001665std::unique_ptr<const DexFile> OatFile::OatDexFile::OpenDexFile(std::string* error_msg) const {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001666 ScopedTrace trace(__PRETTY_FUNCTION__);
Aart Bik37d6a3b2016-06-21 18:30:10 -07001667 static constexpr bool kVerify = false;
1668 static constexpr bool kVerifyChecksum = false;
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001669 return DexFileLoader::Open(dex_file_pointer_,
1670 FileSize(),
1671 dex_file_location_,
1672 dex_file_location_checksum_,
1673 this,
1674 kVerify,
1675 kVerifyChecksum,
1676 error_msg);
Brian Carlstrom89521892011-12-07 22:05:07 -08001677}
1678
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001679uint32_t OatFile::OatDexFile::GetOatClassOffset(uint16_t class_def_index) const {
1680 return oat_class_offsets_pointer_[class_def_index];
1681}
1682
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001683OatFile::OatClass OatFile::OatDexFile::GetOatClass(uint16_t class_def_index) const {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001684 uint32_t oat_class_offset = GetOatClassOffset(class_def_index);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001685
Ian Rogers13735952014-10-08 12:43:28 -07001686 const uint8_t* oat_class_pointer = oat_file_->Begin() + oat_class_offset;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001687 CHECK_LT(oat_class_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001688
Ian Rogers13735952014-10-08 12:43:28 -07001689 const uint8_t* status_pointer = oat_class_pointer;
Brian Carlstromba150c32013-08-27 17:31:03 -07001690 CHECK_LT(status_pointer, oat_file_->End()) << oat_file_->GetLocation();
Vladimir Marko2c64a832018-01-04 11:31:56 +00001691 ClassStatus status = enum_cast<ClassStatus>(*reinterpret_cast<const int16_t*>(status_pointer));
1692 CHECK_LE(status, ClassStatus::kLast);
Brian Carlstromba150c32013-08-27 17:31:03 -07001693
Ian Rogers13735952014-10-08 12:43:28 -07001694 const uint8_t* type_pointer = status_pointer + sizeof(uint16_t);
Brian Carlstromba150c32013-08-27 17:31:03 -07001695 CHECK_LT(type_pointer, oat_file_->End()) << oat_file_->GetLocation();
1696 OatClassType type = static_cast<OatClassType>(*reinterpret_cast<const uint16_t*>(type_pointer));
1697 CHECK_LT(type, kOatClassMax);
1698
Ian Rogers13735952014-10-08 12:43:28 -07001699 const uint8_t* after_type_pointer = type_pointer + sizeof(int16_t);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001700 CHECK_LE(after_type_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07001701
Brian Carlstromcd937a92014-03-04 22:53:23 -08001702 uint32_t bitmap_size = 0;
Ian Rogers13735952014-10-08 12:43:28 -07001703 const uint8_t* bitmap_pointer = nullptr;
1704 const uint8_t* methods_pointer = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07001705 if (type != kOatClassNoneCompiled) {
1706 if (type == kOatClassSomeCompiled) {
1707 bitmap_size = static_cast<uint32_t>(*reinterpret_cast<const uint32_t*>(after_type_pointer));
1708 bitmap_pointer = after_type_pointer + sizeof(bitmap_size);
1709 CHECK_LE(bitmap_pointer, oat_file_->End()) << oat_file_->GetLocation();
1710 methods_pointer = bitmap_pointer + bitmap_size;
1711 } else {
1712 methods_pointer = after_type_pointer;
1713 }
1714 CHECK_LE(methods_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstromcd937a92014-03-04 22:53:23 -08001715 }
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001716
Richard Uhler07b3c232015-03-31 15:57:54 -07001717 return OatFile::OatClass(oat_file_,
1718 status,
1719 type,
1720 bitmap_size,
1721 reinterpret_cast<const uint32_t*>(bitmap_pointer),
1722 reinterpret_cast<const OatMethodOffsets*>(methods_pointer));
Brian Carlstrome24fa612011-09-29 00:53:55 -07001723}
1724
David Sehr9aa352e2016-09-15 18:13:52 -07001725const DexFile::ClassDef* OatFile::OatDexFile::FindClassDef(const DexFile& dex_file,
1726 const char* descriptor,
1727 size_t hash) {
1728 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1729 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
1730 if (LIKELY((oat_dex_file != nullptr) && (oat_dex_file->GetTypeLookupTable() != nullptr))) {
1731 const uint32_t class_def_idx = oat_dex_file->GetTypeLookupTable()->Lookup(descriptor, hash);
Andreas Gampee2abbc62017-09-15 11:59:26 -07001732 return (class_def_idx != dex::kDexNoIndex) ? &dex_file.GetClassDef(class_def_idx) : nullptr;
David Sehr9aa352e2016-09-15 18:13:52 -07001733 }
1734 // Fast path for rare no class defs case.
1735 const uint32_t num_class_defs = dex_file.NumClassDefs();
1736 if (num_class_defs == 0) {
1737 return nullptr;
1738 }
1739 const DexFile::TypeId* type_id = dex_file.FindTypeId(descriptor);
1740 if (type_id != nullptr) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001741 dex::TypeIndex type_idx = dex_file.GetIndexForTypeId(*type_id);
David Sehr9aa352e2016-09-15 18:13:52 -07001742 return dex_file.FindClassDef(type_idx);
1743 }
1744 return nullptr;
1745}
1746
Mathieu Chartier120aa282017-08-05 16:03:03 -07001747// Madvise the dex file based on the state we are moving to.
1748void OatDexFile::MadviseDexFile(const DexFile& dex_file, MadviseState state) {
Mathieu Chartierc42cb0e2017-10-13 11:35:00 -07001749 Runtime* const runtime = Runtime::Current();
1750 const bool low_ram = runtime->GetHeap()->IsLowMemoryMode();
Mathieu Chartier150d25d2017-08-28 09:52:55 -07001751 // TODO: Also do madvise hints for non low ram devices.
Mathieu Chartierc42cb0e2017-10-13 11:35:00 -07001752 if (!low_ram) {
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001753 return;
1754 }
Mathieu Chartierc42cb0e2017-10-13 11:35:00 -07001755 if (state == MadviseState::kMadviseStateAtLoad && runtime->MAdviseRandomAccess()) {
1756 // Default every dex file to MADV_RANDOM when its loaded by default for low ram devices.
1757 // Other devices have enough page cache to get performance benefits from loading more pages
1758 // into the page cache.
1759 MadviseLargestPageAlignedRegion(dex_file.Begin(),
1760 dex_file.Begin() + dex_file.Size(),
1761 MADV_RANDOM);
Mathieu Chartier120aa282017-08-05 16:03:03 -07001762 }
1763 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1764 if (oat_dex_file != nullptr) {
1765 // Should always be there.
1766 const DexLayoutSections* const sections = oat_dex_file->GetDexLayoutSections();
1767 CHECK(sections != nullptr);
1768 sections->Madvise(&dex_file, state);
1769 }
1770}
1771
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001772OatFile::OatClass::OatClass(const OatFile* oat_file,
Vladimir Marko2c64a832018-01-04 11:31:56 +00001773 ClassStatus status,
Brian Carlstromba150c32013-08-27 17:31:03 -07001774 OatClassType type,
1775 uint32_t bitmap_size,
1776 const uint32_t* bitmap_pointer,
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001777 const OatMethodOffsets* methods_pointer)
Brian Carlstromba150c32013-08-27 17:31:03 -07001778 : oat_file_(oat_file), status_(status), type_(type),
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001779 bitmap_(bitmap_pointer), methods_pointer_(methods_pointer) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001780 switch (type_) {
1781 case kOatClassAllCompiled: {
1782 CHECK_EQ(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001783 CHECK(bitmap_pointer == nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001784 CHECK(methods_pointer != nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001785 break;
1786 }
1787 case kOatClassSomeCompiled: {
1788 CHECK_NE(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001789 CHECK(bitmap_pointer != nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001790 CHECK(methods_pointer != nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001791 break;
1792 }
1793 case kOatClassNoneCompiled: {
1794 CHECK_EQ(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001795 CHECK(bitmap_pointer == nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001796 CHECK(methods_pointer_ == nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001797 break;
1798 }
1799 case kOatClassMax: {
1800 LOG(FATAL) << "Invalid OatClassType " << type_;
1801 break;
1802 }
1803 }
1804}
Brian Carlstrome24fa612011-09-29 00:53:55 -07001805
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001806uint32_t OatFile::OatClass::GetOatMethodOffsetsOffset(uint32_t method_index) const {
1807 const OatMethodOffsets* oat_method_offsets = GetOatMethodOffsets(method_index);
1808 if (oat_method_offsets == nullptr) {
1809 return 0u;
1810 }
1811 return reinterpret_cast<const uint8_t*>(oat_method_offsets) - oat_file_->Begin();
1812}
1813
1814const OatMethodOffsets* OatFile::OatClass::GetOatMethodOffsets(uint32_t method_index) const {
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001815 // 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 -07001816 if (methods_pointer_ == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001817 CHECK_EQ(kOatClassNoneCompiled, type_);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001818 return nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07001819 }
1820 size_t methods_pointer_index;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001821 if (bitmap_ == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001822 CHECK_EQ(kOatClassAllCompiled, type_);
1823 methods_pointer_index = method_index;
1824 } else {
1825 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001826 if (!BitVector::IsBitSet(bitmap_, method_index)) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001827 return nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07001828 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001829 size_t num_set_bits = BitVector::NumSetBits(bitmap_, method_index);
1830 methods_pointer_index = num_set_bits;
Brian Carlstromba150c32013-08-27 17:31:03 -07001831 }
1832 const OatMethodOffsets& oat_method_offsets = methods_pointer_[methods_pointer_index];
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001833 return &oat_method_offsets;
1834}
1835
1836const OatFile::OatMethod OatFile::OatClass::GetOatMethod(uint32_t method_index) const {
1837 const OatMethodOffsets* oat_method_offsets = GetOatMethodOffsets(method_index);
1838 if (oat_method_offsets == nullptr) {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001839 return OatMethod(nullptr, 0);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001840 }
1841 if (oat_file_->IsExecutable() ||
1842 Runtime::Current() == nullptr || // This case applies for oatdump.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001843 Runtime::Current()->IsAotCompiler()) {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001844 return OatMethod(oat_file_->Begin(), oat_method_offsets->code_offset_);
Alex Light9dcc4572014-08-14 14:16:26 -07001845 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001846 // We aren't allowed to use the compiled code. We just force it down the interpreted / jit
1847 // version.
1848 return OatMethod(oat_file_->Begin(), 0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001849}
1850
Mathieu Chartiere401d142015-04-22 13:56:20 -07001851void OatFile::OatMethod::LinkMethod(ArtMethod* method) const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001852 CHECK(method != nullptr);
Ian Rogersef7d42f2014-01-06 12:55:46 -08001853 method->SetEntryPointFromQuickCompiledCode(GetQuickCode());
Brian Carlstromae826982011-11-09 01:33:42 -08001854}
1855
Andreas Gampe7ba64962014-10-23 11:37:40 -07001856bool OatFile::IsPic() const {
Igor Murashkin46774762014-10-22 11:37:02 -07001857 return GetOatHeader().IsPic();
Andreas Gampe7ba64962014-10-23 11:37:40 -07001858 // TODO: Check against oat_patches. b/18144996
1859}
1860
Sebastien Hertz0de11332015-05-13 12:14:05 +02001861bool OatFile::IsDebuggable() const {
1862 return GetOatHeader().IsDebuggable();
1863}
1864
Andreas Gampe29d38e72016-03-23 15:31:51 +00001865CompilerFilter::Filter OatFile::GetCompilerFilter() const {
1866 return GetOatHeader().GetCompilerFilter();
Calin Juravleb077e152016-02-18 18:47:37 +00001867}
1868
Calin Juravle44e5efa2017-09-12 00:54:26 -07001869std::string OatFile::GetClassLoaderContext() const {
1870 return GetOatHeader().GetStoreValueByKey(OatHeader::kClassPathKey);
Igor Murashkin2ffb7032017-11-08 13:35:21 -08001871}
Calin Juravle44e5efa2017-09-12 00:54:26 -07001872
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001873OatFile::OatClass OatFile::FindOatClass(const DexFile& dex_file,
1874 uint16_t class_def_idx,
1875 bool* found) {
1876 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
1877 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Mathieu Chartier1b868492016-11-16 16:22:37 -08001878 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001879 *found = false;
1880 return OatFile::OatClass::Invalid();
1881 }
1882 *found = true;
1883 return oat_dex_file->GetOatClass(class_def_idx);
1884}
1885
Mathieu Chartier1b868492016-11-16 16:22:37 -08001886void OatFile::OatDexFile::AssertAotCompiler() {
1887 CHECK(Runtime::Current()->IsAotCompiler());
1888}
1889
Brian Carlstrome24fa612011-09-29 00:53:55 -07001890} // namespace art