blob: 734e700c81ab973a86f6fe6e0d8123b0f5d04354 [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"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080041#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080042#include "base/systrace.h"
Elliott Hughes76160052012-12-12 16:31:20 -080043#include "base/unix_file/fd_file.h"
Andreas Gampea5b09a62016-11-17 15:21:22 -080044#include "dex_file_types.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080045#include "elf_file.h"
Alex Light84d76052014-08-22 17:49:35 -070046#include "elf_utils.h"
Vladimir Markoaad75c62016-10-03 08:46:48 +000047#include "gc_root.h"
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +010048#include "gc/space/image_space.h"
David Srbecky1baabf02015-06-16 17:12:34 +000049#include "mem_map.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080050#include "mirror/class.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070051#include "mirror/object-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070052#include "oat.h"
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +010053#include "oat_file-inl.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070054#include "oat_file_manager.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070055#include "os.h"
Andreas Gampe22f8e5c2014-07-09 11:38:21 -070056#include "runtime.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000057#include "type_lookup_table.h"
David Sehr9aa352e2016-09-15 18:13:52 -070058#include "utf-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080059#include "utils.h"
Vladimir Marko97d7e1c2016-10-04 14:44:28 +010060#include "vdex_file.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070061
62namespace art {
63
Andreas Gampe46ee31b2016-12-14 10:11:49 -080064using android::base::StringPrintf;
65
Andreas Gampe049cff02015-12-01 23:27:12 -080066// Whether OatFile::Open will try dlopen. Fallback is our own ELF loader.
David Srbecky1baabf02015-06-16 17:12:34 +000067static constexpr bool kUseDlopen = true;
Andreas Gampefa8429b2015-04-07 18:34:42 -070068
Andreas Gampe049cff02015-12-01 23:27:12 -080069// Whether OatFile::Open will try dlopen on the host. On the host we're not linking against
Andreas Gampefa8429b2015-04-07 18:34:42 -070070// bionic, so cannot take advantage of the support for changed semantics (loading the same soname
71// multiple times). However, if/when we switch the above, we likely want to switch this, too,
72// to get test coverage of the code paths.
David Srbecky1baabf02015-06-16 17:12:34 +000073static constexpr bool kUseDlopenOnHost = true;
Andreas Gampefa8429b2015-04-07 18:34:42 -070074
75// For debugging, Open will print DlOpen error message if set to true.
76static constexpr bool kPrintDlOpenErrorMessage = false;
77
Mathieu Chartierbe8303d2017-08-17 17:39:39 -070078// If true, we advise the kernel about dex file mem map accesses.
Mathieu Chartier150d25d2017-08-28 09:52:55 -070079static constexpr bool kMadviseDexFileAccesses = true;
Mathieu Chartierbe8303d2017-08-17 17:39:39 -070080
Andreas Gampe049cff02015-12-01 23:27:12 -080081// Note for OatFileBase and descendents:
82//
83// These are used in OatFile::Open to try all our loaders.
84//
85// The process is simple:
86//
87// 1) Allocate an instance through the standard constructor (location, executable)
88// 2) Load() to try to open the file.
89// 3) ComputeFields() to populate the OatFile fields like begin_, using FindDynamicSymbolAddress.
90// 4) PreSetup() for any steps that should be done before the final setup.
91// 5) Setup() to complete the procedure.
Richard Uhlere5fed032015-03-18 08:21:11 -070092
Andreas Gampe049cff02015-12-01 23:27:12 -080093class OatFileBase : public OatFile {
94 public:
95 virtual ~OatFileBase() {}
Richard Uhlere5fed032015-03-18 08:21:11 -070096
Andreas Gampe049cff02015-12-01 23:27:12 -080097 template <typename kOatFileBaseSubType>
David Brazdil7b49e6c2016-09-01 11:06:18 +010098 static OatFileBase* OpenOatFile(const std::string& vdex_filename,
99 const std::string& elf_filename,
Alex Light84d76052014-08-22 17:49:35 -0700100 const std::string& location,
Andreas Gampe049cff02015-12-01 23:27:12 -0800101 uint8_t* requested_base,
102 uint8_t* oat_file_begin,
103 bool writable,
104 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800105 bool low_4gb,
Richard Uhlere5fed032015-03-18 08:21:11 -0700106 const char* abs_dex_location,
Andreas Gampe049cff02015-12-01 23:27:12 -0800107 std::string* error_msg);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800108
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700109 template <typename kOatFileBaseSubType>
110 static OatFileBase* OpenOatFile(int vdex_fd,
111 int oat_fd,
112 const std::string& vdex_filename,
113 const std::string& oat_filename,
114 uint8_t* requested_base,
115 uint8_t* oat_file_begin,
116 bool writable,
117 bool executable,
118 bool low_4gb,
119 const char* abs_dex_location,
120 std::string* error_msg);
121
Andreas Gampe049cff02015-12-01 23:27:12 -0800122 protected:
123 OatFileBase(const std::string& filename, bool executable) : OatFile(filename, executable) {}
Andreas Gampefa8429b2015-04-07 18:34:42 -0700124
Andreas Gampe049cff02015-12-01 23:27:12 -0800125 virtual const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
126 std::string* error_msg) const = 0;
127
Andreas Gampe4075f832016-05-18 13:09:54 -0700128 virtual void PreLoad() = 0;
129
David Brazdil7b49e6c2016-09-01 11:06:18 +0100130 bool LoadVdex(const std::string& vdex_filename,
131 bool writable,
132 bool low_4gb,
133 std::string* error_msg);
134
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700135 bool LoadVdex(int vdex_fd,
136 const std::string& vdex_filename,
137 bool writable,
138 bool low_4gb,
139 std::string* error_msg);
140
Andreas Gampe049cff02015-12-01 23:27:12 -0800141 virtual bool Load(const std::string& elf_filename,
142 uint8_t* oat_file_begin,
143 bool writable,
144 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800145 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800146 std::string* error_msg) = 0;
147
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700148 virtual bool Load(int oat_fd,
149 uint8_t* oat_file_begin,
150 bool writable,
151 bool executable,
152 bool low_4gb,
153 std::string* error_msg) = 0;
154
Andreas Gampe049cff02015-12-01 23:27:12 -0800155 bool ComputeFields(uint8_t* requested_base,
156 const std::string& file_path,
157 std::string* error_msg);
158
159 virtual void PreSetup(const std::string& elf_filename) = 0;
160
161 bool Setup(const char* abs_dex_location, std::string* error_msg);
162
163 // Setters exposed for ElfOatFile.
164
165 void SetBegin(const uint8_t* begin) {
166 begin_ = begin;
Andreas Gampefa8429b2015-04-07 18:34:42 -0700167 }
168
Andreas Gampe049cff02015-12-01 23:27:12 -0800169 void SetEnd(const uint8_t* end) {
170 end_ = end;
171 }
172
David Brazdilc93b3be2016-09-12 18:49:58 +0100173 void SetVdex(VdexFile* vdex) {
174 vdex_.reset(vdex);
175 }
176
Andreas Gampe049cff02015-12-01 23:27:12 -0800177 private:
178 DISALLOW_COPY_AND_ASSIGN(OatFileBase);
179};
180
181template <typename kOatFileBaseSubType>
David Brazdil7b49e6c2016-09-01 11:06:18 +0100182OatFileBase* OatFileBase::OpenOatFile(const std::string& vdex_filename,
183 const std::string& elf_filename,
Andreas Gampe049cff02015-12-01 23:27:12 -0800184 const std::string& location,
185 uint8_t* requested_base,
186 uint8_t* oat_file_begin,
187 bool writable,
188 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800189 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800190 const char* abs_dex_location,
191 std::string* error_msg) {
192 std::unique_ptr<OatFileBase> ret(new kOatFileBaseSubType(location, executable));
Andreas Gampe4075f832016-05-18 13:09:54 -0700193
194 ret->PreLoad();
195
David Brazdil7b49e6c2016-09-01 11:06:18 +0100196 if (kIsVdexEnabled && !ret->LoadVdex(vdex_filename, writable, low_4gb, error_msg)) {
197 return nullptr;
198 }
199
Andreas Gampe049cff02015-12-01 23:27:12 -0800200 if (!ret->Load(elf_filename,
201 oat_file_begin,
202 writable,
203 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800204 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800205 error_msg)) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800206 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800207 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800208
Andreas Gampe049cff02015-12-01 23:27:12 -0800209 if (!ret->ComputeFields(requested_base, elf_filename, error_msg)) {
210 return nullptr;
211 }
Andreas Gampe4075f832016-05-18 13:09:54 -0700212
Andreas Gampe049cff02015-12-01 23:27:12 -0800213 ret->PreSetup(elf_filename);
214
215 if (!ret->Setup(abs_dex_location, error_msg)) {
216 return nullptr;
217 }
218
Dave Allison69dfe512014-07-11 17:11:58 +0000219 return ret.release();
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800220}
221
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700222template <typename kOatFileBaseSubType>
223OatFileBase* OatFileBase::OpenOatFile(int vdex_fd,
224 int oat_fd,
225 const std::string& vdex_location,
226 const std::string& oat_location,
227 uint8_t* requested_base,
228 uint8_t* oat_file_begin,
229 bool writable,
230 bool executable,
231 bool low_4gb,
232 const char* abs_dex_location,
233 std::string* error_msg) {
234 std::unique_ptr<OatFileBase> ret(new kOatFileBaseSubType(oat_location, executable));
235
236 if (kIsVdexEnabled && !ret->LoadVdex(vdex_fd, vdex_location, writable, low_4gb, error_msg)) {
237 return nullptr;
238 }
239
240 if (!ret->Load(oat_fd,
241 oat_file_begin,
242 writable,
243 executable,
244 low_4gb,
245 error_msg)) {
246 return nullptr;
247 }
248
249 if (!ret->ComputeFields(requested_base, oat_location, error_msg)) {
250 return nullptr;
251 }
252
253 ret->PreSetup(oat_location);
254
255 if (!ret->Setup(abs_dex_location, error_msg)) {
256 return nullptr;
257 }
258
259 return ret.release();
260}
261
David Brazdil7b49e6c2016-09-01 11:06:18 +0100262bool OatFileBase::LoadVdex(const std::string& vdex_filename,
263 bool writable,
264 bool low_4gb,
265 std::string* error_msg) {
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +0100266 vdex_ = VdexFile::Open(vdex_filename, writable, low_4gb, /* unquicken*/ false, error_msg);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100267 if (vdex_.get() == nullptr) {
268 *error_msg = StringPrintf("Failed to load vdex file '%s' %s",
269 vdex_filename.c_str(),
270 error_msg->c_str());
271 return false;
272 }
273 return true;
274}
275
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700276bool OatFileBase::LoadVdex(int vdex_fd,
277 const std::string& vdex_filename,
278 bool writable,
279 bool low_4gb,
280 std::string* error_msg) {
281 if (vdex_fd != -1) {
282 struct stat s;
283 int rc = TEMP_FAILURE_RETRY(fstat(vdex_fd, &s));
284 if (rc == -1) {
285 PLOG(WARNING) << "Failed getting length of vdex file";
286 } else {
287 vdex_ = VdexFile::Open(vdex_fd,
288 s.st_size,
289 vdex_filename,
290 writable,
291 low_4gb,
292 false /* unquicken */,
293 error_msg);
294 if (vdex_.get() == nullptr) {
295 *error_msg = "Failed opening vdex file.";
296 return false;
297 }
298 }
299 }
300 return true;
301}
302
Andreas Gampe049cff02015-12-01 23:27:12 -0800303bool OatFileBase::ComputeFields(uint8_t* requested_base,
304 const std::string& file_path,
305 std::string* error_msg) {
306 std::string symbol_error_msg;
307 begin_ = FindDynamicSymbolAddress("oatdata", &symbol_error_msg);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700308 if (begin_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800309 *error_msg = StringPrintf("Failed to find oatdata symbol in '%s' %s",
310 file_path.c_str(),
311 symbol_error_msg.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700312 return false;
313 }
314 if (requested_base != nullptr && begin_ != requested_base) {
Nicolas Geoffrayf97cf2a2016-03-09 15:36:23 +0000315 // Host can fail this check. Do not dump there to avoid polluting the output.
Andreas Gampe7ec09042016-04-01 17:20:49 -0700316 if (kIsTargetBuild && (kIsDebugBuild || VLOG_IS_ON(oat))) {
Nicolas Geoffrayf97cf2a2016-03-09 15:36:23 +0000317 PrintFileToLog("/proc/self/maps", LogSeverity::WARNING);
318 }
Andreas Gampefa8429b2015-04-07 18:34:42 -0700319 *error_msg = StringPrintf("Failed to find oatdata symbol at expected address: "
Andreas Gampe049cff02015-12-01 23:27:12 -0800320 "oatdata=%p != expected=%p. See process maps in the log.",
321 begin_, requested_base);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700322 return false;
323 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800324 end_ = FindDynamicSymbolAddress("oatlastword", &symbol_error_msg);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700325 if (end_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800326 *error_msg = StringPrintf("Failed to find oatlastword symbol in '%s' %s",
327 file_path.c_str(),
328 symbol_error_msg.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700329 return false;
330 }
331 // Readjust to be non-inclusive upper bound.
332 end_ += sizeof(uint32_t);
333
Andreas Gampe049cff02015-12-01 23:27:12 -0800334 bss_begin_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbss", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700335 if (bss_begin_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800336 // No .bss section.
Andreas Gampefa8429b2015-04-07 18:34:42 -0700337 bss_end_ = nullptr;
Andreas Gampefa8429b2015-04-07 18:34:42 -0700338 } else {
Andreas Gampe049cff02015-12-01 23:27:12 -0800339 bss_end_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbsslastword", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700340 if (bss_end_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800341 *error_msg = StringPrintf("Failed to find oatbasslastword symbol in '%s'", file_path.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700342 return false;
343 }
344 // Readjust to be non-inclusive upper bound.
345 bss_end_ += sizeof(uint32_t);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100346 // Find bss methods if present.
347 bss_methods_ =
348 const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbssmethods", &symbol_error_msg));
Vladimir Markoaad75c62016-10-03 08:46:48 +0000349 // Find bss roots if present.
350 bss_roots_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbssroots", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700351 }
352
Andreas Gampe049cff02015-12-01 23:27:12 -0800353 return true;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800354}
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800355
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100356// Read an unaligned entry from the OatDexFile data in OatFile and advance the read
357// position by the number of bytes read, i.e. sizeof(T).
358// Return true on success, false if the read would go beyond the end of the OatFile.
359template <typename T>
Vladimir Marko722fa982015-10-19 18:18:27 +0100360inline static bool ReadOatDexFileData(const OatFile& oat_file,
361 /*inout*/const uint8_t** oat,
362 /*out*/T* value) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100363 DCHECK(oat != nullptr);
364 DCHECK(value != nullptr);
365 DCHECK_LE(*oat, oat_file.End());
366 if (UNLIKELY(static_cast<size_t>(oat_file.End() - *oat) < sizeof(T))) {
367 return false;
368 }
369 static_assert(std::is_trivial<T>::value, "T must be a trivial type");
370 typedef __attribute__((__aligned__(1))) T unaligned_type;
371 *value = *reinterpret_cast<const unaligned_type*>(*oat);
372 *oat += sizeof(T);
373 return true;
374}
375
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100376static inline bool MapConstantTables(const gc::space::ImageSpace* space,
377 uint8_t* address) {
378 // If MREMAP_DUP is ever merged to Linux kernel, use it to avoid the unnecessary open()/close().
379 // Note: The current approach relies on the filename still referencing the same inode.
380
381 File file(space->GetImageFilename(), O_RDONLY, /* checkUsage */ false);
382 if (!file.IsOpened()) {
383 LOG(ERROR) << "Failed to open boot image file " << space->GetImageFilename();
384 return false;
385 }
386
387 uint32_t offset = space->GetImageHeader().GetBootImageConstantTablesOffset();
388 uint32_t size = space->GetImageHeader().GetBootImageConstantTablesSize();
389 std::string error_msg;
390 std::unique_ptr<MemMap> mem_map(MemMap::MapFileAtAddress(address,
391 size,
392 PROT_READ,
393 MAP_PRIVATE,
394 file.Fd(),
395 offset,
396 /* low_4gb */ false,
397 /* reuse */ true,
398 file.GetPath().c_str(),
399 &error_msg));
400 if (mem_map == nullptr) {
401 LOG(ERROR) << "Failed to mmap boot image tables from file " << space->GetImageFilename();
402 return false;
403 }
404 return true;
405}
406
Andreas Gampe049cff02015-12-01 23:27:12 -0800407bool OatFileBase::Setup(const char* abs_dex_location, std::string* error_msg) {
Brian Carlstromf1b30302013-03-28 10:35:32 -0700408 if (!GetOatHeader().IsValid()) {
Andreas Gampe2bcb3b22014-12-12 15:25:14 -0800409 std::string cause = GetOatHeader().GetValidationErrorMessage();
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100410 *error_msg = StringPrintf("Invalid oat header for '%s': %s",
411 GetLocation().c_str(),
Andreas Gampe2bcb3b22014-12-12 15:25:14 -0800412 cause.c_str());
Brian Carlstromf1b30302013-03-28 10:35:32 -0700413 return false;
414 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100415 PointerSize pointer_size = GetInstructionSetPointerSize(GetOatHeader().GetInstructionSet());
416 size_t key_value_store_size =
417 (Size() >= sizeof(OatHeader)) ? GetOatHeader().GetKeyValueStoreSize() : 0u;
418 if (Size() < sizeof(OatHeader) + key_value_store_size) {
419 *error_msg = StringPrintf("In oat file '%s' found truncated OatHeader, "
420 "size = %zu < %zu + %zu",
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100421 GetLocation().c_str(),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100422 Size(),
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100423 sizeof(OatHeader),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100424 key_value_store_size);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700425 return false;
426 }
427
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100428 size_t oat_dex_files_offset = GetOatHeader().GetOatDexFilesOffset();
429 if (oat_dex_files_offset < GetOatHeader().GetHeaderSize() || oat_dex_files_offset > Size()) {
430 *error_msg = StringPrintf("In oat file '%s' found invalid oat dex files offset: "
431 "%zu is not in [%zu, %zu]",
432 GetLocation().c_str(),
433 oat_dex_files_offset,
434 GetOatHeader().GetHeaderSize(),
435 Size());
436 return false;
437 }
438 const uint8_t* oat = Begin() + oat_dex_files_offset; // Jump to the OatDexFile records.
439
440 DCHECK_GE(static_cast<size_t>(pointer_size), alignof(GcRoot<mirror::Object>));
441 if (!IsAligned<kPageSize>(bss_begin_) ||
442 !IsAlignedParam(bss_methods_, static_cast<size_t>(pointer_size)) ||
443 !IsAlignedParam(bss_roots_, static_cast<size_t>(pointer_size)) ||
Vladimir Markoaad75c62016-10-03 08:46:48 +0000444 !IsAligned<alignof(GcRoot<mirror::Object>)>(bss_end_)) {
445 *error_msg = StringPrintf("In oat file '%s' found unaligned bss symbol(s): "
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100446 "begin = %p, methods_ = %p, roots = %p, end = %p",
Vladimir Markoaad75c62016-10-03 08:46:48 +0000447 GetLocation().c_str(),
448 bss_begin_,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100449 bss_methods_,
Vladimir Markoaad75c62016-10-03 08:46:48 +0000450 bss_roots_,
451 bss_end_);
452 return false;
453 }
454
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100455 if ((bss_methods_ != nullptr && (bss_methods_ < bss_begin_ || bss_methods_ > bss_end_)) ||
456 (bss_roots_ != nullptr && (bss_roots_ < bss_begin_ || bss_roots_ > bss_end_)) ||
457 (bss_methods_ != nullptr && bss_roots_ != nullptr && bss_methods_ > bss_roots_)) {
458 *error_msg = StringPrintf("In oat file '%s' found bss symbol(s) outside .bss or unordered: "
Vladimir Marko0f3c7002017-09-07 14:15:56 +0100459 "begin = %p, methods = %p, roots = %p, end = %p",
Vladimir Markoaad75c62016-10-03 08:46:48 +0000460 GetLocation().c_str(),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000461 bss_begin_,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100462 bss_methods_,
463 bss_roots_,
Vladimir Markoaad75c62016-10-03 08:46:48 +0000464 bss_end_);
465 return false;
466 }
467
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100468 uint8_t* after_tables =
469 (bss_methods_ != nullptr) ? bss_methods_ : bss_roots_; // May be null.
470 uint8_t* boot_image_tables = (bss_begin_ == after_tables) ? nullptr : bss_begin_;
471 uint8_t* boot_image_tables_end =
472 (bss_begin_ == after_tables) ? nullptr : (after_tables != nullptr) ? after_tables : bss_end_;
473 DCHECK_EQ(boot_image_tables != nullptr, boot_image_tables_end != nullptr);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100474 uint32_t dex_file_count = GetOatHeader().GetDexFileCount();
475 oat_dex_files_storage_.reserve(dex_file_count);
476 for (size_t i = 0; i < dex_file_count; i++) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100477 uint32_t dex_file_location_size;
478 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_location_size))) {
479 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu truncated after dex file "
480 "location size",
481 GetLocation().c_str(),
482 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700483 return false;
484 }
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100485 if (UNLIKELY(dex_file_location_size == 0U)) {
486 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu with empty location name",
487 GetLocation().c_str(),
488 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700489 return false;
490 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000491 if (UNLIKELY(static_cast<size_t>(End() - oat) < dex_file_location_size)) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100492 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu with truncated dex file "
493 "location",
494 GetLocation().c_str(),
495 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700496 return false;
497 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000498 const char* dex_file_location_data = reinterpret_cast<const char*>(oat);
499 oat += dex_file_location_size;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700500
Richard Uhlere5fed032015-03-18 08:21:11 -0700501 std::string dex_file_location = ResolveRelativeEncodedDexLocation(
502 abs_dex_location,
503 std::string(dex_file_location_data, dex_file_location_size));
Brian Carlstrome24fa612011-09-29 00:53:55 -0700504
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100505 uint32_t dex_file_checksum;
506 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_checksum))) {
507 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated after "
508 "dex file checksum",
509 GetLocation().c_str(),
510 i,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700511 dex_file_location.c_str());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700512 return false;
513 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700514
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100515 uint32_t dex_file_offset;
516 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_offset))) {
517 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated "
518 "after dex file offsets",
519 GetLocation().c_str(),
520 i,
521 dex_file_location.c_str());
522 return false;
523 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700524 if (UNLIKELY(dex_file_offset == 0U)) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100525 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with zero dex "
526 "file offset",
527 GetLocation().c_str(),
528 i,
529 dex_file_location.c_str());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700530 return false;
531 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100532 if (UNLIKELY(dex_file_offset > DexSize())) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100533 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
534 "offset %u > %zu",
535 GetLocation().c_str(),
536 i,
537 dex_file_location.c_str(),
538 dex_file_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100539 DexSize());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700540 return false;
541 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100542 if (UNLIKELY(DexSize() - dex_file_offset < sizeof(DexFile::Header))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000543 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
544 "offset %u of %zu but the size of dex file header is %zu",
545 GetLocation().c_str(),
546 i,
547 dex_file_location.c_str(),
548 dex_file_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100549 DexSize(),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000550 sizeof(DexFile::Header));
551 return false;
552 }
Brian Carlstrom89521892011-12-07 22:05:07 -0800553
David Brazdil7b49e6c2016-09-01 11:06:18 +0100554 const uint8_t* dex_file_pointer = DexBegin() + dex_file_offset;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700555 if (UNLIKELY(!DexFile::IsMagicValid(dex_file_pointer))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100556 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with invalid "
557 "dex file magic '%s'",
558 GetLocation().c_str(),
559 i,
560 dex_file_location.c_str(),
561 dex_file_pointer);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700562 return false;
563 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700564 if (UNLIKELY(!DexFile::IsVersionValid(dex_file_pointer))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100565 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with invalid "
566 "dex file version '%s'",
567 GetLocation().c_str(),
568 i,
569 dex_file_location.c_str(),
570 dex_file_pointer);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700571 return false;
572 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800573 const DexFile::Header* header = reinterpret_cast<const DexFile::Header*>(dex_file_pointer);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100574 if (DexSize() - dex_file_offset < header->file_size_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000575 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
576 "offset %u and size %u truncated at %zu",
577 GetLocation().c_str(),
578 i,
579 dex_file_location.c_str(),
580 dex_file_offset,
581 header->file_size_,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100582 DexSize());
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000583 return false;
584 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300585
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000586 uint32_t class_offsets_offset;
587 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &class_offsets_offset))) {
588 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated "
589 "after class offsets offset",
590 GetLocation().c_str(),
591 i,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300592 dex_file_location.c_str());
593 return false;
594 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000595 if (UNLIKELY(class_offsets_offset > Size()) ||
596 UNLIKELY((Size() - class_offsets_offset) / sizeof(uint32_t) < header->class_defs_size_)) {
597 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with truncated "
598 "class offsets, offset %u of %zu, class defs %u",
599 GetLocation().c_str(),
600 i,
601 dex_file_location.c_str(),
602 class_offsets_offset,
603 Size(),
604 header->class_defs_size_);
605 return false;
606 }
607 if (UNLIKELY(!IsAligned<alignof(uint32_t)>(class_offsets_offset))) {
608 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with unaligned "
609 "class offsets, offset %u",
610 GetLocation().c_str(),
611 i,
612 dex_file_location.c_str(),
613 class_offsets_offset);
614 return false;
615 }
616 const uint32_t* class_offsets_pointer =
617 reinterpret_cast<const uint32_t*>(Begin() + class_offsets_offset);
618
619 uint32_t lookup_table_offset;
620 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &lookup_table_offset))) {
621 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zd for '%s' truncated "
622 "after lookup table offset",
623 GetLocation().c_str(),
624 i,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300625 dex_file_location.c_str());
626 return false;
627 }
628 const uint8_t* lookup_table_data = lookup_table_offset != 0u
629 ? Begin() + lookup_table_offset
630 : nullptr;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000631 if (lookup_table_offset != 0u &&
632 (UNLIKELY(lookup_table_offset > Size()) ||
633 UNLIKELY(Size() - lookup_table_offset <
634 TypeLookupTable::RawDataLength(header->class_defs_size_)))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100635 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with truncated "
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000636 "type lookup table, offset %u of %zu, class defs %u",
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100637 GetLocation().c_str(),
638 i,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000639 dex_file_location.c_str(),
640 lookup_table_offset,
641 Size(),
642 header->class_defs_size_);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700643 return false;
644 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700645
Mathieu Chartier120aa282017-08-05 16:03:03 -0700646 uint32_t dex_layout_sections_offset;
647 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_layout_sections_offset))) {
648 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zd for '%s' truncated "
649 "after dex layout sections offset",
650 GetLocation().c_str(),
651 i,
652 dex_file_location.c_str());
653 return false;
654 }
655 const DexLayoutSections* const dex_layout_sections = dex_layout_sections_offset != 0
656 ? reinterpret_cast<const DexLayoutSections*>(Begin() + dex_layout_sections_offset)
657 : nullptr;
658
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100659 uint32_t method_bss_mapping_offset;
660 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &method_bss_mapping_offset))) {
661 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zd for '%s' truncated "
662 "after method bss mapping offset",
663 GetLocation().c_str(),
664 i,
665 dex_file_location.c_str());
666 return false;
667 }
668 const bool readable_method_bss_mapping_size =
669 method_bss_mapping_offset != 0u &&
670 method_bss_mapping_offset <= Size() &&
671 IsAligned<alignof(MethodBssMapping)>(method_bss_mapping_offset) &&
672 Size() - method_bss_mapping_offset >= MethodBssMapping::ComputeSize(0);
673 const MethodBssMapping* method_bss_mapping = readable_method_bss_mapping_size
674 ? reinterpret_cast<const MethodBssMapping*>(Begin() + method_bss_mapping_offset)
675 : nullptr;
676 if (method_bss_mapping_offset != 0u &&
677 (UNLIKELY(method_bss_mapping == nullptr) ||
678 UNLIKELY(method_bss_mapping->size() == 0u) ||
679 UNLIKELY(Size() - method_bss_mapping_offset <
680 MethodBssMapping::ComputeSize(method_bss_mapping->size())))) {
681 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with unaligned or "
682 " truncated method bss mapping, offset %u of %zu, length %zu",
683 GetLocation().c_str(),
684 i,
685 dex_file_location.c_str(),
686 method_bss_mapping_offset,
687 Size(),
688 method_bss_mapping != nullptr ? method_bss_mapping->size() : 0u);
689 return false;
690 }
691 if (kIsDebugBuild && method_bss_mapping != nullptr) {
692 const MethodBssMappingEntry* prev_entry = nullptr;
693 for (const MethodBssMappingEntry& entry : *method_bss_mapping) {
694 CHECK_ALIGNED_PARAM(entry.bss_offset, static_cast<size_t>(pointer_size));
695 CHECK_LT(entry.bss_offset, BssSize());
696 CHECK_LE(POPCOUNT(entry.index_mask) * static_cast<size_t>(pointer_size), entry.bss_offset);
697 size_t index_mask_span = (entry.index_mask != 0u) ? 16u - CTZ(entry.index_mask) : 0u;
698 CHECK_LE(index_mask_span, entry.method_index);
699 if (prev_entry != nullptr) {
700 CHECK_LT(prev_entry->method_index, entry.method_index - index_mask_span);
701 }
702 prev_entry = &entry;
703 }
704 CHECK_LT(prev_entry->method_index,
705 reinterpret_cast<const DexFile::Header*>(dex_file_pointer)->method_ids_size_);
706 }
707
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100708 std::string canonical_location = DexFile::GetDexCanonicalLocation(dex_file_location.c_str());
709
710 // Create the OatDexFile and add it to the owning container.
Vladimir Marko539690a2014-06-05 18:36:42 +0100711 OatDexFile* oat_dex_file = new OatDexFile(this,
712 dex_file_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100713 canonical_location,
Vladimir Marko539690a2014-06-05 18:36:42 +0100714 dex_file_checksum,
715 dex_file_pointer,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300716 lookup_table_data,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100717 method_bss_mapping,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000718 class_offsets_pointer,
Mathieu Chartier120aa282017-08-05 16:03:03 -0700719 dex_layout_sections);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100720 oat_dex_files_storage_.push_back(oat_dex_file);
721
722 // Add the location and canonical location (if different) to the oat_dex_files_ table.
Vladimir Marko3f5838d2014-08-07 18:07:18 +0100723 StringPiece key(oat_dex_file->GetDexFileLocation());
Vladimir Marko539690a2014-06-05 18:36:42 +0100724 oat_dex_files_.Put(key, oat_dex_file);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100725 if (canonical_location != dex_file_location) {
726 StringPiece canonical_key(oat_dex_file->GetCanonicalDexFileLocation());
727 oat_dex_files_.Put(canonical_key, oat_dex_file);
728 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700729 }
Vladimir Marko09d09432015-09-08 13:47:48 +0100730
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100731 if (boot_image_tables != nullptr) {
Vladimir Marko667585a2017-09-29 10:42:31 +0100732 Runtime* runtime = Runtime::Current();
733 if (UNLIKELY(runtime == nullptr)) {
734 // This must be oatdump without boot image. Make sure the .bss is inaccessible.
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700735 CheckedCall(mprotect, "protect bss", const_cast<uint8_t*>(BssBegin()), BssSize(), PROT_NONE);
Vladimir Marko667585a2017-09-29 10:42:31 +0100736 } else {
737 // Map boot image tables into the .bss. The reserved size must match size of the tables.
738 size_t reserved_size = static_cast<size_t>(boot_image_tables_end - boot_image_tables);
739 size_t tables_size = 0u;
740 for (gc::space::ImageSpace* space : runtime->GetHeap()->GetBootImageSpaces()) {
741 tables_size += space->GetImageHeader().GetBootImageConstantTablesSize();
742 DCHECK_ALIGNED(tables_size, kPageSize);
743 }
744 if (tables_size != reserved_size) {
745 *error_msg = StringPrintf("In oat file '%s' found unexpected boot image table sizes, "
746 " %zu bytes, should be %zu.",
747 GetLocation().c_str(),
748 reserved_size,
749 tables_size);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100750 return false;
751 }
Vladimir Marko667585a2017-09-29 10:42:31 +0100752 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
753 uint32_t current_tables_size = space->GetImageHeader().GetBootImageConstantTablesSize();
754 if (current_tables_size != 0u && !MapConstantTables(space, boot_image_tables)) {
755 return false;
756 }
757 boot_image_tables += current_tables_size;
758 }
759 DCHECK(boot_image_tables == boot_image_tables_end);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100760 }
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100761 }
Brian Carlstromf1b30302013-03-28 10:35:32 -0700762 return true;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700763}
764
Andreas Gampe049cff02015-12-01 23:27:12 -0800765////////////////////////
766// OatFile via dlopen //
767////////////////////////
768
Andreas Gampe049cff02015-12-01 23:27:12 -0800769class DlOpenOatFile FINAL : public OatFileBase {
770 public:
771 DlOpenOatFile(const std::string& filename, bool executable)
772 : OatFileBase(filename, executable),
773 dlopen_handle_(nullptr),
Richard Uhlera206c742016-05-24 15:04:22 -0700774 shared_objects_before_(0) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800775 }
776
777 ~DlOpenOatFile() {
778 if (dlopen_handle_ != nullptr) {
Richard Uhlera206c742016-05-24 15:04:22 -0700779 if (!kIsTargetBuild) {
780 MutexLock mu(Thread::Current(), *Locks::host_dlopen_handles_lock_);
781 host_dlopen_handles_.erase(dlopen_handle_);
Mathieu Chartierc7d3f4b2016-06-01 10:48:19 -0700782 dlclose(dlopen_handle_);
783 } else {
784 dlclose(dlopen_handle_);
Richard Uhlera206c742016-05-24 15:04:22 -0700785 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800786 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800787 }
788
789 protected:
790 const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
791 std::string* error_msg) const OVERRIDE {
792 const uint8_t* ptr =
793 reinterpret_cast<const uint8_t*>(dlsym(dlopen_handle_, symbol_name.c_str()));
794 if (ptr == nullptr) {
795 *error_msg = dlerror();
796 }
797 return ptr;
798 }
799
Andreas Gampe4075f832016-05-18 13:09:54 -0700800 void PreLoad() OVERRIDE;
801
Andreas Gampe049cff02015-12-01 23:27:12 -0800802 bool Load(const std::string& elf_filename,
803 uint8_t* oat_file_begin,
804 bool writable,
805 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800806 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800807 std::string* error_msg) OVERRIDE;
808
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700809 bool Load(int, uint8_t*, bool, bool, bool, std::string*) {
810 return false;
811 }
812
Andreas Gampe049cff02015-12-01 23:27:12 -0800813 // Ask the linker where it mmaped the file and notify our mmap wrapper of the regions.
814 void PreSetup(const std::string& elf_filename) OVERRIDE;
815
816 private:
817 bool Dlopen(const std::string& elf_filename,
818 uint8_t* oat_file_begin,
819 std::string* error_msg);
820
Richard Uhlera206c742016-05-24 15:04:22 -0700821 // On the host, if the same library is loaded again with dlopen the same
822 // file handle is returned. This differs from the behavior of dlopen on the
823 // target, where dlopen reloads the library at a different address every
824 // time you load it. The runtime relies on the target behavior to ensure
825 // each instance of the loaded library has a unique dex cache. To avoid
826 // problems, we fall back to our own linker in the case when the same
827 // library is opened multiple times on host. dlopen_handles_ is used to
828 // detect that case.
829 // Guarded by host_dlopen_handles_lock_;
830 static std::unordered_set<void*> host_dlopen_handles_;
831
Andreas Gampe049cff02015-12-01 23:27:12 -0800832 // dlopen handle during runtime.
833 void* dlopen_handle_; // TODO: Unique_ptr with custom deleter.
834
835 // Dummy memory map objects corresponding to the regions mapped by dlopen.
836 std::vector<std::unique_ptr<MemMap>> dlopen_mmaps_;
837
Andreas Gampe4075f832016-05-18 13:09:54 -0700838 // The number of shared objects the linker told us about before loading. Used to
839 // (optimistically) optimize the PreSetup stage (see comment there).
840 size_t shared_objects_before_;
841
Andreas Gampe049cff02015-12-01 23:27:12 -0800842 DISALLOW_COPY_AND_ASSIGN(DlOpenOatFile);
843};
844
Richard Uhlera206c742016-05-24 15:04:22 -0700845std::unordered_set<void*> DlOpenOatFile::host_dlopen_handles_;
846
Andreas Gampe4075f832016-05-18 13:09:54 -0700847void DlOpenOatFile::PreLoad() {
848#ifdef __APPLE__
Andreas Gampe39004a62016-05-18 21:27:00 -0700849 UNUSED(shared_objects_before_);
Andreas Gampe4075f832016-05-18 13:09:54 -0700850 LOG(FATAL) << "Should not reach here.";
851 UNREACHABLE();
852#else
853 // Count the entries in dl_iterate_phdr we get at this point in time.
854 struct dl_iterate_context {
855 static int callback(struct dl_phdr_info *info ATTRIBUTE_UNUSED,
856 size_t size ATTRIBUTE_UNUSED,
857 void *data) {
858 reinterpret_cast<dl_iterate_context*>(data)->count++;
859 return 0; // Continue iteration.
860 }
861 size_t count = 0;
862 } context;
863
864 dl_iterate_phdr(dl_iterate_context::callback, &context);
865 shared_objects_before_ = context.count;
866#endif
867}
868
Andreas Gampe049cff02015-12-01 23:27:12 -0800869bool DlOpenOatFile::Load(const std::string& elf_filename,
870 uint8_t* oat_file_begin,
871 bool writable,
872 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800873 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800874 std::string* error_msg) {
875 // Use dlopen only when flagged to do so, and when it's OK to load things executable.
876 // TODO: Also try when not executable? The issue here could be re-mapping as writable (as
877 // !executable is a sign that we may want to patch), which may not be allowed for
878 // various reasons.
879 if (!kUseDlopen) {
880 *error_msg = "DlOpen is disabled.";
881 return false;
882 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800883 if (low_4gb) {
884 *error_msg = "DlOpen does not support low 4gb loading.";
885 return false;
886 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800887 if (writable) {
888 *error_msg = "DlOpen does not support writable loading.";
889 return false;
890 }
891 if (!executable) {
892 *error_msg = "DlOpen does not support non-executable loading.";
893 return false;
894 }
895
896 // dlopen always returns the same library if it is already opened on the host. For this reason
897 // we only use dlopen if we are the target or we do not already have the dex file opened. Having
898 // the same library loaded multiple times at different addresses is required for class unloading
899 // and for having dex caches arrays in the .bss section.
900 if (!kIsTargetBuild) {
901 if (!kUseDlopenOnHost) {
902 *error_msg = "DlOpen disabled for host.";
903 return false;
904 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800905 }
906
907 bool success = Dlopen(elf_filename, oat_file_begin, error_msg);
908 DCHECK(dlopen_handle_ != nullptr || !success);
909
910 return success;
911}
912
913bool DlOpenOatFile::Dlopen(const std::string& elf_filename,
914 uint8_t* oat_file_begin,
915 std::string* error_msg) {
916#ifdef __APPLE__
917 // The dl_iterate_phdr syscall is missing. There is similar API on OSX,
918 // but let's fallback to the custom loading code for the time being.
919 UNUSED(elf_filename, oat_file_begin);
920 *error_msg = "Dlopen unsupported on Mac.";
921 return false;
922#else
923 {
924 UniqueCPtr<char> absolute_path(realpath(elf_filename.c_str(), nullptr));
925 if (absolute_path == nullptr) {
926 *error_msg = StringPrintf("Failed to find absolute path for '%s'", elf_filename.c_str());
927 return false;
928 }
Bilyan Borisovbb661c02016-04-04 16:27:32 +0100929#ifdef ART_TARGET_ANDROID
Anton Kirilov3a2e78e2017-01-06 13:33:42 +0000930 android_dlextinfo extinfo = {};
Andreas Gampe049cff02015-12-01 23:27:12 -0800931 extinfo.flags = ANDROID_DLEXT_FORCE_LOAD | // Force-load, don't reuse handle
932 // (open oat files multiple
933 // times).
934 ANDROID_DLEXT_FORCE_FIXED_VADDR; // Take a non-zero vaddr as absolute
935 // (non-pic boot image).
Andreas Gampe226b91e2015-12-02 10:29:33 -0800936 if (oat_file_begin != nullptr) { //
937 extinfo.flags |= ANDROID_DLEXT_LOAD_AT_FIXED_ADDRESS; // Use the requested addr if
938 extinfo.reserved_addr = oat_file_begin; // vaddr = 0.
939 } // (pic boot image).
Andreas Gampe049cff02015-12-01 23:27:12 -0800940 dlopen_handle_ = android_dlopen_ext(absolute_path.get(), RTLD_NOW, &extinfo);
941#else
Andreas Gampe049cff02015-12-01 23:27:12 -0800942 UNUSED(oat_file_begin);
Julien Duraj1af0c4f2016-11-16 14:05:48 +0000943 static_assert(!kIsTargetBuild || kIsTargetLinux, "host_dlopen_handles_ will leak handles");
Mathieu Chartierc7d3f4b2016-06-01 10:48:19 -0700944 MutexLock mu(Thread::Current(), *Locks::host_dlopen_handles_lock_);
Richard Uhlera206c742016-05-24 15:04:22 -0700945 dlopen_handle_ = dlopen(absolute_path.get(), RTLD_NOW);
946 if (dlopen_handle_ != nullptr) {
Richard Uhlera206c742016-05-24 15:04:22 -0700947 if (!host_dlopen_handles_.insert(dlopen_handle_).second) {
948 dlclose(dlopen_handle_);
949 dlopen_handle_ = nullptr;
950 *error_msg = StringPrintf("host dlopen re-opened '%s'", elf_filename.c_str());
951 return false;
952 }
953 }
Bilyan Borisovbb661c02016-04-04 16:27:32 +0100954#endif // ART_TARGET_ANDROID
Andreas Gampe049cff02015-12-01 23:27:12 -0800955 }
956 if (dlopen_handle_ == nullptr) {
957 *error_msg = StringPrintf("Failed to dlopen '%s': %s", elf_filename.c_str(), dlerror());
958 return false;
959 }
960 return true;
961#endif
962}
963
964void DlOpenOatFile::PreSetup(const std::string& elf_filename) {
Andreas Gampe74f07b52015-12-02 11:53:26 -0800965#ifdef __APPLE__
966 UNUSED(elf_filename);
967 LOG(FATAL) << "Should not reach here.";
968 UNREACHABLE();
969#else
Andreas Gampe049cff02015-12-01 23:27:12 -0800970 struct dl_iterate_context {
971 static int callback(struct dl_phdr_info *info, size_t /* size */, void *data) {
972 auto* context = reinterpret_cast<dl_iterate_context*>(data);
Andreas Gampe4075f832016-05-18 13:09:54 -0700973 context->shared_objects_seen++;
974 if (context->shared_objects_seen < context->shared_objects_before) {
975 // We haven't been called yet for anything we haven't seen before. Just continue.
976 // Note: this is aggressively optimistic. If another thread was unloading a library,
977 // we may miss out here. However, this does not happen often in practice.
978 return 0;
979 }
980
Andreas Gampe049cff02015-12-01 23:27:12 -0800981 // See whether this callback corresponds to the file which we have just loaded.
982 bool contains_begin = false;
983 for (int i = 0; i < info->dlpi_phnum; i++) {
984 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
985 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
986 info->dlpi_phdr[i].p_vaddr);
987 size_t memsz = info->dlpi_phdr[i].p_memsz;
988 if (vaddr <= context->begin_ && context->begin_ < vaddr + memsz) {
989 contains_begin = true;
990 break;
991 }
992 }
993 }
994 // Add dummy mmaps for this file.
995 if (contains_begin) {
996 for (int i = 0; i < info->dlpi_phnum; i++) {
997 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
998 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
999 info->dlpi_phdr[i].p_vaddr);
1000 size_t memsz = info->dlpi_phdr[i].p_memsz;
1001 MemMap* mmap = MemMap::MapDummy(info->dlpi_name, vaddr, memsz);
1002 context->dlopen_mmaps_->push_back(std::unique_ptr<MemMap>(mmap));
1003 }
1004 }
1005 return 1; // Stop iteration and return 1 from dl_iterate_phdr.
1006 }
1007 return 0; // Continue iteration and return 0 from dl_iterate_phdr when finished.
1008 }
1009 const uint8_t* const begin_;
1010 std::vector<std::unique_ptr<MemMap>>* const dlopen_mmaps_;
Andreas Gampe4075f832016-05-18 13:09:54 -07001011 const size_t shared_objects_before;
1012 size_t shared_objects_seen;
1013 };
1014 dl_iterate_context context = { Begin(), &dlopen_mmaps_, shared_objects_before_, 0};
Andreas Gampe049cff02015-12-01 23:27:12 -08001015
1016 if (dl_iterate_phdr(dl_iterate_context::callback, &context) == 0) {
Andreas Gampe4075f832016-05-18 13:09:54 -07001017 // Hm. Maybe our optimization went wrong. Try another time with shared_objects_before == 0
1018 // before giving up. This should be unusual.
1019 VLOG(oat) << "Need a second run in PreSetup, didn't find with shared_objects_before="
1020 << shared_objects_before_;
1021 dl_iterate_context context0 = { Begin(), &dlopen_mmaps_, 0, 0};
1022 if (dl_iterate_phdr(dl_iterate_context::callback, &context0) == 0) {
1023 // OK, give up and print an error.
1024 PrintFileToLog("/proc/self/maps", LogSeverity::WARNING);
1025 LOG(ERROR) << "File " << elf_filename << " loaded with dlopen but cannot find its mmaps.";
1026 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001027 }
Andreas Gampe74f07b52015-12-02 11:53:26 -08001028#endif
Andreas Gampe049cff02015-12-01 23:27:12 -08001029}
1030
1031////////////////////////////////////////////////
1032// OatFile via our own ElfFile implementation //
1033////////////////////////////////////////////////
1034
1035class ElfOatFile FINAL : public OatFileBase {
1036 public:
1037 ElfOatFile(const std::string& filename, bool executable) : OatFileBase(filename, executable) {}
1038
1039 static ElfOatFile* OpenElfFile(File* file,
1040 const std::string& location,
1041 uint8_t* requested_base,
1042 uint8_t* oat_file_begin, // Override base if not null
1043 bool writable,
1044 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001045 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001046 const char* abs_dex_location,
1047 std::string* error_msg);
1048
1049 bool InitializeFromElfFile(ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +01001050 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001051 const char* abs_dex_location,
1052 std::string* error_msg);
1053
1054 protected:
1055 const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
1056 std::string* error_msg) const OVERRIDE {
1057 const uint8_t* ptr = elf_file_->FindDynamicSymbolAddress(symbol_name);
1058 if (ptr == nullptr) {
1059 *error_msg = "(Internal implementation could not find symbol)";
1060 }
1061 return ptr;
1062 }
1063
Andreas Gampe4075f832016-05-18 13:09:54 -07001064 void PreLoad() OVERRIDE {
1065 }
1066
Andreas Gampe049cff02015-12-01 23:27:12 -08001067 bool Load(const std::string& elf_filename,
1068 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1069 bool writable,
1070 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001071 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001072 std::string* error_msg) OVERRIDE;
1073
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001074 bool Load(int oat_fd,
1075 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1076 bool writable,
1077 bool executable,
1078 bool low_4gb,
1079 std::string* error_msg) OVERRIDE;
1080
Andreas Gampe049cff02015-12-01 23:27:12 -08001081 void PreSetup(const std::string& elf_filename ATTRIBUTE_UNUSED) OVERRIDE {
1082 }
1083
1084 private:
1085 bool ElfFileOpen(File* file,
1086 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1087 bool writable,
1088 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001089 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001090 std::string* error_msg);
1091
1092 private:
1093 // Backing memory map for oat file during cross compilation.
1094 std::unique_ptr<ElfFile> elf_file_;
1095
1096 DISALLOW_COPY_AND_ASSIGN(ElfOatFile);
1097};
1098
1099ElfOatFile* ElfOatFile::OpenElfFile(File* file,
1100 const std::string& location,
1101 uint8_t* requested_base,
1102 uint8_t* oat_file_begin, // Override base if not null
1103 bool writable,
1104 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001105 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001106 const char* abs_dex_location,
1107 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001108 ScopedTrace trace("Open elf file " + location);
Andreas Gampe049cff02015-12-01 23:27:12 -08001109 std::unique_ptr<ElfOatFile> oat_file(new ElfOatFile(location, executable));
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001110 bool success = oat_file->ElfFileOpen(file,
1111 oat_file_begin,
1112 writable,
1113 low_4gb,
1114 executable,
1115 error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -08001116 if (!success) {
1117 CHECK(!error_msg->empty());
1118 return nullptr;
1119 }
1120
1121 // Complete the setup.
1122 if (!oat_file->ComputeFields(requested_base, file->GetPath(), error_msg)) {
1123 return nullptr;
1124 }
1125
1126 if (!oat_file->Setup(abs_dex_location, error_msg)) {
1127 return nullptr;
1128 }
1129
1130 return oat_file.release();
1131}
1132
1133bool ElfOatFile::InitializeFromElfFile(ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +01001134 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001135 const char* abs_dex_location,
1136 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001137 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -08001138 if (IsExecutable()) {
1139 *error_msg = "Cannot initialize from elf file in executable mode.";
1140 return false;
1141 }
1142 elf_file_.reset(elf_file);
David Brazdilc93b3be2016-09-12 18:49:58 +01001143 SetVdex(vdex_file);
Andreas Gampe049cff02015-12-01 23:27:12 -08001144 uint64_t offset, size;
1145 bool has_section = elf_file->GetSectionOffsetAndSize(".rodata", &offset, &size);
1146 CHECK(has_section);
1147 SetBegin(elf_file->Begin() + offset);
1148 SetEnd(elf_file->Begin() + size + offset);
1149 // Ignore the optional .bss section when opening non-executable.
1150 return Setup(abs_dex_location, error_msg);
1151}
1152
1153bool ElfOatFile::Load(const std::string& elf_filename,
1154 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1155 bool writable,
1156 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001157 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001158 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001159 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -08001160 std::unique_ptr<File> file(OS::OpenFileForReading(elf_filename.c_str()));
1161 if (file == nullptr) {
1162 *error_msg = StringPrintf("Failed to open oat filename for reading: %s", strerror(errno));
1163 return false;
1164 }
1165 return ElfOatFile::ElfFileOpen(file.get(),
1166 oat_file_begin,
1167 writable,
1168 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001169 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001170 error_msg);
1171}
1172
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001173bool ElfOatFile::Load(int oat_fd,
1174 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1175 bool writable,
1176 bool executable,
1177 bool low_4gb,
1178 std::string* error_msg) {
1179 ScopedTrace trace(__PRETTY_FUNCTION__);
1180 if (oat_fd != -1) {
1181 std::unique_ptr<File> file = std::make_unique<File>(oat_fd, false);
1182 file->DisableAutoClose();
1183 if (file == nullptr) {
1184 *error_msg = StringPrintf("Failed to open oat filename for reading: %s",
1185 strerror(errno));
1186 return false;
1187 }
1188 return ElfOatFile::ElfFileOpen(file.get(),
1189 oat_file_begin,
1190 writable,
1191 executable,
1192 low_4gb,
1193 error_msg);
1194 }
1195 return false;
1196}
1197
Andreas Gampe049cff02015-12-01 23:27:12 -08001198bool ElfOatFile::ElfFileOpen(File* file,
1199 uint8_t* oat_file_begin,
1200 bool writable,
1201 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001202 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001203 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001204 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -08001205 // TODO: rename requested_base to oat_data_begin
1206 elf_file_.reset(ElfFile::Open(file,
1207 writable,
1208 /*program_header_only*/true,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001209 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001210 error_msg,
1211 oat_file_begin));
1212 if (elf_file_ == nullptr) {
1213 DCHECK(!error_msg->empty());
1214 return false;
1215 }
Brian Carlstromf5b0f2c2016-10-14 01:04:26 -07001216 bool loaded = elf_file_->Load(file, executable, low_4gb, error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -08001217 DCHECK(loaded || !error_msg->empty());
1218 return loaded;
1219}
1220
1221//////////////////////////
1222// General OatFile code //
1223//////////////////////////
1224
1225std::string OatFile::ResolveRelativeEncodedDexLocation(
1226 const char* abs_dex_location, const std::string& rel_dex_location) {
1227 if (abs_dex_location != nullptr && rel_dex_location[0] != '/') {
1228 // Strip :classes<N>.dex used for secondary multidex files.
1229 std::string base = DexFile::GetBaseLocation(rel_dex_location);
1230 std::string multidex_suffix = DexFile::GetMultiDexSuffix(rel_dex_location);
1231
1232 // Check if the base is a suffix of the provided abs_dex_location.
1233 std::string target_suffix = "/" + base;
1234 std::string abs_location(abs_dex_location);
1235 if (abs_location.size() > target_suffix.size()) {
1236 size_t pos = abs_location.size() - target_suffix.size();
1237 if (abs_location.compare(pos, std::string::npos, target_suffix) == 0) {
1238 return abs_location + multidex_suffix;
1239 }
1240 }
1241 }
1242 return rel_dex_location;
1243}
1244
1245static void CheckLocation(const std::string& location) {
1246 CHECK(!location.empty());
1247}
1248
1249OatFile* OatFile::OpenWithElfFile(ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +01001250 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001251 const std::string& location,
1252 const char* abs_dex_location,
1253 std::string* error_msg) {
1254 std::unique_ptr<ElfOatFile> oat_file(new ElfOatFile(location, false /* executable */));
David Brazdilc93b3be2016-09-12 18:49:58 +01001255 return oat_file->InitializeFromElfFile(elf_file, vdex_file, abs_dex_location, error_msg)
Andreas Gampe049cff02015-12-01 23:27:12 -08001256 ? oat_file.release()
1257 : nullptr;
1258}
1259
David Brazdil7b49e6c2016-09-01 11:06:18 +01001260OatFile* OatFile::Open(const std::string& oat_filename,
1261 const std::string& oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001262 uint8_t* requested_base,
1263 uint8_t* oat_file_begin,
1264 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001265 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001266 const char* abs_dex_location,
1267 std::string* error_msg) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001268 ScopedTrace trace("Open oat file " + oat_location);
1269 CHECK(!oat_filename.empty()) << oat_location;
1270 CheckLocation(oat_location);
Andreas Gampe54315c72016-05-18 21:10:42 -07001271
Calin Juravle367b9d82017-05-15 18:18:39 -07001272 std::string vdex_filename = GetVdexFilename(oat_filename);
David Brazdil7b49e6c2016-09-01 11:06:18 +01001273
1274 // Check that the files even exist, fast-fail.
1275 if (kIsVdexEnabled && !OS::FileExists(vdex_filename.c_str())) {
1276 *error_msg = StringPrintf("File %s does not exist.", vdex_filename.c_str());
1277 return nullptr;
1278 } else if (!OS::FileExists(oat_filename.c_str())) {
1279 *error_msg = StringPrintf("File %s does not exist.", oat_filename.c_str());
Andreas Gampe54315c72016-05-18 21:10:42 -07001280 return nullptr;
1281 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001282
1283 // Try dlopen first, as it is required for native debuggability. This will fail fast if dlopen is
1284 // disabled.
David Brazdil7b49e6c2016-09-01 11:06:18 +01001285 OatFile* with_dlopen = OatFileBase::OpenOatFile<DlOpenOatFile>(vdex_filename,
1286 oat_filename,
1287 oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001288 requested_base,
1289 oat_file_begin,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001290 false /* writable */,
Andreas Gampe049cff02015-12-01 23:27:12 -08001291 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001292 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001293 abs_dex_location,
1294 error_msg);
1295 if (with_dlopen != nullptr) {
1296 return with_dlopen;
1297 }
1298 if (kPrintDlOpenErrorMessage) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001299 LOG(ERROR) << "Failed to dlopen: " << oat_filename << " with error " << *error_msg;
Andreas Gampe049cff02015-12-01 23:27:12 -08001300 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001301 // If we aren't trying to execute, we just use our own ElfFile loader for a couple reasons:
1302 //
1303 // On target, dlopen may fail when compiling due to selinux restrictions on installd.
1304 //
1305 // We use our own ELF loader for Quick to deal with legacy apps that
1306 // open a generated dex file by name, remove the file, then open
1307 // another generated dex file with the same name. http://b/10614658
1308 //
1309 // On host, dlopen is expected to fail when cross compiling, so fall back to OpenElfFile.
1310 //
1311 //
1312 // Another independent reason is the absolute placement of boot.oat. dlopen on the host usually
1313 // 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 +01001314 OatFile* with_internal = OatFileBase::OpenOatFile<ElfOatFile>(vdex_filename,
1315 oat_filename,
1316 oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001317 requested_base,
1318 oat_file_begin,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001319 false /* writable */,
Andreas Gampe049cff02015-12-01 23:27:12 -08001320 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001321 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001322 abs_dex_location,
1323 error_msg);
1324 return with_internal;
1325}
1326
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001327OatFile* OatFile::Open(int vdex_fd,
1328 int oat_fd,
1329 const std::string& oat_location,
1330 uint8_t* requested_base,
1331 uint8_t* oat_file_begin,
1332 bool executable,
1333 bool low_4gb,
1334 const char* abs_dex_location,
1335 std::string* error_msg) {
1336 CHECK(!oat_location.empty()) << oat_location;
1337
1338 std::string vdex_location = GetVdexFilename(oat_location);
1339
1340 OatFile* with_internal = OatFileBase::OpenOatFile<ElfOatFile>(vdex_fd,
1341 oat_fd,
1342 vdex_location,
1343 oat_location,
1344 requested_base,
1345 oat_file_begin,
1346 false /* writable */,
1347 executable,
1348 low_4gb,
1349 abs_dex_location,
1350 error_msg);
1351 return with_internal;
1352}
1353
Andreas Gampe049cff02015-12-01 23:27:12 -08001354OatFile* OatFile::OpenWritable(File* file,
1355 const std::string& location,
1356 const char* abs_dex_location,
1357 std::string* error_msg) {
1358 CheckLocation(location);
1359 return ElfOatFile::OpenElfFile(file,
1360 location,
1361 nullptr,
1362 nullptr,
1363 true,
1364 false,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001365 /*low_4gb*/false,
Andreas Gampe049cff02015-12-01 23:27:12 -08001366 abs_dex_location,
1367 error_msg);
1368}
1369
1370OatFile* OatFile::OpenReadable(File* file,
1371 const std::string& location,
1372 const char* abs_dex_location,
1373 std::string* error_msg) {
1374 CheckLocation(location);
1375 return ElfOatFile::OpenElfFile(file,
1376 location,
1377 nullptr,
1378 nullptr,
1379 false,
1380 false,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001381 /*low_4gb*/false,
Andreas Gampe049cff02015-12-01 23:27:12 -08001382 abs_dex_location,
1383 error_msg);
1384}
1385
1386OatFile::OatFile(const std::string& location, bool is_executable)
1387 : location_(location),
David Brazdil7b49e6c2016-09-01 11:06:18 +01001388 vdex_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001389 begin_(nullptr),
1390 end_(nullptr),
1391 bss_begin_(nullptr),
1392 bss_end_(nullptr),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001393 bss_methods_(nullptr),
Vladimir Markoaad75c62016-10-03 08:46:48 +00001394 bss_roots_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001395 is_executable_(is_executable),
1396 secondary_lookup_lock_("OatFile secondary lookup lock", kOatFileSecondaryLookupLock) {
1397 CHECK(!location_.empty());
1398}
1399
1400OatFile::~OatFile() {
1401 STLDeleteElements(&oat_dex_files_storage_);
1402}
1403
Brian Carlstrome24fa612011-09-29 00:53:55 -07001404const OatHeader& OatFile::GetOatHeader() const {
Ian Rogers30fab402012-01-23 15:43:46 -08001405 return *reinterpret_cast<const OatHeader*>(Begin());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001406}
1407
Ian Rogers13735952014-10-08 12:43:28 -07001408const uint8_t* OatFile::Begin() const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001409 CHECK(begin_ != nullptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001410 return begin_;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001411}
1412
Ian Rogers13735952014-10-08 12:43:28 -07001413const uint8_t* OatFile::End() const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001414 CHECK(end_ != nullptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001415 return end_;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001416}
1417
Vladimir Marko5c42c292015-02-25 12:02:49 +00001418const uint8_t* OatFile::BssBegin() const {
1419 return bss_begin_;
1420}
1421
1422const uint8_t* OatFile::BssEnd() const {
1423 return bss_end_;
1424}
1425
David Brazdil7b49e6c2016-09-01 11:06:18 +01001426const uint8_t* OatFile::DexBegin() const {
1427 return kIsVdexEnabled ? vdex_->Begin() : Begin();
1428}
1429
1430const uint8_t* OatFile::DexEnd() const {
1431 return kIsVdexEnabled ? vdex_->End() : End();
1432}
1433
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001434ArrayRef<ArtMethod*> OatFile::GetBssMethods() const {
1435 if (bss_methods_ != nullptr) {
1436 ArtMethod** methods = reinterpret_cast<ArtMethod**>(bss_methods_);
1437 ArtMethod** methods_end =
1438 reinterpret_cast<ArtMethod**>(bss_roots_ != nullptr ? bss_roots_ : bss_end_);
1439 return ArrayRef<ArtMethod*>(methods, methods_end - methods);
1440 } else {
1441 return ArrayRef<ArtMethod*>();
1442 }
1443}
1444
Vladimir Markoaad75c62016-10-03 08:46:48 +00001445ArrayRef<GcRoot<mirror::Object>> OatFile::GetBssGcRoots() const {
1446 if (bss_roots_ != nullptr) {
1447 auto* roots = reinterpret_cast<GcRoot<mirror::Object>*>(bss_roots_);
1448 auto* roots_end = reinterpret_cast<GcRoot<mirror::Object>*>(bss_end_);
1449 return ArrayRef<GcRoot<mirror::Object>>(roots, roots_end - roots);
1450 } else {
1451 return ArrayRef<GcRoot<mirror::Object>>();
1452 }
1453}
1454
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001455const OatFile::OatDexFile* OatFile::GetOatDexFile(const char* dex_location,
1456 const uint32_t* dex_location_checksum,
Richard Uhler9a37efc2016-08-05 16:32:55 -07001457 std::string* error_msg) const {
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001458 // NOTE: We assume here that the canonical location for a given dex_location never
1459 // changes. If it does (i.e. some symlink used by the filename changes) we may return
1460 // an incorrect OatDexFile. As long as we have a checksum to check, we shall return
1461 // an identical file or fail; otherwise we may see some unpredictable failures.
Calin Juravle4e1d5792014-07-15 23:56:47 +01001462
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001463 // TODO: Additional analysis of usage patterns to see if this can be simplified
1464 // without any performance loss, for example by not doing the first lock-free lookup.
1465
1466 const OatFile::OatDexFile* oat_dex_file = nullptr;
1467 StringPiece key(dex_location);
1468 // Try to find the key cheaply in the oat_dex_files_ map which holds dex locations
1469 // directly mentioned in the oat file and doesn't require locking.
1470 auto primary_it = oat_dex_files_.find(key);
1471 if (primary_it != oat_dex_files_.end()) {
1472 oat_dex_file = primary_it->second;
1473 DCHECK(oat_dex_file != nullptr);
1474 } else {
1475 // This dex_location is not one of the dex locations directly mentioned in the
1476 // oat file. The correct lookup is via the canonical location but first see in
1477 // the secondary_oat_dex_files_ whether we've looked up this location before.
1478 MutexLock mu(Thread::Current(), secondary_lookup_lock_);
1479 auto secondary_lb = secondary_oat_dex_files_.lower_bound(key);
1480 if (secondary_lb != secondary_oat_dex_files_.end() && key == secondary_lb->first) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001481 oat_dex_file = secondary_lb->second; // May be null.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001482 } else {
1483 // We haven't seen this dex_location before, we must check the canonical location.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001484 std::string dex_canonical_location = DexFile::GetDexCanonicalLocation(dex_location);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001485 if (dex_canonical_location != dex_location) {
1486 StringPiece canonical_key(dex_canonical_location);
1487 auto canonical_it = oat_dex_files_.find(canonical_key);
1488 if (canonical_it != oat_dex_files_.end()) {
1489 oat_dex_file = canonical_it->second;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001490 } // else keep null.
1491 } // else keep null.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001492
1493 // Copy the key to the string_cache_ and store the result in secondary map.
1494 string_cache_.emplace_back(key.data(), key.length());
1495 StringPiece key_copy(string_cache_.back());
1496 secondary_oat_dex_files_.PutBefore(secondary_lb, key_copy, oat_dex_file);
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001497 }
1498 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001499
1500 if (oat_dex_file == nullptr) {
1501 if (error_msg != nullptr) {
1502 std::string dex_canonical_location = DexFile::GetDexCanonicalLocation(dex_location);
1503 *error_msg = "Failed to find OatDexFile for DexFile " + std::string(dex_location)
1504 + " (canonical path " + dex_canonical_location + ") in OatFile " + GetLocation();
1505 }
1506 return nullptr;
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001507 }
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001508
Richard Uhler9a37efc2016-08-05 16:32:55 -07001509 if (dex_location_checksum != nullptr &&
1510 oat_dex_file->GetDexFileLocationChecksum() != *dex_location_checksum) {
1511 if (error_msg != nullptr) {
1512 std::string dex_canonical_location = DexFile::GetDexCanonicalLocation(dex_location);
1513 std::string checksum = StringPrintf("0x%08x", oat_dex_file->GetDexFileLocationChecksum());
1514 std::string required_checksum = StringPrintf("0x%08x", *dex_location_checksum);
1515 *error_msg = "OatDexFile for DexFile " + std::string(dex_location)
1516 + " (canonical path " + dex_canonical_location + ") in OatFile " + GetLocation()
1517 + " has checksum " + checksum + " but " + required_checksum + " was required";
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001518 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001519 return nullptr;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001520 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001521 return oat_dex_file;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001522}
1523
Brian Carlstrome24fa612011-09-29 00:53:55 -07001524OatFile::OatDexFile::OatDexFile(const OatFile* oat_file,
Elliott Hughesaa6a5882012-01-13 19:39:16 -08001525 const std::string& dex_file_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001526 const std::string& canonical_dex_file_location,
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001527 uint32_t dex_file_location_checksum,
Ian Rogers13735952014-10-08 12:43:28 -07001528 const uint8_t* dex_file_pointer,
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001529 const uint8_t* lookup_table_data,
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001530 const MethodBssMapping* method_bss_mapping_data,
Vladimir Marko09d09432015-09-08 13:47:48 +01001531 const uint32_t* oat_class_offsets_pointer,
Mathieu Chartier120aa282017-08-05 16:03:03 -07001532 const DexLayoutSections* dex_layout_sections)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001533 : oat_file_(oat_file),
1534 dex_file_location_(dex_file_location),
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001535 canonical_dex_file_location_(canonical_dex_file_location),
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001536 dex_file_location_checksum_(dex_file_location_checksum),
Brian Carlstrom89521892011-12-07 22:05:07 -08001537 dex_file_pointer_(dex_file_pointer),
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001538 lookup_table_data_(lookup_table_data),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001539 method_bss_mapping_(method_bss_mapping_data),
Vladimir Marko09d09432015-09-08 13:47:48 +01001540 oat_class_offsets_pointer_(oat_class_offsets_pointer),
Mathieu Chartier120aa282017-08-05 16:03:03 -07001541 dex_layout_sections_(dex_layout_sections) {
David Sehr9aa352e2016-09-15 18:13:52 -07001542 // Initialize TypeLookupTable.
1543 if (lookup_table_data_ != nullptr) {
1544 // Peek the number of classes from the DexFile.
1545 const DexFile::Header* dex_header = reinterpret_cast<const DexFile::Header*>(dex_file_pointer_);
1546 const uint32_t num_class_defs = dex_header->class_defs_size_;
1547 if (lookup_table_data_ + TypeLookupTable::RawDataLength(num_class_defs) > GetOatFile()->End()) {
1548 LOG(WARNING) << "found truncated lookup table in " << dex_file_location_;
1549 } else {
Mathieu Chartier1b868492016-11-16 16:22:37 -08001550 lookup_table_ = TypeLookupTable::Open(dex_file_pointer_, lookup_table_data_, num_class_defs);
David Sehr9aa352e2016-09-15 18:13:52 -07001551 }
1552 }
1553}
Brian Carlstrome24fa612011-09-29 00:53:55 -07001554
Mathieu Chartier1b868492016-11-16 16:22:37 -08001555OatFile::OatDexFile::OatDexFile(std::unique_ptr<TypeLookupTable>&& lookup_table)
1556 : lookup_table_(std::move(lookup_table)) {}
1557
Brian Carlstrome24fa612011-09-29 00:53:55 -07001558OatFile::OatDexFile::~OatDexFile() {}
1559
Ian Rogers05f28c62012-10-23 18:12:13 -07001560size_t OatFile::OatDexFile::FileSize() const {
1561 return reinterpret_cast<const DexFile::Header*>(dex_file_pointer_)->file_size_;
1562}
1563
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001564std::unique_ptr<const DexFile> OatFile::OatDexFile::OpenDexFile(std::string* error_msg) const {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001565 ScopedTrace trace(__PRETTY_FUNCTION__);
Aart Bik37d6a3b2016-06-21 18:30:10 -07001566 static constexpr bool kVerify = false;
1567 static constexpr bool kVerifyChecksum = false;
Andreas Gampe3a2bd292016-01-26 17:23:47 -08001568 return DexFile::Open(dex_file_pointer_,
1569 FileSize(),
1570 dex_file_location_,
1571 dex_file_location_checksum_,
1572 this,
Aart Bik37d6a3b2016-06-21 18:30:10 -07001573 kVerify,
1574 kVerifyChecksum,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08001575 error_msg);
Brian Carlstrom89521892011-12-07 22:05:07 -08001576}
1577
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001578uint32_t OatFile::OatDexFile::GetOatClassOffset(uint16_t class_def_index) const {
1579 return oat_class_offsets_pointer_[class_def_index];
1580}
1581
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001582OatFile::OatClass OatFile::OatDexFile::GetOatClass(uint16_t class_def_index) const {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001583 uint32_t oat_class_offset = GetOatClassOffset(class_def_index);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001584
Ian Rogers13735952014-10-08 12:43:28 -07001585 const uint8_t* oat_class_pointer = oat_file_->Begin() + oat_class_offset;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001586 CHECK_LT(oat_class_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001587
Ian Rogers13735952014-10-08 12:43:28 -07001588 const uint8_t* status_pointer = oat_class_pointer;
Brian Carlstromba150c32013-08-27 17:31:03 -07001589 CHECK_LT(status_pointer, oat_file_->End()) << oat_file_->GetLocation();
1590 mirror::Class::Status status =
1591 static_cast<mirror::Class::Status>(*reinterpret_cast<const int16_t*>(status_pointer));
1592 CHECK_LT(status, mirror::Class::kStatusMax);
1593
Ian Rogers13735952014-10-08 12:43:28 -07001594 const uint8_t* type_pointer = status_pointer + sizeof(uint16_t);
Brian Carlstromba150c32013-08-27 17:31:03 -07001595 CHECK_LT(type_pointer, oat_file_->End()) << oat_file_->GetLocation();
1596 OatClassType type = static_cast<OatClassType>(*reinterpret_cast<const uint16_t*>(type_pointer));
1597 CHECK_LT(type, kOatClassMax);
1598
Ian Rogers13735952014-10-08 12:43:28 -07001599 const uint8_t* after_type_pointer = type_pointer + sizeof(int16_t);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001600 CHECK_LE(after_type_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07001601
Brian Carlstromcd937a92014-03-04 22:53:23 -08001602 uint32_t bitmap_size = 0;
Ian Rogers13735952014-10-08 12:43:28 -07001603 const uint8_t* bitmap_pointer = nullptr;
1604 const uint8_t* methods_pointer = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07001605 if (type != kOatClassNoneCompiled) {
1606 if (type == kOatClassSomeCompiled) {
1607 bitmap_size = static_cast<uint32_t>(*reinterpret_cast<const uint32_t*>(after_type_pointer));
1608 bitmap_pointer = after_type_pointer + sizeof(bitmap_size);
1609 CHECK_LE(bitmap_pointer, oat_file_->End()) << oat_file_->GetLocation();
1610 methods_pointer = bitmap_pointer + bitmap_size;
1611 } else {
1612 methods_pointer = after_type_pointer;
1613 }
1614 CHECK_LE(methods_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstromcd937a92014-03-04 22:53:23 -08001615 }
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001616
Richard Uhler07b3c232015-03-31 15:57:54 -07001617 return OatFile::OatClass(oat_file_,
1618 status,
1619 type,
1620 bitmap_size,
1621 reinterpret_cast<const uint32_t*>(bitmap_pointer),
1622 reinterpret_cast<const OatMethodOffsets*>(methods_pointer));
Brian Carlstrome24fa612011-09-29 00:53:55 -07001623}
1624
David Sehr9aa352e2016-09-15 18:13:52 -07001625const DexFile::ClassDef* OatFile::OatDexFile::FindClassDef(const DexFile& dex_file,
1626 const char* descriptor,
1627 size_t hash) {
1628 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1629 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
1630 if (LIKELY((oat_dex_file != nullptr) && (oat_dex_file->GetTypeLookupTable() != nullptr))) {
1631 const uint32_t class_def_idx = oat_dex_file->GetTypeLookupTable()->Lookup(descriptor, hash);
Andreas Gampee2abbc62017-09-15 11:59:26 -07001632 return (class_def_idx != dex::kDexNoIndex) ? &dex_file.GetClassDef(class_def_idx) : nullptr;
David Sehr9aa352e2016-09-15 18:13:52 -07001633 }
1634 // Fast path for rare no class defs case.
1635 const uint32_t num_class_defs = dex_file.NumClassDefs();
1636 if (num_class_defs == 0) {
1637 return nullptr;
1638 }
1639 const DexFile::TypeId* type_id = dex_file.FindTypeId(descriptor);
1640 if (type_id != nullptr) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001641 dex::TypeIndex type_idx = dex_file.GetIndexForTypeId(*type_id);
David Sehr9aa352e2016-09-15 18:13:52 -07001642 return dex_file.FindClassDef(type_idx);
1643 }
1644 return nullptr;
1645}
1646
Mathieu Chartier120aa282017-08-05 16:03:03 -07001647// Madvise the dex file based on the state we are moving to.
1648void OatDexFile::MadviseDexFile(const DexFile& dex_file, MadviseState state) {
Mathieu Chartier150d25d2017-08-28 09:52:55 -07001649 const bool low_ram = Runtime::Current()->GetHeap()->IsLowMemoryMode();
1650 // TODO: Also do madvise hints for non low ram devices.
1651 if (!kMadviseDexFileAccesses || !low_ram) {
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001652 return;
1653 }
Mathieu Chartier120aa282017-08-05 16:03:03 -07001654 if (state == MadviseState::kMadviseStateAtLoad) {
Mathieu Chartier150d25d2017-08-28 09:52:55 -07001655 if (low_ram) {
Mathieu Chartier4ec507d2017-08-15 15:21:40 -07001656 // Default every dex file to MADV_RANDOM when its loaded by default for low ram devices.
1657 // Other devices have enough page cache to get performance benefits from loading more pages
1658 // into the page cache.
1659 MadviseLargestPageAlignedRegion(dex_file.Begin(),
1660 dex_file.Begin() + dex_file.Size(),
1661 MADV_RANDOM);
1662 }
Mathieu Chartier120aa282017-08-05 16:03:03 -07001663 }
1664 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1665 if (oat_dex_file != nullptr) {
1666 // Should always be there.
1667 const DexLayoutSections* const sections = oat_dex_file->GetDexLayoutSections();
1668 CHECK(sections != nullptr);
1669 sections->Madvise(&dex_file, state);
1670 }
1671}
1672
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001673OatFile::OatClass::OatClass(const OatFile* oat_file,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001674 mirror::Class::Status status,
Brian Carlstromba150c32013-08-27 17:31:03 -07001675 OatClassType type,
1676 uint32_t bitmap_size,
1677 const uint32_t* bitmap_pointer,
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001678 const OatMethodOffsets* methods_pointer)
Brian Carlstromba150c32013-08-27 17:31:03 -07001679 : oat_file_(oat_file), status_(status), type_(type),
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001680 bitmap_(bitmap_pointer), methods_pointer_(methods_pointer) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001681 switch (type_) {
1682 case kOatClassAllCompiled: {
1683 CHECK_EQ(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001684 CHECK(bitmap_pointer == nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001685 CHECK(methods_pointer != nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001686 break;
1687 }
1688 case kOatClassSomeCompiled: {
1689 CHECK_NE(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001690 CHECK(bitmap_pointer != nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001691 CHECK(methods_pointer != nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001692 break;
1693 }
1694 case kOatClassNoneCompiled: {
1695 CHECK_EQ(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001696 CHECK(bitmap_pointer == nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001697 CHECK(methods_pointer_ == nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001698 break;
1699 }
1700 case kOatClassMax: {
1701 LOG(FATAL) << "Invalid OatClassType " << type_;
1702 break;
1703 }
1704 }
1705}
Brian Carlstrome24fa612011-09-29 00:53:55 -07001706
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001707uint32_t OatFile::OatClass::GetOatMethodOffsetsOffset(uint32_t method_index) const {
1708 const OatMethodOffsets* oat_method_offsets = GetOatMethodOffsets(method_index);
1709 if (oat_method_offsets == nullptr) {
1710 return 0u;
1711 }
1712 return reinterpret_cast<const uint8_t*>(oat_method_offsets) - oat_file_->Begin();
1713}
1714
1715const OatMethodOffsets* OatFile::OatClass::GetOatMethodOffsets(uint32_t method_index) const {
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001716 // 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 -07001717 if (methods_pointer_ == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001718 CHECK_EQ(kOatClassNoneCompiled, type_);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001719 return nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07001720 }
1721 size_t methods_pointer_index;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001722 if (bitmap_ == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001723 CHECK_EQ(kOatClassAllCompiled, type_);
1724 methods_pointer_index = method_index;
1725 } else {
1726 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001727 if (!BitVector::IsBitSet(bitmap_, method_index)) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001728 return nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07001729 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001730 size_t num_set_bits = BitVector::NumSetBits(bitmap_, method_index);
1731 methods_pointer_index = num_set_bits;
Brian Carlstromba150c32013-08-27 17:31:03 -07001732 }
1733 const OatMethodOffsets& oat_method_offsets = methods_pointer_[methods_pointer_index];
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001734 return &oat_method_offsets;
1735}
1736
1737const OatFile::OatMethod OatFile::OatClass::GetOatMethod(uint32_t method_index) const {
1738 const OatMethodOffsets* oat_method_offsets = GetOatMethodOffsets(method_index);
1739 if (oat_method_offsets == nullptr) {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001740 return OatMethod(nullptr, 0);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001741 }
1742 if (oat_file_->IsExecutable() ||
1743 Runtime::Current() == nullptr || // This case applies for oatdump.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001744 Runtime::Current()->IsAotCompiler()) {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001745 return OatMethod(oat_file_->Begin(), oat_method_offsets->code_offset_);
Alex Light9dcc4572014-08-14 14:16:26 -07001746 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001747 // We aren't allowed to use the compiled code. We just force it down the interpreted / jit
1748 // version.
1749 return OatMethod(oat_file_->Begin(), 0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001750}
1751
Mathieu Chartiere401d142015-04-22 13:56:20 -07001752void OatFile::OatMethod::LinkMethod(ArtMethod* method) const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001753 CHECK(method != nullptr);
Ian Rogersef7d42f2014-01-06 12:55:46 -08001754 method->SetEntryPointFromQuickCompiledCode(GetQuickCode());
Brian Carlstromae826982011-11-09 01:33:42 -08001755}
1756
Andreas Gampe7ba64962014-10-23 11:37:40 -07001757bool OatFile::IsPic() const {
Igor Murashkin46774762014-10-22 11:37:02 -07001758 return GetOatHeader().IsPic();
Andreas Gampe7ba64962014-10-23 11:37:40 -07001759 // TODO: Check against oat_patches. b/18144996
1760}
1761
Sebastien Hertz0de11332015-05-13 12:14:05 +02001762bool OatFile::IsDebuggable() const {
1763 return GetOatHeader().IsDebuggable();
1764}
1765
Andreas Gampe29d38e72016-03-23 15:31:51 +00001766CompilerFilter::Filter OatFile::GetCompilerFilter() const {
1767 return GetOatHeader().GetCompilerFilter();
Calin Juravleb077e152016-02-18 18:47:37 +00001768}
1769
Calin Juravle44e5efa2017-09-12 00:54:26 -07001770std::string OatFile::GetClassLoaderContext() const {
1771 return GetOatHeader().GetStoreValueByKey(OatHeader::kClassPathKey);
1772};
1773
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001774OatFile::OatClass OatFile::FindOatClass(const DexFile& dex_file,
1775 uint16_t class_def_idx,
1776 bool* found) {
1777 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
1778 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Mathieu Chartier1b868492016-11-16 16:22:37 -08001779 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001780 *found = false;
1781 return OatFile::OatClass::Invalid();
1782 }
1783 *found = true;
1784 return oat_dex_file->GetOatClass(class_def_idx);
1785}
1786
Mathieu Chartier1b868492016-11-16 16:22:37 -08001787void OatFile::OatDexFile::AssertAotCompiler() {
1788 CHECK(Runtime::Current()->IsAotCompiler());
1789}
1790
Brian Carlstrome24fa612011-09-29 00:53:55 -07001791} // namespace art