blob: 7a3014e2109975113efc30713e3d102d0e8d4b2d [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"
Andreas Gampea5b09a62016-11-17 15:21:22 -080046#include "dex_file_types.h"
Mathieu Chartier79c87da2017-10-10 11:54:29 -070047#include "dex_file_loader.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080048#include "elf_file.h"
Alex Light84d76052014-08-22 17:49:35 -070049#include "elf_utils.h"
Vladimir Markoaad75c62016-10-03 08:46:48 +000050#include "gc_root.h"
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +010051#include "gc/space/image_space.h"
David Srbecky1baabf02015-06-16 17:12:34 +000052#include "mem_map.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080053#include "mirror/class.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070054#include "mirror/object-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070055#include "oat.h"
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +010056#include "oat_file-inl.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070057#include "oat_file_manager.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070058#include "os.h"
Andreas Gampe22f8e5c2014-07-09 11:38:21 -070059#include "runtime.h"
Mathieu Chartier292567e2017-10-12 13:24:38 -070060#include "standard_dex_file.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
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000197 if (!ret->LoadVdex(vdex_filename, writable, low_4gb, error_msg)) {
David Brazdil7b49e6c2016-09-01 11:06:18 +0100198 return nullptr;
199 }
200
Andreas Gampe049cff02015-12-01 23:27:12 -0800201 if (!ret->Load(elf_filename,
202 oat_file_begin,
203 writable,
204 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800205 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800206 error_msg)) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800207 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800208 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800209
Andreas Gampe049cff02015-12-01 23:27:12 -0800210 if (!ret->ComputeFields(requested_base, elf_filename, error_msg)) {
211 return nullptr;
212 }
Andreas Gampe4075f832016-05-18 13:09:54 -0700213
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
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +0000237 if (!ret->LoadVdex(vdex_fd, vdex_location, writable, low_4gb, error_msg)) {
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700238 return nullptr;
239 }
240
241 if (!ret->Load(oat_fd,
242 oat_file_begin,
243 writable,
244 executable,
245 low_4gb,
246 error_msg)) {
247 return nullptr;
248 }
249
250 if (!ret->ComputeFields(requested_base, oat_location, error_msg)) {
251 return nullptr;
252 }
253
254 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) {
Nicolas Geoffray4e868fa2017-04-21 17:16:44 +0100267 vdex_ = VdexFile::Open(vdex_filename, writable, low_4gb, /* unquicken*/ false, error_msg);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100268 if (vdex_.get() == nullptr) {
269 *error_msg = StringPrintf("Failed to load vdex file '%s' %s",
270 vdex_filename.c_str(),
271 error_msg->c_str());
272 return false;
273 }
274 return true;
275}
276
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700277bool OatFileBase::LoadVdex(int vdex_fd,
278 const std::string& vdex_filename,
279 bool writable,
280 bool low_4gb,
281 std::string* error_msg) {
282 if (vdex_fd != -1) {
283 struct stat s;
284 int rc = TEMP_FAILURE_RETRY(fstat(vdex_fd, &s));
285 if (rc == -1) {
286 PLOG(WARNING) << "Failed getting length of vdex file";
287 } else {
288 vdex_ = VdexFile::Open(vdex_fd,
289 s.st_size,
290 vdex_filename,
291 writable,
292 low_4gb,
293 false /* unquicken */,
294 error_msg);
295 if (vdex_.get() == nullptr) {
296 *error_msg = "Failed opening vdex file.";
297 return false;
298 }
299 }
300 }
301 return true;
302}
303
Andreas Gampe049cff02015-12-01 23:27:12 -0800304bool OatFileBase::ComputeFields(uint8_t* requested_base,
305 const std::string& file_path,
306 std::string* error_msg) {
307 std::string symbol_error_msg;
308 begin_ = FindDynamicSymbolAddress("oatdata", &symbol_error_msg);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700309 if (begin_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800310 *error_msg = StringPrintf("Failed to find oatdata symbol in '%s' %s",
311 file_path.c_str(),
312 symbol_error_msg.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700313 return false;
314 }
315 if (requested_base != nullptr && begin_ != requested_base) {
Nicolas Geoffrayf97cf2a2016-03-09 15:36:23 +0000316 // Host can fail this check. Do not dump there to avoid polluting the output.
Andreas Gampe7ec09042016-04-01 17:20:49 -0700317 if (kIsTargetBuild && (kIsDebugBuild || VLOG_IS_ON(oat))) {
Andreas Gampe170331f2017-12-07 18:41:03 -0800318 PrintFileToLog("/proc/self/maps", android::base::LogSeverity::WARNING);
Nicolas Geoffrayf97cf2a2016-03-09 15:36:23 +0000319 }
Andreas Gampefa8429b2015-04-07 18:34:42 -0700320 *error_msg = StringPrintf("Failed to find oatdata symbol at expected address: "
Andreas Gampe049cff02015-12-01 23:27:12 -0800321 "oatdata=%p != expected=%p. See process maps in the log.",
322 begin_, requested_base);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700323 return false;
324 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800325 end_ = FindDynamicSymbolAddress("oatlastword", &symbol_error_msg);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700326 if (end_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800327 *error_msg = StringPrintf("Failed to find oatlastword symbol in '%s' %s",
328 file_path.c_str(),
329 symbol_error_msg.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700330 return false;
331 }
332 // Readjust to be non-inclusive upper bound.
333 end_ += sizeof(uint32_t);
334
Andreas Gampe049cff02015-12-01 23:27:12 -0800335 bss_begin_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbss", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700336 if (bss_begin_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800337 // No .bss section.
Andreas Gampefa8429b2015-04-07 18:34:42 -0700338 bss_end_ = nullptr;
Andreas Gampefa8429b2015-04-07 18:34:42 -0700339 } else {
Andreas Gampe049cff02015-12-01 23:27:12 -0800340 bss_end_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbsslastword", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700341 if (bss_end_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800342 *error_msg = StringPrintf("Failed to find oatbasslastword symbol in '%s'", file_path.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700343 return false;
344 }
345 // Readjust to be non-inclusive upper bound.
346 bss_end_ += sizeof(uint32_t);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100347 // Find bss methods if present.
348 bss_methods_ =
349 const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbssmethods", &symbol_error_msg));
Vladimir Markoaad75c62016-10-03 08:46:48 +0000350 // Find bss roots if present.
351 bss_roots_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbssroots", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700352 }
353
Andreas Gampe049cff02015-12-01 23:27:12 -0800354 return true;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800355}
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800356
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100357// Read an unaligned entry from the OatDexFile data in OatFile and advance the read
358// position by the number of bytes read, i.e. sizeof(T).
359// Return true on success, false if the read would go beyond the end of the OatFile.
360template <typename T>
Vladimir Marko722fa982015-10-19 18:18:27 +0100361inline static bool ReadOatDexFileData(const OatFile& oat_file,
362 /*inout*/const uint8_t** oat,
363 /*out*/T* value) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100364 DCHECK(oat != nullptr);
365 DCHECK(value != nullptr);
366 DCHECK_LE(*oat, oat_file.End());
367 if (UNLIKELY(static_cast<size_t>(oat_file.End() - *oat) < sizeof(T))) {
368 return false;
369 }
370 static_assert(std::is_trivial<T>::value, "T must be a trivial type");
371 typedef __attribute__((__aligned__(1))) T unaligned_type;
372 *value = *reinterpret_cast<const unaligned_type*>(*oat);
373 *oat += sizeof(T);
374 return true;
375}
376
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100377static inline bool MapConstantTables(const gc::space::ImageSpace* space,
378 uint8_t* address) {
379 // If MREMAP_DUP is ever merged to Linux kernel, use it to avoid the unnecessary open()/close().
380 // Note: The current approach relies on the filename still referencing the same inode.
381
382 File file(space->GetImageFilename(), O_RDONLY, /* checkUsage */ false);
383 if (!file.IsOpened()) {
384 LOG(ERROR) << "Failed to open boot image file " << space->GetImageFilename();
385 return false;
386 }
387
388 uint32_t offset = space->GetImageHeader().GetBootImageConstantTablesOffset();
389 uint32_t size = space->GetImageHeader().GetBootImageConstantTablesSize();
390 std::string error_msg;
391 std::unique_ptr<MemMap> mem_map(MemMap::MapFileAtAddress(address,
392 size,
393 PROT_READ,
394 MAP_PRIVATE,
395 file.Fd(),
396 offset,
397 /* low_4gb */ false,
398 /* reuse */ true,
399 file.GetPath().c_str(),
400 &error_msg));
401 if (mem_map == nullptr) {
402 LOG(ERROR) << "Failed to mmap boot image tables from file " << space->GetImageFilename();
403 return false;
404 }
405 return true;
406}
407
Vladimir Markof3c52b42017-11-17 17:32:12 +0000408static bool ReadIndexBssMapping(OatFile* oat_file,
409 /*inout*/const uint8_t** oat,
410 size_t dex_file_index,
411 const std::string& dex_file_location,
412 const char* tag,
413 /*out*/const IndexBssMapping** mapping,
414 std::string* error_msg) {
415 uint32_t index_bss_mapping_offset;
416 if (UNLIKELY(!ReadOatDexFileData(*oat_file, oat, &index_bss_mapping_offset))) {
417 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zd for '%s' truncated "
418 "after %s bss mapping offset",
419 oat_file->GetLocation().c_str(),
420 dex_file_index,
421 dex_file_location.c_str(),
422 tag);
423 return false;
424 }
425 const bool readable_index_bss_mapping_size =
426 index_bss_mapping_offset != 0u &&
427 index_bss_mapping_offset <= oat_file->Size() &&
428 IsAligned<alignof(IndexBssMapping)>(index_bss_mapping_offset) &&
429 oat_file->Size() - index_bss_mapping_offset >= IndexBssMapping::ComputeSize(0);
430 const IndexBssMapping* index_bss_mapping = readable_index_bss_mapping_size
431 ? reinterpret_cast<const IndexBssMapping*>(oat_file->Begin() + index_bss_mapping_offset)
432 : nullptr;
433 if (index_bss_mapping_offset != 0u &&
434 (UNLIKELY(index_bss_mapping == nullptr) ||
435 UNLIKELY(index_bss_mapping->size() == 0u) ||
436 UNLIKELY(oat_file->Size() - index_bss_mapping_offset <
437 IndexBssMapping::ComputeSize(index_bss_mapping->size())))) {
438 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with unaligned or "
439 " truncated %s bss mapping, offset %u of %zu, length %zu",
440 oat_file->GetLocation().c_str(),
441 dex_file_index,
442 dex_file_location.c_str(),
443 tag,
444 index_bss_mapping_offset,
445 oat_file->Size(),
446 index_bss_mapping != nullptr ? index_bss_mapping->size() : 0u);
447 return false;
448 }
449
450 *mapping = index_bss_mapping;
451 return true;
452}
453
454static void DCheckIndexToBssMapping(OatFile* oat_file,
455 uint32_t number_of_indexes,
456 size_t slot_size,
457 const IndexBssMapping* index_bss_mapping) {
458 if (kIsDebugBuild && index_bss_mapping != nullptr) {
459 size_t index_bits = IndexBssMappingEntry::IndexBits(number_of_indexes);
460 const IndexBssMappingEntry* prev_entry = nullptr;
461 for (const IndexBssMappingEntry& entry : *index_bss_mapping) {
462 CHECK_ALIGNED_PARAM(entry.bss_offset, slot_size);
463 // When loading a non-executable ElfOatFile, .bss symbols are not even
464 // looked up, so we cannot verify the offset against BssSize().
465 if (oat_file->IsExecutable()) {
466 CHECK_LT(entry.bss_offset, oat_file->BssSize());
467 }
468 uint32_t mask = entry.GetMask(index_bits);
469 CHECK_LE(POPCOUNT(mask) * slot_size, entry.bss_offset);
470 size_t index_mask_span = (mask != 0u) ? 32u - index_bits - CTZ(mask) : 0u;
471 CHECK_LE(index_mask_span, entry.GetIndex(index_bits));
472 if (prev_entry != nullptr) {
473 CHECK_LT(prev_entry->GetIndex(index_bits), entry.GetIndex(index_bits) - index_mask_span);
474 }
475 prev_entry = &entry;
476 }
477 CHECK_LT(prev_entry->GetIndex(index_bits), number_of_indexes);
478 }
479}
480
Andreas Gampe049cff02015-12-01 23:27:12 -0800481bool OatFileBase::Setup(const char* abs_dex_location, std::string* error_msg) {
Brian Carlstromf1b30302013-03-28 10:35:32 -0700482 if (!GetOatHeader().IsValid()) {
Andreas Gampe2bcb3b22014-12-12 15:25:14 -0800483 std::string cause = GetOatHeader().GetValidationErrorMessage();
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100484 *error_msg = StringPrintf("Invalid oat header for '%s': %s",
485 GetLocation().c_str(),
Andreas Gampe2bcb3b22014-12-12 15:25:14 -0800486 cause.c_str());
Brian Carlstromf1b30302013-03-28 10:35:32 -0700487 return false;
488 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100489 PointerSize pointer_size = GetInstructionSetPointerSize(GetOatHeader().GetInstructionSet());
490 size_t key_value_store_size =
491 (Size() >= sizeof(OatHeader)) ? GetOatHeader().GetKeyValueStoreSize() : 0u;
492 if (Size() < sizeof(OatHeader) + key_value_store_size) {
493 *error_msg = StringPrintf("In oat file '%s' found truncated OatHeader, "
494 "size = %zu < %zu + %zu",
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100495 GetLocation().c_str(),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100496 Size(),
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100497 sizeof(OatHeader),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100498 key_value_store_size);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700499 return false;
500 }
501
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100502 size_t oat_dex_files_offset = GetOatHeader().GetOatDexFilesOffset();
503 if (oat_dex_files_offset < GetOatHeader().GetHeaderSize() || oat_dex_files_offset > Size()) {
504 *error_msg = StringPrintf("In oat file '%s' found invalid oat dex files offset: "
505 "%zu is not in [%zu, %zu]",
506 GetLocation().c_str(),
507 oat_dex_files_offset,
508 GetOatHeader().GetHeaderSize(),
509 Size());
510 return false;
511 }
512 const uint8_t* oat = Begin() + oat_dex_files_offset; // Jump to the OatDexFile records.
513
514 DCHECK_GE(static_cast<size_t>(pointer_size), alignof(GcRoot<mirror::Object>));
515 if (!IsAligned<kPageSize>(bss_begin_) ||
516 !IsAlignedParam(bss_methods_, static_cast<size_t>(pointer_size)) ||
517 !IsAlignedParam(bss_roots_, static_cast<size_t>(pointer_size)) ||
Vladimir Markoaad75c62016-10-03 08:46:48 +0000518 !IsAligned<alignof(GcRoot<mirror::Object>)>(bss_end_)) {
519 *error_msg = StringPrintf("In oat file '%s' found unaligned bss symbol(s): "
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100520 "begin = %p, methods_ = %p, roots = %p, end = %p",
Vladimir Markoaad75c62016-10-03 08:46:48 +0000521 GetLocation().c_str(),
522 bss_begin_,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100523 bss_methods_,
Vladimir Markoaad75c62016-10-03 08:46:48 +0000524 bss_roots_,
525 bss_end_);
526 return false;
527 }
528
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100529 if ((bss_methods_ != nullptr && (bss_methods_ < bss_begin_ || bss_methods_ > bss_end_)) ||
530 (bss_roots_ != nullptr && (bss_roots_ < bss_begin_ || bss_roots_ > bss_end_)) ||
531 (bss_methods_ != nullptr && bss_roots_ != nullptr && bss_methods_ > bss_roots_)) {
532 *error_msg = StringPrintf("In oat file '%s' found bss symbol(s) outside .bss or unordered: "
Vladimir Marko0f3c7002017-09-07 14:15:56 +0100533 "begin = %p, methods = %p, roots = %p, end = %p",
Vladimir Markoaad75c62016-10-03 08:46:48 +0000534 GetLocation().c_str(),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000535 bss_begin_,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100536 bss_methods_,
537 bss_roots_,
Vladimir Markoaad75c62016-10-03 08:46:48 +0000538 bss_end_);
539 return false;
540 }
541
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100542 uint8_t* after_tables =
543 (bss_methods_ != nullptr) ? bss_methods_ : bss_roots_; // May be null.
544 uint8_t* boot_image_tables = (bss_begin_ == after_tables) ? nullptr : bss_begin_;
545 uint8_t* boot_image_tables_end =
546 (bss_begin_ == after_tables) ? nullptr : (after_tables != nullptr) ? after_tables : bss_end_;
547 DCHECK_EQ(boot_image_tables != nullptr, boot_image_tables_end != nullptr);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100548 uint32_t dex_file_count = GetOatHeader().GetDexFileCount();
549 oat_dex_files_storage_.reserve(dex_file_count);
550 for (size_t i = 0; i < dex_file_count; i++) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100551 uint32_t dex_file_location_size;
552 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_location_size))) {
553 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu truncated after dex file "
554 "location size",
555 GetLocation().c_str(),
556 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700557 return false;
558 }
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100559 if (UNLIKELY(dex_file_location_size == 0U)) {
560 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu with empty location name",
561 GetLocation().c_str(),
562 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700563 return false;
564 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000565 if (UNLIKELY(static_cast<size_t>(End() - oat) < dex_file_location_size)) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100566 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu with truncated dex file "
567 "location",
568 GetLocation().c_str(),
569 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700570 return false;
571 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000572 const char* dex_file_location_data = reinterpret_cast<const char*>(oat);
573 oat += dex_file_location_size;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700574
Richard Uhlere5fed032015-03-18 08:21:11 -0700575 std::string dex_file_location = ResolveRelativeEncodedDexLocation(
576 abs_dex_location,
577 std::string(dex_file_location_data, dex_file_location_size));
Brian Carlstrome24fa612011-09-29 00:53:55 -0700578
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100579 uint32_t dex_file_checksum;
580 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_checksum))) {
581 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated after "
582 "dex file checksum",
583 GetLocation().c_str(),
584 i,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700585 dex_file_location.c_str());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700586 return false;
587 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700588
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100589 uint32_t dex_file_offset;
590 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_offset))) {
591 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated "
592 "after dex file offsets",
593 GetLocation().c_str(),
594 i,
595 dex_file_location.c_str());
596 return false;
597 }
Andreas Gampee166e672017-12-19 18:59:29 +0000598 if (UNLIKELY(dex_file_offset == 0U)) {
599 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with zero dex "
600 "file offset",
601 GetLocation().c_str(),
602 i,
603 dex_file_location.c_str());
604 return false;
605 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100606 if (UNLIKELY(dex_file_offset > DexSize())) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100607 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
608 "offset %u > %zu",
609 GetLocation().c_str(),
610 i,
611 dex_file_location.c_str(),
612 dex_file_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100613 DexSize());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700614 return false;
615 }
Andreas Gampee166e672017-12-19 18:59:29 +0000616 if (UNLIKELY(DexSize() - dex_file_offset < sizeof(DexFile::Header))) {
617 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
618 "offset %u of %zu but the size of dex file header is %zu",
619 GetLocation().c_str(),
620 i,
621 dex_file_location.c_str(),
622 dex_file_offset,
623 DexSize(),
624 sizeof(DexFile::Header));
625 return false;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000626 }
Brian Carlstrom89521892011-12-07 22:05:07 -0800627
Andreas Gampee166e672017-12-19 18:59:29 +0000628 const uint8_t* dex_file_pointer = DexBegin() + dex_file_offset;
629
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700630 const bool valid_magic = DexFileLoader::IsMagicValid(dex_file_pointer);
Mathieu Chartier7b074bf2017-09-25 16:22:36 -0700631 if (UNLIKELY(!valid_magic)) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100632 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with invalid "
633 "dex file magic '%s'",
634 GetLocation().c_str(),
635 i,
636 dex_file_location.c_str(),
637 dex_file_pointer);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700638 return false;
639 }
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700640 if (UNLIKELY(!DexFileLoader::IsVersionAndMagicValid(dex_file_pointer))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100641 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with invalid "
642 "dex file version '%s'",
643 GetLocation().c_str(),
644 i,
645 dex_file_location.c_str(),
646 dex_file_pointer);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700647 return false;
648 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800649 const DexFile::Header* header = reinterpret_cast<const DexFile::Header*>(dex_file_pointer);
Andreas Gampee166e672017-12-19 18:59:29 +0000650 if (DexSize() - dex_file_offset < header->file_size_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000651 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
652 "offset %u and size %u truncated at %zu",
653 GetLocation().c_str(),
654 i,
655 dex_file_location.c_str(),
656 dex_file_offset,
657 header->file_size_,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100658 DexSize());
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000659 return false;
660 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300661
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000662 uint32_t class_offsets_offset;
663 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &class_offsets_offset))) {
664 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated "
665 "after class offsets offset",
666 GetLocation().c_str(),
667 i,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300668 dex_file_location.c_str());
669 return false;
670 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000671 if (UNLIKELY(class_offsets_offset > Size()) ||
672 UNLIKELY((Size() - class_offsets_offset) / sizeof(uint32_t) < header->class_defs_size_)) {
673 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with truncated "
674 "class offsets, offset %u of %zu, class defs %u",
675 GetLocation().c_str(),
676 i,
677 dex_file_location.c_str(),
678 class_offsets_offset,
679 Size(),
680 header->class_defs_size_);
681 return false;
682 }
683 if (UNLIKELY(!IsAligned<alignof(uint32_t)>(class_offsets_offset))) {
684 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with unaligned "
685 "class offsets, offset %u",
686 GetLocation().c_str(),
687 i,
688 dex_file_location.c_str(),
689 class_offsets_offset);
690 return false;
691 }
692 const uint32_t* class_offsets_pointer =
693 reinterpret_cast<const uint32_t*>(Begin() + class_offsets_offset);
694
695 uint32_t lookup_table_offset;
696 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &lookup_table_offset))) {
697 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zd for '%s' truncated "
698 "after lookup table offset",
699 GetLocation().c_str(),
700 i,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300701 dex_file_location.c_str());
702 return false;
703 }
704 const uint8_t* lookup_table_data = lookup_table_offset != 0u
705 ? Begin() + lookup_table_offset
706 : nullptr;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000707 if (lookup_table_offset != 0u &&
708 (UNLIKELY(lookup_table_offset > Size()) ||
709 UNLIKELY(Size() - lookup_table_offset <
710 TypeLookupTable::RawDataLength(header->class_defs_size_)))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100711 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with truncated "
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000712 "type lookup table, offset %u of %zu, class defs %u",
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100713 GetLocation().c_str(),
714 i,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000715 dex_file_location.c_str(),
716 lookup_table_offset,
717 Size(),
718 header->class_defs_size_);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700719 return false;
720 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700721
Mathieu Chartier120aa282017-08-05 16:03:03 -0700722 uint32_t dex_layout_sections_offset;
723 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_layout_sections_offset))) {
724 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zd for '%s' truncated "
725 "after dex layout sections offset",
726 GetLocation().c_str(),
727 i,
728 dex_file_location.c_str());
729 return false;
730 }
731 const DexLayoutSections* const dex_layout_sections = dex_layout_sections_offset != 0
732 ? reinterpret_cast<const DexLayoutSections*>(Begin() + dex_layout_sections_offset)
733 : nullptr;
734
Vladimir Markof3c52b42017-11-17 17:32:12 +0000735 const IndexBssMapping* method_bss_mapping;
736 const IndexBssMapping* type_bss_mapping;
737 const IndexBssMapping* string_bss_mapping;
738 if (!ReadIndexBssMapping(
739 this, &oat, i, dex_file_location, "method", &method_bss_mapping, error_msg) ||
740 !ReadIndexBssMapping(
741 this, &oat, i, dex_file_location, "type", &type_bss_mapping, error_msg) ||
742 !ReadIndexBssMapping(
743 this, &oat, i, dex_file_location, "string", &string_bss_mapping, error_msg)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100744 return false;
745 }
Vladimir Markof3c52b42017-11-17 17:32:12 +0000746 DCheckIndexToBssMapping(
747 this, header->method_ids_size_, static_cast<size_t>(pointer_size), method_bss_mapping);
748 DCheckIndexToBssMapping(
749 this, header->type_ids_size_, sizeof(GcRoot<mirror::Class>), type_bss_mapping);
750 DCheckIndexToBssMapping(
751 this, header->string_ids_size_, sizeof(GcRoot<mirror::String>), string_bss_mapping);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100752
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700753 std::string canonical_location =
754 DexFileLoader::GetDexCanonicalLocation(dex_file_location.c_str());
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100755
756 // Create the OatDexFile and add it to the owning container.
Vladimir Marko539690a2014-06-05 18:36:42 +0100757 OatDexFile* oat_dex_file = new OatDexFile(this,
758 dex_file_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100759 canonical_location,
Vladimir Marko539690a2014-06-05 18:36:42 +0100760 dex_file_checksum,
761 dex_file_pointer,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300762 lookup_table_data,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100763 method_bss_mapping,
Vladimir Markof3c52b42017-11-17 17:32:12 +0000764 type_bss_mapping,
765 string_bss_mapping,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000766 class_offsets_pointer,
Mathieu Chartier120aa282017-08-05 16:03:03 -0700767 dex_layout_sections);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100768 oat_dex_files_storage_.push_back(oat_dex_file);
769
770 // Add the location and canonical location (if different) to the oat_dex_files_ table.
Vladimir Marko3f5838d2014-08-07 18:07:18 +0100771 StringPiece key(oat_dex_file->GetDexFileLocation());
Vladimir Marko539690a2014-06-05 18:36:42 +0100772 oat_dex_files_.Put(key, oat_dex_file);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100773 if (canonical_location != dex_file_location) {
774 StringPiece canonical_key(oat_dex_file->GetCanonicalDexFileLocation());
775 oat_dex_files_.Put(canonical_key, oat_dex_file);
776 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700777 }
Vladimir Marko09d09432015-09-08 13:47:48 +0100778
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100779 if (boot_image_tables != nullptr) {
Vladimir Marko667585a2017-09-29 10:42:31 +0100780 Runtime* runtime = Runtime::Current();
781 if (UNLIKELY(runtime == nullptr)) {
782 // This must be oatdump without boot image. Make sure the .bss is inaccessible.
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700783 CheckedCall(mprotect, "protect bss", const_cast<uint8_t*>(BssBegin()), BssSize(), PROT_NONE);
Vladimir Marko667585a2017-09-29 10:42:31 +0100784 } else {
785 // Map boot image tables into the .bss. The reserved size must match size of the tables.
786 size_t reserved_size = static_cast<size_t>(boot_image_tables_end - boot_image_tables);
787 size_t tables_size = 0u;
788 for (gc::space::ImageSpace* space : runtime->GetHeap()->GetBootImageSpaces()) {
789 tables_size += space->GetImageHeader().GetBootImageConstantTablesSize();
790 DCHECK_ALIGNED(tables_size, kPageSize);
791 }
792 if (tables_size != reserved_size) {
793 *error_msg = StringPrintf("In oat file '%s' found unexpected boot image table sizes, "
794 " %zu bytes, should be %zu.",
795 GetLocation().c_str(),
796 reserved_size,
797 tables_size);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100798 return false;
799 }
Vladimir Marko667585a2017-09-29 10:42:31 +0100800 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
801 uint32_t current_tables_size = space->GetImageHeader().GetBootImageConstantTablesSize();
802 if (current_tables_size != 0u && !MapConstantTables(space, boot_image_tables)) {
803 return false;
804 }
805 boot_image_tables += current_tables_size;
806 }
807 DCHECK(boot_image_tables == boot_image_tables_end);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100808 }
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100809 }
Brian Carlstromf1b30302013-03-28 10:35:32 -0700810 return true;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700811}
812
Andreas Gampe049cff02015-12-01 23:27:12 -0800813////////////////////////
814// OatFile via dlopen //
815////////////////////////
816
Andreas Gampe049cff02015-12-01 23:27:12 -0800817class DlOpenOatFile FINAL : public OatFileBase {
818 public:
819 DlOpenOatFile(const std::string& filename, bool executable)
820 : OatFileBase(filename, executable),
821 dlopen_handle_(nullptr),
Richard Uhlera206c742016-05-24 15:04:22 -0700822 shared_objects_before_(0) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800823 }
824
825 ~DlOpenOatFile() {
826 if (dlopen_handle_ != nullptr) {
Richard Uhlera206c742016-05-24 15:04:22 -0700827 if (!kIsTargetBuild) {
828 MutexLock mu(Thread::Current(), *Locks::host_dlopen_handles_lock_);
829 host_dlopen_handles_.erase(dlopen_handle_);
Mathieu Chartierc7d3f4b2016-06-01 10:48:19 -0700830 dlclose(dlopen_handle_);
831 } else {
832 dlclose(dlopen_handle_);
Richard Uhlera206c742016-05-24 15:04:22 -0700833 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800834 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800835 }
836
837 protected:
838 const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
839 std::string* error_msg) const OVERRIDE {
840 const uint8_t* ptr =
841 reinterpret_cast<const uint8_t*>(dlsym(dlopen_handle_, symbol_name.c_str()));
842 if (ptr == nullptr) {
843 *error_msg = dlerror();
844 }
845 return ptr;
846 }
847
Andreas Gampe4075f832016-05-18 13:09:54 -0700848 void PreLoad() OVERRIDE;
849
Andreas Gampe049cff02015-12-01 23:27:12 -0800850 bool Load(const std::string& elf_filename,
851 uint8_t* oat_file_begin,
852 bool writable,
853 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800854 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800855 std::string* error_msg) OVERRIDE;
856
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700857 bool Load(int, uint8_t*, bool, bool, bool, std::string*) {
858 return false;
859 }
860
Andreas Gampe049cff02015-12-01 23:27:12 -0800861 // Ask the linker where it mmaped the file and notify our mmap wrapper of the regions.
862 void PreSetup(const std::string& elf_filename) OVERRIDE;
863
864 private:
865 bool Dlopen(const std::string& elf_filename,
866 uint8_t* oat_file_begin,
867 std::string* error_msg);
868
Richard Uhlera206c742016-05-24 15:04:22 -0700869 // On the host, if the same library is loaded again with dlopen the same
870 // file handle is returned. This differs from the behavior of dlopen on the
871 // target, where dlopen reloads the library at a different address every
872 // time you load it. The runtime relies on the target behavior to ensure
873 // each instance of the loaded library has a unique dex cache. To avoid
874 // problems, we fall back to our own linker in the case when the same
875 // library is opened multiple times on host. dlopen_handles_ is used to
876 // detect that case.
877 // Guarded by host_dlopen_handles_lock_;
878 static std::unordered_set<void*> host_dlopen_handles_;
879
Andreas Gampe049cff02015-12-01 23:27:12 -0800880 // dlopen handle during runtime.
881 void* dlopen_handle_; // TODO: Unique_ptr with custom deleter.
882
883 // Dummy memory map objects corresponding to the regions mapped by dlopen.
884 std::vector<std::unique_ptr<MemMap>> dlopen_mmaps_;
885
Andreas Gampe4075f832016-05-18 13:09:54 -0700886 // The number of shared objects the linker told us about before loading. Used to
887 // (optimistically) optimize the PreSetup stage (see comment there).
888 size_t shared_objects_before_;
889
Andreas Gampe049cff02015-12-01 23:27:12 -0800890 DISALLOW_COPY_AND_ASSIGN(DlOpenOatFile);
891};
892
Richard Uhlera206c742016-05-24 15:04:22 -0700893std::unordered_set<void*> DlOpenOatFile::host_dlopen_handles_;
894
Andreas Gampe4075f832016-05-18 13:09:54 -0700895void DlOpenOatFile::PreLoad() {
896#ifdef __APPLE__
Andreas Gampe39004a62016-05-18 21:27:00 -0700897 UNUSED(shared_objects_before_);
Andreas Gampe4075f832016-05-18 13:09:54 -0700898 LOG(FATAL) << "Should not reach here.";
899 UNREACHABLE();
900#else
901 // Count the entries in dl_iterate_phdr we get at this point in time.
902 struct dl_iterate_context {
903 static int callback(struct dl_phdr_info *info ATTRIBUTE_UNUSED,
904 size_t size ATTRIBUTE_UNUSED,
905 void *data) {
906 reinterpret_cast<dl_iterate_context*>(data)->count++;
907 return 0; // Continue iteration.
908 }
909 size_t count = 0;
910 } context;
911
912 dl_iterate_phdr(dl_iterate_context::callback, &context);
913 shared_objects_before_ = context.count;
914#endif
915}
916
Andreas Gampe049cff02015-12-01 23:27:12 -0800917bool DlOpenOatFile::Load(const std::string& elf_filename,
918 uint8_t* oat_file_begin,
919 bool writable,
920 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800921 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800922 std::string* error_msg) {
923 // Use dlopen only when flagged to do so, and when it's OK to load things executable.
924 // TODO: Also try when not executable? The issue here could be re-mapping as writable (as
925 // !executable is a sign that we may want to patch), which may not be allowed for
926 // various reasons.
927 if (!kUseDlopen) {
928 *error_msg = "DlOpen is disabled.";
929 return false;
930 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800931 if (low_4gb) {
932 *error_msg = "DlOpen does not support low 4gb loading.";
933 return false;
934 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800935 if (writable) {
936 *error_msg = "DlOpen does not support writable loading.";
937 return false;
938 }
939 if (!executable) {
940 *error_msg = "DlOpen does not support non-executable loading.";
941 return false;
942 }
943
944 // dlopen always returns the same library if it is already opened on the host. For this reason
945 // we only use dlopen if we are the target or we do not already have the dex file opened. Having
946 // the same library loaded multiple times at different addresses is required for class unloading
947 // and for having dex caches arrays in the .bss section.
948 if (!kIsTargetBuild) {
949 if (!kUseDlopenOnHost) {
950 *error_msg = "DlOpen disabled for host.";
951 return false;
952 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800953 }
954
955 bool success = Dlopen(elf_filename, oat_file_begin, error_msg);
956 DCHECK(dlopen_handle_ != nullptr || !success);
957
958 return success;
959}
960
961bool DlOpenOatFile::Dlopen(const std::string& elf_filename,
962 uint8_t* oat_file_begin,
963 std::string* error_msg) {
964#ifdef __APPLE__
965 // The dl_iterate_phdr syscall is missing. There is similar API on OSX,
966 // but let's fallback to the custom loading code for the time being.
967 UNUSED(elf_filename, oat_file_begin);
968 *error_msg = "Dlopen unsupported on Mac.";
969 return false;
970#else
971 {
972 UniqueCPtr<char> absolute_path(realpath(elf_filename.c_str(), nullptr));
973 if (absolute_path == nullptr) {
974 *error_msg = StringPrintf("Failed to find absolute path for '%s'", elf_filename.c_str());
975 return false;
976 }
Bilyan Borisovbb661c02016-04-04 16:27:32 +0100977#ifdef ART_TARGET_ANDROID
Anton Kirilov3a2e78e2017-01-06 13:33:42 +0000978 android_dlextinfo extinfo = {};
Andreas Gampe049cff02015-12-01 23:27:12 -0800979 extinfo.flags = ANDROID_DLEXT_FORCE_LOAD | // Force-load, don't reuse handle
980 // (open oat files multiple
981 // times).
982 ANDROID_DLEXT_FORCE_FIXED_VADDR; // Take a non-zero vaddr as absolute
983 // (non-pic boot image).
Andreas Gampe226b91e2015-12-02 10:29:33 -0800984 if (oat_file_begin != nullptr) { //
985 extinfo.flags |= ANDROID_DLEXT_LOAD_AT_FIXED_ADDRESS; // Use the requested addr if
986 extinfo.reserved_addr = oat_file_begin; // vaddr = 0.
987 } // (pic boot image).
Andreas Gampe049cff02015-12-01 23:27:12 -0800988 dlopen_handle_ = android_dlopen_ext(absolute_path.get(), RTLD_NOW, &extinfo);
989#else
Andreas Gampe049cff02015-12-01 23:27:12 -0800990 UNUSED(oat_file_begin);
Julien Duraj1af0c4f2016-11-16 14:05:48 +0000991 static_assert(!kIsTargetBuild || kIsTargetLinux, "host_dlopen_handles_ will leak handles");
Mathieu Chartierc7d3f4b2016-06-01 10:48:19 -0700992 MutexLock mu(Thread::Current(), *Locks::host_dlopen_handles_lock_);
Richard Uhlera206c742016-05-24 15:04:22 -0700993 dlopen_handle_ = dlopen(absolute_path.get(), RTLD_NOW);
994 if (dlopen_handle_ != nullptr) {
Richard Uhlera206c742016-05-24 15:04:22 -0700995 if (!host_dlopen_handles_.insert(dlopen_handle_).second) {
996 dlclose(dlopen_handle_);
997 dlopen_handle_ = nullptr;
998 *error_msg = StringPrintf("host dlopen re-opened '%s'", elf_filename.c_str());
999 return false;
1000 }
1001 }
Bilyan Borisovbb661c02016-04-04 16:27:32 +01001002#endif // ART_TARGET_ANDROID
Andreas Gampe049cff02015-12-01 23:27:12 -08001003 }
1004 if (dlopen_handle_ == nullptr) {
1005 *error_msg = StringPrintf("Failed to dlopen '%s': %s", elf_filename.c_str(), dlerror());
1006 return false;
1007 }
1008 return true;
1009#endif
1010}
1011
1012void DlOpenOatFile::PreSetup(const std::string& elf_filename) {
Andreas Gampe74f07b52015-12-02 11:53:26 -08001013#ifdef __APPLE__
1014 UNUSED(elf_filename);
1015 LOG(FATAL) << "Should not reach here.";
1016 UNREACHABLE();
1017#else
Andreas Gampe049cff02015-12-01 23:27:12 -08001018 struct dl_iterate_context {
1019 static int callback(struct dl_phdr_info *info, size_t /* size */, void *data) {
1020 auto* context = reinterpret_cast<dl_iterate_context*>(data);
Andreas Gampe4075f832016-05-18 13:09:54 -07001021 context->shared_objects_seen++;
1022 if (context->shared_objects_seen < context->shared_objects_before) {
1023 // We haven't been called yet for anything we haven't seen before. Just continue.
1024 // Note: this is aggressively optimistic. If another thread was unloading a library,
1025 // we may miss out here. However, this does not happen often in practice.
1026 return 0;
1027 }
1028
Andreas Gampe049cff02015-12-01 23:27:12 -08001029 // See whether this callback corresponds to the file which we have just loaded.
1030 bool contains_begin = false;
1031 for (int i = 0; i < info->dlpi_phnum; i++) {
1032 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
1033 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
1034 info->dlpi_phdr[i].p_vaddr);
1035 size_t memsz = info->dlpi_phdr[i].p_memsz;
1036 if (vaddr <= context->begin_ && context->begin_ < vaddr + memsz) {
1037 contains_begin = true;
1038 break;
1039 }
1040 }
1041 }
1042 // Add dummy mmaps for this file.
1043 if (contains_begin) {
1044 for (int i = 0; i < info->dlpi_phnum; i++) {
1045 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
1046 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
1047 info->dlpi_phdr[i].p_vaddr);
1048 size_t memsz = info->dlpi_phdr[i].p_memsz;
1049 MemMap* mmap = MemMap::MapDummy(info->dlpi_name, vaddr, memsz);
1050 context->dlopen_mmaps_->push_back(std::unique_ptr<MemMap>(mmap));
1051 }
1052 }
1053 return 1; // Stop iteration and return 1 from dl_iterate_phdr.
1054 }
1055 return 0; // Continue iteration and return 0 from dl_iterate_phdr when finished.
1056 }
1057 const uint8_t* const begin_;
1058 std::vector<std::unique_ptr<MemMap>>* const dlopen_mmaps_;
Andreas Gampe4075f832016-05-18 13:09:54 -07001059 const size_t shared_objects_before;
1060 size_t shared_objects_seen;
1061 };
1062 dl_iterate_context context = { Begin(), &dlopen_mmaps_, shared_objects_before_, 0};
Andreas Gampe049cff02015-12-01 23:27:12 -08001063
1064 if (dl_iterate_phdr(dl_iterate_context::callback, &context) == 0) {
Andreas Gampe4075f832016-05-18 13:09:54 -07001065 // Hm. Maybe our optimization went wrong. Try another time with shared_objects_before == 0
1066 // before giving up. This should be unusual.
1067 VLOG(oat) << "Need a second run in PreSetup, didn't find with shared_objects_before="
1068 << shared_objects_before_;
1069 dl_iterate_context context0 = { Begin(), &dlopen_mmaps_, 0, 0};
1070 if (dl_iterate_phdr(dl_iterate_context::callback, &context0) == 0) {
1071 // OK, give up and print an error.
Andreas Gampe170331f2017-12-07 18:41:03 -08001072 PrintFileToLog("/proc/self/maps", android::base::LogSeverity::WARNING);
Andreas Gampe4075f832016-05-18 13:09:54 -07001073 LOG(ERROR) << "File " << elf_filename << " loaded with dlopen but cannot find its mmaps.";
1074 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001075 }
Andreas Gampe74f07b52015-12-02 11:53:26 -08001076#endif
Andreas Gampe049cff02015-12-01 23:27:12 -08001077}
1078
1079////////////////////////////////////////////////
1080// OatFile via our own ElfFile implementation //
1081////////////////////////////////////////////////
1082
1083class ElfOatFile FINAL : public OatFileBase {
1084 public:
1085 ElfOatFile(const std::string& filename, bool executable) : OatFileBase(filename, executable) {}
1086
1087 static ElfOatFile* OpenElfFile(File* file,
1088 const std::string& location,
1089 uint8_t* requested_base,
1090 uint8_t* oat_file_begin, // Override base if not null
1091 bool writable,
1092 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001093 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001094 const char* abs_dex_location,
1095 std::string* error_msg);
1096
1097 bool InitializeFromElfFile(ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +01001098 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001099 const char* abs_dex_location,
1100 std::string* error_msg);
1101
1102 protected:
1103 const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
1104 std::string* error_msg) const OVERRIDE {
1105 const uint8_t* ptr = elf_file_->FindDynamicSymbolAddress(symbol_name);
1106 if (ptr == nullptr) {
1107 *error_msg = "(Internal implementation could not find symbol)";
1108 }
1109 return ptr;
1110 }
1111
Andreas Gampe4075f832016-05-18 13:09:54 -07001112 void PreLoad() OVERRIDE {
1113 }
1114
Andreas Gampe049cff02015-12-01 23:27:12 -08001115 bool Load(const std::string& elf_filename,
1116 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1117 bool writable,
1118 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001119 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001120 std::string* error_msg) OVERRIDE;
1121
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001122 bool Load(int oat_fd,
1123 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1124 bool writable,
1125 bool executable,
1126 bool low_4gb,
1127 std::string* error_msg) OVERRIDE;
1128
Andreas Gampe049cff02015-12-01 23:27:12 -08001129 void PreSetup(const std::string& elf_filename ATTRIBUTE_UNUSED) OVERRIDE {
1130 }
1131
1132 private:
1133 bool ElfFileOpen(File* file,
1134 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1135 bool writable,
1136 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001137 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001138 std::string* error_msg);
1139
1140 private:
1141 // Backing memory map for oat file during cross compilation.
1142 std::unique_ptr<ElfFile> elf_file_;
1143
1144 DISALLOW_COPY_AND_ASSIGN(ElfOatFile);
1145};
1146
1147ElfOatFile* ElfOatFile::OpenElfFile(File* file,
1148 const std::string& location,
1149 uint8_t* requested_base,
1150 uint8_t* oat_file_begin, // Override base if not null
1151 bool writable,
1152 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001153 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001154 const char* abs_dex_location,
1155 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001156 ScopedTrace trace("Open elf file " + location);
Andreas Gampe049cff02015-12-01 23:27:12 -08001157 std::unique_ptr<ElfOatFile> oat_file(new ElfOatFile(location, executable));
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001158 bool success = oat_file->ElfFileOpen(file,
1159 oat_file_begin,
1160 writable,
1161 low_4gb,
1162 executable,
1163 error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -08001164 if (!success) {
1165 CHECK(!error_msg->empty());
1166 return nullptr;
1167 }
1168
1169 // Complete the setup.
1170 if (!oat_file->ComputeFields(requested_base, file->GetPath(), error_msg)) {
1171 return nullptr;
1172 }
1173
1174 if (!oat_file->Setup(abs_dex_location, error_msg)) {
1175 return nullptr;
1176 }
1177
1178 return oat_file.release();
1179}
1180
1181bool ElfOatFile::InitializeFromElfFile(ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +01001182 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001183 const char* abs_dex_location,
1184 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001185 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -08001186 if (IsExecutable()) {
1187 *error_msg = "Cannot initialize from elf file in executable mode.";
1188 return false;
1189 }
1190 elf_file_.reset(elf_file);
David Brazdilc93b3be2016-09-12 18:49:58 +01001191 SetVdex(vdex_file);
Andreas Gampe049cff02015-12-01 23:27:12 -08001192 uint64_t offset, size;
1193 bool has_section = elf_file->GetSectionOffsetAndSize(".rodata", &offset, &size);
1194 CHECK(has_section);
1195 SetBegin(elf_file->Begin() + offset);
1196 SetEnd(elf_file->Begin() + size + offset);
1197 // Ignore the optional .bss section when opening non-executable.
1198 return Setup(abs_dex_location, error_msg);
1199}
1200
1201bool ElfOatFile::Load(const std::string& elf_filename,
1202 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1203 bool writable,
1204 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001205 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001206 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001207 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -08001208 std::unique_ptr<File> file(OS::OpenFileForReading(elf_filename.c_str()));
1209 if (file == nullptr) {
1210 *error_msg = StringPrintf("Failed to open oat filename for reading: %s", strerror(errno));
1211 return false;
1212 }
1213 return ElfOatFile::ElfFileOpen(file.get(),
1214 oat_file_begin,
1215 writable,
1216 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001217 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001218 error_msg);
1219}
1220
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001221bool ElfOatFile::Load(int oat_fd,
1222 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1223 bool writable,
1224 bool executable,
1225 bool low_4gb,
1226 std::string* error_msg) {
1227 ScopedTrace trace(__PRETTY_FUNCTION__);
1228 if (oat_fd != -1) {
1229 std::unique_ptr<File> file = std::make_unique<File>(oat_fd, false);
1230 file->DisableAutoClose();
1231 if (file == nullptr) {
1232 *error_msg = StringPrintf("Failed to open oat filename for reading: %s",
1233 strerror(errno));
1234 return false;
1235 }
1236 return ElfOatFile::ElfFileOpen(file.get(),
1237 oat_file_begin,
1238 writable,
1239 executable,
1240 low_4gb,
1241 error_msg);
1242 }
1243 return false;
1244}
1245
Andreas Gampe049cff02015-12-01 23:27:12 -08001246bool ElfOatFile::ElfFileOpen(File* file,
1247 uint8_t* oat_file_begin,
1248 bool writable,
1249 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001250 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001251 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001252 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -08001253 // TODO: rename requested_base to oat_data_begin
1254 elf_file_.reset(ElfFile::Open(file,
1255 writable,
1256 /*program_header_only*/true,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001257 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001258 error_msg,
1259 oat_file_begin));
1260 if (elf_file_ == nullptr) {
1261 DCHECK(!error_msg->empty());
1262 return false;
1263 }
Brian Carlstromf5b0f2c2016-10-14 01:04:26 -07001264 bool loaded = elf_file_->Load(file, executable, low_4gb, error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -08001265 DCHECK(loaded || !error_msg->empty());
1266 return loaded;
1267}
1268
1269//////////////////////////
1270// General OatFile code //
1271//////////////////////////
1272
1273std::string OatFile::ResolveRelativeEncodedDexLocation(
1274 const char* abs_dex_location, const std::string& rel_dex_location) {
1275 if (abs_dex_location != nullptr && rel_dex_location[0] != '/') {
1276 // Strip :classes<N>.dex used for secondary multidex files.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001277 std::string base = DexFileLoader::GetBaseLocation(rel_dex_location);
1278 std::string multidex_suffix = DexFileLoader::GetMultiDexSuffix(rel_dex_location);
Andreas Gampe049cff02015-12-01 23:27:12 -08001279
1280 // Check if the base is a suffix of the provided abs_dex_location.
1281 std::string target_suffix = "/" + base;
1282 std::string abs_location(abs_dex_location);
1283 if (abs_location.size() > target_suffix.size()) {
1284 size_t pos = abs_location.size() - target_suffix.size();
1285 if (abs_location.compare(pos, std::string::npos, target_suffix) == 0) {
1286 return abs_location + multidex_suffix;
1287 }
1288 }
1289 }
1290 return rel_dex_location;
1291}
1292
1293static void CheckLocation(const std::string& location) {
1294 CHECK(!location.empty());
1295}
1296
1297OatFile* OatFile::OpenWithElfFile(ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +01001298 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001299 const std::string& location,
1300 const char* abs_dex_location,
1301 std::string* error_msg) {
1302 std::unique_ptr<ElfOatFile> oat_file(new ElfOatFile(location, false /* executable */));
David Brazdilc93b3be2016-09-12 18:49:58 +01001303 return oat_file->InitializeFromElfFile(elf_file, vdex_file, abs_dex_location, error_msg)
Andreas Gampe049cff02015-12-01 23:27:12 -08001304 ? oat_file.release()
1305 : nullptr;
1306}
1307
David Brazdil7b49e6c2016-09-01 11:06:18 +01001308OatFile* OatFile::Open(const std::string& oat_filename,
1309 const std::string& oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001310 uint8_t* requested_base,
1311 uint8_t* oat_file_begin,
1312 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001313 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001314 const char* abs_dex_location,
1315 std::string* error_msg) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001316 ScopedTrace trace("Open oat file " + oat_location);
1317 CHECK(!oat_filename.empty()) << oat_location;
1318 CheckLocation(oat_location);
Andreas Gampe54315c72016-05-18 21:10:42 -07001319
Calin Juravle367b9d82017-05-15 18:18:39 -07001320 std::string vdex_filename = GetVdexFilename(oat_filename);
David Brazdil7b49e6c2016-09-01 11:06:18 +01001321
1322 // Check that the files even exist, fast-fail.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001323 if (!OS::FileExists(vdex_filename.c_str())) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001324 *error_msg = StringPrintf("File %s does not exist.", vdex_filename.c_str());
1325 return nullptr;
1326 } else if (!OS::FileExists(oat_filename.c_str())) {
1327 *error_msg = StringPrintf("File %s does not exist.", oat_filename.c_str());
Andreas Gampe54315c72016-05-18 21:10:42 -07001328 return nullptr;
1329 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001330
1331 // Try dlopen first, as it is required for native debuggability. This will fail fast if dlopen is
1332 // disabled.
David Brazdil7b49e6c2016-09-01 11:06:18 +01001333 OatFile* with_dlopen = OatFileBase::OpenOatFile<DlOpenOatFile>(vdex_filename,
1334 oat_filename,
1335 oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001336 requested_base,
1337 oat_file_begin,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001338 false /* writable */,
Andreas Gampe049cff02015-12-01 23:27:12 -08001339 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001340 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001341 abs_dex_location,
1342 error_msg);
1343 if (with_dlopen != nullptr) {
1344 return with_dlopen;
1345 }
1346 if (kPrintDlOpenErrorMessage) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001347 LOG(ERROR) << "Failed to dlopen: " << oat_filename << " with error " << *error_msg;
Andreas Gampe049cff02015-12-01 23:27:12 -08001348 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001349 // If we aren't trying to execute, we just use our own ElfFile loader for a couple reasons:
1350 //
1351 // On target, dlopen may fail when compiling due to selinux restrictions on installd.
1352 //
1353 // We use our own ELF loader for Quick to deal with legacy apps that
1354 // open a generated dex file by name, remove the file, then open
1355 // another generated dex file with the same name. http://b/10614658
1356 //
1357 // On host, dlopen is expected to fail when cross compiling, so fall back to OpenElfFile.
1358 //
1359 //
1360 // Another independent reason is the absolute placement of boot.oat. dlopen on the host usually
1361 // 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 +01001362 OatFile* with_internal = OatFileBase::OpenOatFile<ElfOatFile>(vdex_filename,
1363 oat_filename,
1364 oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001365 requested_base,
1366 oat_file_begin,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001367 false /* writable */,
Andreas Gampe049cff02015-12-01 23:27:12 -08001368 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001369 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001370 abs_dex_location,
1371 error_msg);
1372 return with_internal;
1373}
1374
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001375OatFile* OatFile::Open(int vdex_fd,
1376 int oat_fd,
1377 const std::string& oat_location,
1378 uint8_t* requested_base,
1379 uint8_t* oat_file_begin,
1380 bool executable,
1381 bool low_4gb,
1382 const char* abs_dex_location,
1383 std::string* error_msg) {
1384 CHECK(!oat_location.empty()) << oat_location;
1385
1386 std::string vdex_location = GetVdexFilename(oat_location);
1387
1388 OatFile* with_internal = OatFileBase::OpenOatFile<ElfOatFile>(vdex_fd,
1389 oat_fd,
1390 vdex_location,
1391 oat_location,
1392 requested_base,
1393 oat_file_begin,
1394 false /* writable */,
1395 executable,
1396 low_4gb,
1397 abs_dex_location,
1398 error_msg);
1399 return with_internal;
1400}
1401
Andreas Gampe049cff02015-12-01 23:27:12 -08001402OatFile* OatFile::OpenWritable(File* file,
1403 const std::string& location,
1404 const char* abs_dex_location,
1405 std::string* error_msg) {
1406 CheckLocation(location);
1407 return ElfOatFile::OpenElfFile(file,
1408 location,
1409 nullptr,
1410 nullptr,
1411 true,
1412 false,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001413 /*low_4gb*/false,
Andreas Gampe049cff02015-12-01 23:27:12 -08001414 abs_dex_location,
1415 error_msg);
1416}
1417
1418OatFile* OatFile::OpenReadable(File* file,
1419 const std::string& location,
1420 const char* abs_dex_location,
1421 std::string* error_msg) {
1422 CheckLocation(location);
1423 return ElfOatFile::OpenElfFile(file,
1424 location,
1425 nullptr,
1426 nullptr,
1427 false,
1428 false,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001429 /*low_4gb*/false,
Andreas Gampe049cff02015-12-01 23:27:12 -08001430 abs_dex_location,
1431 error_msg);
1432}
1433
1434OatFile::OatFile(const std::string& location, bool is_executable)
1435 : location_(location),
David Brazdil7b49e6c2016-09-01 11:06:18 +01001436 vdex_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001437 begin_(nullptr),
1438 end_(nullptr),
1439 bss_begin_(nullptr),
1440 bss_end_(nullptr),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001441 bss_methods_(nullptr),
Vladimir Markoaad75c62016-10-03 08:46:48 +00001442 bss_roots_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001443 is_executable_(is_executable),
1444 secondary_lookup_lock_("OatFile secondary lookup lock", kOatFileSecondaryLookupLock) {
1445 CHECK(!location_.empty());
1446}
1447
1448OatFile::~OatFile() {
1449 STLDeleteElements(&oat_dex_files_storage_);
1450}
1451
Brian Carlstrome24fa612011-09-29 00:53:55 -07001452const OatHeader& OatFile::GetOatHeader() const {
Ian Rogers30fab402012-01-23 15:43:46 -08001453 return *reinterpret_cast<const OatHeader*>(Begin());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001454}
1455
Ian Rogers13735952014-10-08 12:43:28 -07001456const uint8_t* OatFile::Begin() const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001457 CHECK(begin_ != nullptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001458 return begin_;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001459}
1460
Ian Rogers13735952014-10-08 12:43:28 -07001461const uint8_t* OatFile::End() const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001462 CHECK(end_ != nullptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001463 return end_;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001464}
1465
Vladimir Marko5c42c292015-02-25 12:02:49 +00001466const uint8_t* OatFile::BssBegin() const {
1467 return bss_begin_;
1468}
1469
1470const uint8_t* OatFile::BssEnd() const {
1471 return bss_end_;
1472}
1473
David Brazdil7b49e6c2016-09-01 11:06:18 +01001474const uint8_t* OatFile::DexBegin() const {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001475 return vdex_->Begin();
David Brazdil7b49e6c2016-09-01 11:06:18 +01001476}
1477
1478const uint8_t* OatFile::DexEnd() const {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001479 return vdex_->End();
David Brazdil7b49e6c2016-09-01 11:06:18 +01001480}
1481
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001482ArrayRef<ArtMethod*> OatFile::GetBssMethods() const {
1483 if (bss_methods_ != nullptr) {
1484 ArtMethod** methods = reinterpret_cast<ArtMethod**>(bss_methods_);
1485 ArtMethod** methods_end =
1486 reinterpret_cast<ArtMethod**>(bss_roots_ != nullptr ? bss_roots_ : bss_end_);
1487 return ArrayRef<ArtMethod*>(methods, methods_end - methods);
1488 } else {
1489 return ArrayRef<ArtMethod*>();
1490 }
1491}
1492
Vladimir Markoaad75c62016-10-03 08:46:48 +00001493ArrayRef<GcRoot<mirror::Object>> OatFile::GetBssGcRoots() const {
1494 if (bss_roots_ != nullptr) {
1495 auto* roots = reinterpret_cast<GcRoot<mirror::Object>*>(bss_roots_);
1496 auto* roots_end = reinterpret_cast<GcRoot<mirror::Object>*>(bss_end_);
1497 return ArrayRef<GcRoot<mirror::Object>>(roots, roots_end - roots);
1498 } else {
1499 return ArrayRef<GcRoot<mirror::Object>>();
1500 }
1501}
1502
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001503uint32_t OatFile::GetDebugInfoOffset(const DexFile& dex_file, uint32_t debug_info_off) {
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00001504 // Note that although the specification says that 0 should be used if there
1505 // is no debug information, some applications incorrectly use 0xFFFFFFFF.
Mathieu Chartier808c7a52017-12-15 11:19:33 -08001506 // The following check also handles debug_info_off == 0.
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00001507 if (debug_info_off < dex_file.Size() || debug_info_off == 0xFFFFFFFF) {
1508 return debug_info_off;
1509 }
1510 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1511 if (oat_dex_file == nullptr || (oat_dex_file->GetOatFile() == nullptr)) {
1512 return debug_info_off;
1513 }
1514 return oat_dex_file->GetOatFile()->GetVdexFile()->GetDebugInfoOffset(
1515 dex_file, debug_info_off);
Nicolas Geoffray58cc1cb2017-11-20 13:27:29 +00001516}
1517
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001518const OatFile::OatDexFile* OatFile::GetOatDexFile(const char* dex_location,
1519 const uint32_t* dex_location_checksum,
Richard Uhler9a37efc2016-08-05 16:32:55 -07001520 std::string* error_msg) const {
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001521 // NOTE: We assume here that the canonical location for a given dex_location never
1522 // changes. If it does (i.e. some symlink used by the filename changes) we may return
1523 // an incorrect OatDexFile. As long as we have a checksum to check, we shall return
1524 // an identical file or fail; otherwise we may see some unpredictable failures.
Calin Juravle4e1d5792014-07-15 23:56:47 +01001525
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001526 // TODO: Additional analysis of usage patterns to see if this can be simplified
1527 // without any performance loss, for example by not doing the first lock-free lookup.
1528
1529 const OatFile::OatDexFile* oat_dex_file = nullptr;
1530 StringPiece key(dex_location);
1531 // Try to find the key cheaply in the oat_dex_files_ map which holds dex locations
1532 // directly mentioned in the oat file and doesn't require locking.
1533 auto primary_it = oat_dex_files_.find(key);
1534 if (primary_it != oat_dex_files_.end()) {
1535 oat_dex_file = primary_it->second;
1536 DCHECK(oat_dex_file != nullptr);
1537 } else {
1538 // This dex_location is not one of the dex locations directly mentioned in the
1539 // oat file. The correct lookup is via the canonical location but first see in
1540 // the secondary_oat_dex_files_ whether we've looked up this location before.
1541 MutexLock mu(Thread::Current(), secondary_lookup_lock_);
1542 auto secondary_lb = secondary_oat_dex_files_.lower_bound(key);
1543 if (secondary_lb != secondary_oat_dex_files_.end() && key == secondary_lb->first) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001544 oat_dex_file = secondary_lb->second; // May be null.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001545 } else {
1546 // We haven't seen this dex_location before, we must check the canonical location.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001547 std::string dex_canonical_location = DexFileLoader::GetDexCanonicalLocation(dex_location);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001548 if (dex_canonical_location != dex_location) {
1549 StringPiece canonical_key(dex_canonical_location);
1550 auto canonical_it = oat_dex_files_.find(canonical_key);
1551 if (canonical_it != oat_dex_files_.end()) {
1552 oat_dex_file = canonical_it->second;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001553 } // else keep null.
1554 } // else keep null.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001555
1556 // Copy the key to the string_cache_ and store the result in secondary map.
1557 string_cache_.emplace_back(key.data(), key.length());
1558 StringPiece key_copy(string_cache_.back());
1559 secondary_oat_dex_files_.PutBefore(secondary_lb, key_copy, oat_dex_file);
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001560 }
1561 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001562
1563 if (oat_dex_file == nullptr) {
1564 if (error_msg != nullptr) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001565 std::string dex_canonical_location = DexFileLoader::GetDexCanonicalLocation(dex_location);
Richard Uhler9a37efc2016-08-05 16:32:55 -07001566 *error_msg = "Failed to find OatDexFile for DexFile " + std::string(dex_location)
1567 + " (canonical path " + dex_canonical_location + ") in OatFile " + GetLocation();
1568 }
1569 return nullptr;
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001570 }
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001571
Richard Uhler9a37efc2016-08-05 16:32:55 -07001572 if (dex_location_checksum != nullptr &&
1573 oat_dex_file->GetDexFileLocationChecksum() != *dex_location_checksum) {
1574 if (error_msg != nullptr) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001575 std::string dex_canonical_location = DexFileLoader::GetDexCanonicalLocation(dex_location);
Richard Uhler9a37efc2016-08-05 16:32:55 -07001576 std::string checksum = StringPrintf("0x%08x", oat_dex_file->GetDexFileLocationChecksum());
1577 std::string required_checksum = StringPrintf("0x%08x", *dex_location_checksum);
1578 *error_msg = "OatDexFile for DexFile " + std::string(dex_location)
1579 + " (canonical path " + dex_canonical_location + ") in OatFile " + GetLocation()
1580 + " has checksum " + checksum + " but " + required_checksum + " was required";
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001581 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001582 return nullptr;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001583 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001584 return oat_dex_file;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001585}
1586
Brian Carlstrome24fa612011-09-29 00:53:55 -07001587OatFile::OatDexFile::OatDexFile(const OatFile* oat_file,
Elliott Hughesaa6a5882012-01-13 19:39:16 -08001588 const std::string& dex_file_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001589 const std::string& canonical_dex_file_location,
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001590 uint32_t dex_file_location_checksum,
Ian Rogers13735952014-10-08 12:43:28 -07001591 const uint8_t* dex_file_pointer,
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001592 const uint8_t* lookup_table_data,
Vladimir Markof3c52b42017-11-17 17:32:12 +00001593 const IndexBssMapping* method_bss_mapping_data,
1594 const IndexBssMapping* type_bss_mapping_data,
1595 const IndexBssMapping* string_bss_mapping_data,
Vladimir Marko09d09432015-09-08 13:47:48 +01001596 const uint32_t* oat_class_offsets_pointer,
Mathieu Chartier120aa282017-08-05 16:03:03 -07001597 const DexLayoutSections* dex_layout_sections)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001598 : oat_file_(oat_file),
1599 dex_file_location_(dex_file_location),
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001600 canonical_dex_file_location_(canonical_dex_file_location),
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001601 dex_file_location_checksum_(dex_file_location_checksum),
Brian Carlstrom89521892011-12-07 22:05:07 -08001602 dex_file_pointer_(dex_file_pointer),
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001603 lookup_table_data_(lookup_table_data),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001604 method_bss_mapping_(method_bss_mapping_data),
Vladimir Markof3c52b42017-11-17 17:32:12 +00001605 type_bss_mapping_(type_bss_mapping_data),
1606 string_bss_mapping_(string_bss_mapping_data),
Vladimir Marko09d09432015-09-08 13:47:48 +01001607 oat_class_offsets_pointer_(oat_class_offsets_pointer),
Mathieu Chartier120aa282017-08-05 16:03:03 -07001608 dex_layout_sections_(dex_layout_sections) {
David Sehr9aa352e2016-09-15 18:13:52 -07001609 // Initialize TypeLookupTable.
1610 if (lookup_table_data_ != nullptr) {
1611 // Peek the number of classes from the DexFile.
1612 const DexFile::Header* dex_header = reinterpret_cast<const DexFile::Header*>(dex_file_pointer_);
1613 const uint32_t num_class_defs = dex_header->class_defs_size_;
1614 if (lookup_table_data_ + TypeLookupTable::RawDataLength(num_class_defs) > GetOatFile()->End()) {
1615 LOG(WARNING) << "found truncated lookup table in " << dex_file_location_;
1616 } else {
Mathieu Chartier1b868492016-11-16 16:22:37 -08001617 lookup_table_ = TypeLookupTable::Open(dex_file_pointer_, lookup_table_data_, num_class_defs);
David Sehr9aa352e2016-09-15 18:13:52 -07001618 }
1619 }
1620}
Brian Carlstrome24fa612011-09-29 00:53:55 -07001621
Mathieu Chartier1b868492016-11-16 16:22:37 -08001622OatFile::OatDexFile::OatDexFile(std::unique_ptr<TypeLookupTable>&& lookup_table)
1623 : lookup_table_(std::move(lookup_table)) {}
1624
Brian Carlstrome24fa612011-09-29 00:53:55 -07001625OatFile::OatDexFile::~OatDexFile() {}
1626
Ian Rogers05f28c62012-10-23 18:12:13 -07001627size_t OatFile::OatDexFile::FileSize() const {
1628 return reinterpret_cast<const DexFile::Header*>(dex_file_pointer_)->file_size_;
1629}
1630
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001631std::unique_ptr<const DexFile> OatFile::OatDexFile::OpenDexFile(std::string* error_msg) const {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001632 ScopedTrace trace(__PRETTY_FUNCTION__);
Aart Bik37d6a3b2016-06-21 18:30:10 -07001633 static constexpr bool kVerify = false;
1634 static constexpr bool kVerifyChecksum = false;
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001635 return DexFileLoader::Open(dex_file_pointer_,
1636 FileSize(),
1637 dex_file_location_,
1638 dex_file_location_checksum_,
1639 this,
1640 kVerify,
1641 kVerifyChecksum,
1642 error_msg);
Brian Carlstrom89521892011-12-07 22:05:07 -08001643}
1644
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001645uint32_t OatFile::OatDexFile::GetOatClassOffset(uint16_t class_def_index) const {
1646 return oat_class_offsets_pointer_[class_def_index];
1647}
1648
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001649OatFile::OatClass OatFile::OatDexFile::GetOatClass(uint16_t class_def_index) const {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001650 uint32_t oat_class_offset = GetOatClassOffset(class_def_index);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001651
Ian Rogers13735952014-10-08 12:43:28 -07001652 const uint8_t* oat_class_pointer = oat_file_->Begin() + oat_class_offset;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001653 CHECK_LT(oat_class_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001654
Ian Rogers13735952014-10-08 12:43:28 -07001655 const uint8_t* status_pointer = oat_class_pointer;
Brian Carlstromba150c32013-08-27 17:31:03 -07001656 CHECK_LT(status_pointer, oat_file_->End()) << oat_file_->GetLocation();
Vladimir Marko2c64a832018-01-04 11:31:56 +00001657 ClassStatus status = enum_cast<ClassStatus>(*reinterpret_cast<const int16_t*>(status_pointer));
1658 CHECK_LE(status, ClassStatus::kLast);
Brian Carlstromba150c32013-08-27 17:31:03 -07001659
Ian Rogers13735952014-10-08 12:43:28 -07001660 const uint8_t* type_pointer = status_pointer + sizeof(uint16_t);
Brian Carlstromba150c32013-08-27 17:31:03 -07001661 CHECK_LT(type_pointer, oat_file_->End()) << oat_file_->GetLocation();
1662 OatClassType type = static_cast<OatClassType>(*reinterpret_cast<const uint16_t*>(type_pointer));
1663 CHECK_LT(type, kOatClassMax);
1664
Ian Rogers13735952014-10-08 12:43:28 -07001665 const uint8_t* after_type_pointer = type_pointer + sizeof(int16_t);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001666 CHECK_LE(after_type_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07001667
Brian Carlstromcd937a92014-03-04 22:53:23 -08001668 uint32_t bitmap_size = 0;
Ian Rogers13735952014-10-08 12:43:28 -07001669 const uint8_t* bitmap_pointer = nullptr;
1670 const uint8_t* methods_pointer = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07001671 if (type != kOatClassNoneCompiled) {
1672 if (type == kOatClassSomeCompiled) {
1673 bitmap_size = static_cast<uint32_t>(*reinterpret_cast<const uint32_t*>(after_type_pointer));
1674 bitmap_pointer = after_type_pointer + sizeof(bitmap_size);
1675 CHECK_LE(bitmap_pointer, oat_file_->End()) << oat_file_->GetLocation();
1676 methods_pointer = bitmap_pointer + bitmap_size;
1677 } else {
1678 methods_pointer = after_type_pointer;
1679 }
1680 CHECK_LE(methods_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstromcd937a92014-03-04 22:53:23 -08001681 }
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001682
Richard Uhler07b3c232015-03-31 15:57:54 -07001683 return OatFile::OatClass(oat_file_,
1684 status,
1685 type,
1686 bitmap_size,
1687 reinterpret_cast<const uint32_t*>(bitmap_pointer),
1688 reinterpret_cast<const OatMethodOffsets*>(methods_pointer));
Brian Carlstrome24fa612011-09-29 00:53:55 -07001689}
1690
David Sehr9aa352e2016-09-15 18:13:52 -07001691const DexFile::ClassDef* OatFile::OatDexFile::FindClassDef(const DexFile& dex_file,
1692 const char* descriptor,
1693 size_t hash) {
1694 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1695 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
1696 if (LIKELY((oat_dex_file != nullptr) && (oat_dex_file->GetTypeLookupTable() != nullptr))) {
1697 const uint32_t class_def_idx = oat_dex_file->GetTypeLookupTable()->Lookup(descriptor, hash);
Andreas Gampee2abbc62017-09-15 11:59:26 -07001698 return (class_def_idx != dex::kDexNoIndex) ? &dex_file.GetClassDef(class_def_idx) : nullptr;
David Sehr9aa352e2016-09-15 18:13:52 -07001699 }
1700 // Fast path for rare no class defs case.
1701 const uint32_t num_class_defs = dex_file.NumClassDefs();
1702 if (num_class_defs == 0) {
1703 return nullptr;
1704 }
1705 const DexFile::TypeId* type_id = dex_file.FindTypeId(descriptor);
1706 if (type_id != nullptr) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001707 dex::TypeIndex type_idx = dex_file.GetIndexForTypeId(*type_id);
David Sehr9aa352e2016-09-15 18:13:52 -07001708 return dex_file.FindClassDef(type_idx);
1709 }
1710 return nullptr;
1711}
1712
Mathieu Chartier120aa282017-08-05 16:03:03 -07001713// Madvise the dex file based on the state we are moving to.
1714void OatDexFile::MadviseDexFile(const DexFile& dex_file, MadviseState state) {
Mathieu Chartierc42cb0e2017-10-13 11:35:00 -07001715 Runtime* const runtime = Runtime::Current();
1716 const bool low_ram = runtime->GetHeap()->IsLowMemoryMode();
Mathieu Chartier150d25d2017-08-28 09:52:55 -07001717 // TODO: Also do madvise hints for non low ram devices.
Mathieu Chartierc42cb0e2017-10-13 11:35:00 -07001718 if (!low_ram) {
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001719 return;
1720 }
Mathieu Chartierc42cb0e2017-10-13 11:35:00 -07001721 if (state == MadviseState::kMadviseStateAtLoad && runtime->MAdviseRandomAccess()) {
1722 // Default every dex file to MADV_RANDOM when its loaded by default for low ram devices.
1723 // Other devices have enough page cache to get performance benefits from loading more pages
1724 // into the page cache.
1725 MadviseLargestPageAlignedRegion(dex_file.Begin(),
1726 dex_file.Begin() + dex_file.Size(),
1727 MADV_RANDOM);
Mathieu Chartier120aa282017-08-05 16:03:03 -07001728 }
1729 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1730 if (oat_dex_file != nullptr) {
1731 // Should always be there.
1732 const DexLayoutSections* const sections = oat_dex_file->GetDexLayoutSections();
1733 CHECK(sections != nullptr);
1734 sections->Madvise(&dex_file, state);
1735 }
1736}
1737
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001738OatFile::OatClass::OatClass(const OatFile* oat_file,
Vladimir Marko2c64a832018-01-04 11:31:56 +00001739 ClassStatus status,
Brian Carlstromba150c32013-08-27 17:31:03 -07001740 OatClassType type,
1741 uint32_t bitmap_size,
1742 const uint32_t* bitmap_pointer,
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001743 const OatMethodOffsets* methods_pointer)
Brian Carlstromba150c32013-08-27 17:31:03 -07001744 : oat_file_(oat_file), status_(status), type_(type),
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001745 bitmap_(bitmap_pointer), methods_pointer_(methods_pointer) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001746 switch (type_) {
1747 case kOatClassAllCompiled: {
1748 CHECK_EQ(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001749 CHECK(bitmap_pointer == nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001750 CHECK(methods_pointer != nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001751 break;
1752 }
1753 case kOatClassSomeCompiled: {
1754 CHECK_NE(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001755 CHECK(bitmap_pointer != nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001756 CHECK(methods_pointer != nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001757 break;
1758 }
1759 case kOatClassNoneCompiled: {
1760 CHECK_EQ(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001761 CHECK(bitmap_pointer == nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001762 CHECK(methods_pointer_ == nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001763 break;
1764 }
1765 case kOatClassMax: {
1766 LOG(FATAL) << "Invalid OatClassType " << type_;
1767 break;
1768 }
1769 }
1770}
Brian Carlstrome24fa612011-09-29 00:53:55 -07001771
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001772uint32_t OatFile::OatClass::GetOatMethodOffsetsOffset(uint32_t method_index) const {
1773 const OatMethodOffsets* oat_method_offsets = GetOatMethodOffsets(method_index);
1774 if (oat_method_offsets == nullptr) {
1775 return 0u;
1776 }
1777 return reinterpret_cast<const uint8_t*>(oat_method_offsets) - oat_file_->Begin();
1778}
1779
1780const OatMethodOffsets* OatFile::OatClass::GetOatMethodOffsets(uint32_t method_index) const {
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001781 // 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 -07001782 if (methods_pointer_ == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001783 CHECK_EQ(kOatClassNoneCompiled, type_);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001784 return nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07001785 }
1786 size_t methods_pointer_index;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001787 if (bitmap_ == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001788 CHECK_EQ(kOatClassAllCompiled, type_);
1789 methods_pointer_index = method_index;
1790 } else {
1791 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001792 if (!BitVector::IsBitSet(bitmap_, method_index)) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001793 return nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07001794 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001795 size_t num_set_bits = BitVector::NumSetBits(bitmap_, method_index);
1796 methods_pointer_index = num_set_bits;
Brian Carlstromba150c32013-08-27 17:31:03 -07001797 }
1798 const OatMethodOffsets& oat_method_offsets = methods_pointer_[methods_pointer_index];
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001799 return &oat_method_offsets;
1800}
1801
1802const OatFile::OatMethod OatFile::OatClass::GetOatMethod(uint32_t method_index) const {
1803 const OatMethodOffsets* oat_method_offsets = GetOatMethodOffsets(method_index);
1804 if (oat_method_offsets == nullptr) {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001805 return OatMethod(nullptr, 0);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001806 }
1807 if (oat_file_->IsExecutable() ||
1808 Runtime::Current() == nullptr || // This case applies for oatdump.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001809 Runtime::Current()->IsAotCompiler()) {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001810 return OatMethod(oat_file_->Begin(), oat_method_offsets->code_offset_);
Alex Light9dcc4572014-08-14 14:16:26 -07001811 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001812 // We aren't allowed to use the compiled code. We just force it down the interpreted / jit
1813 // version.
1814 return OatMethod(oat_file_->Begin(), 0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001815}
1816
Mathieu Chartiere401d142015-04-22 13:56:20 -07001817void OatFile::OatMethod::LinkMethod(ArtMethod* method) const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001818 CHECK(method != nullptr);
Ian Rogersef7d42f2014-01-06 12:55:46 -08001819 method->SetEntryPointFromQuickCompiledCode(GetQuickCode());
Brian Carlstromae826982011-11-09 01:33:42 -08001820}
1821
Andreas Gampe7ba64962014-10-23 11:37:40 -07001822bool OatFile::IsPic() const {
Igor Murashkin46774762014-10-22 11:37:02 -07001823 return GetOatHeader().IsPic();
Andreas Gampe7ba64962014-10-23 11:37:40 -07001824 // TODO: Check against oat_patches. b/18144996
1825}
1826
Sebastien Hertz0de11332015-05-13 12:14:05 +02001827bool OatFile::IsDebuggable() const {
1828 return GetOatHeader().IsDebuggable();
1829}
1830
Andreas Gampe29d38e72016-03-23 15:31:51 +00001831CompilerFilter::Filter OatFile::GetCompilerFilter() const {
1832 return GetOatHeader().GetCompilerFilter();
Calin Juravleb077e152016-02-18 18:47:37 +00001833}
1834
Calin Juravle44e5efa2017-09-12 00:54:26 -07001835std::string OatFile::GetClassLoaderContext() const {
1836 return GetOatHeader().GetStoreValueByKey(OatHeader::kClassPathKey);
Igor Murashkin2ffb7032017-11-08 13:35:21 -08001837}
Calin Juravle44e5efa2017-09-12 00:54:26 -07001838
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001839OatFile::OatClass OatFile::FindOatClass(const DexFile& dex_file,
1840 uint16_t class_def_idx,
1841 bool* found) {
1842 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
1843 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Mathieu Chartier1b868492016-11-16 16:22:37 -08001844 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001845 *found = false;
1846 return OatFile::OatClass::Invalid();
1847 }
1848 *found = true;
1849 return oat_dex_file->GetOatClass(class_def_idx);
1850}
1851
Mathieu Chartier1b868492016-11-16 16:22:37 -08001852void OatFile::OatDexFile::AssertAotCompiler() {
1853 CHECK(Runtime::Current()->IsAotCompiler());
1854}
1855
Brian Carlstrome24fa612011-09-29 00:53:55 -07001856} // namespace art