blob: c03dbccbc4dc4d08ff23536dce1cec9691dd41a3 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Brian Carlstrome24fa612011-09-29 00:53:55 -070016
17#include "oat_file.h"
18
Brian Carlstrom700c8d32012-11-05 10:42:02 -080019#include <dlfcn.h>
David Srbecky1baabf02015-06-16 17:12:34 +000020#ifndef __APPLE__
21#include <link.h> // for dl_iterate_phdr.
22#endif
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070023#include <unistd.h>
24
25#include <cstdlib>
26#include <cstring>
Richard Uhlere5fed032015-03-18 08:21:11 -070027#include <sstream>
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070028#include <type_traits>
Shubham Ajmerab22dea02017-10-04 18:36:41 -070029#include <sys/stat.h>
Richard Uhlere5fed032015-03-18 08:21:11 -070030
Andreas Gampefa8429b2015-04-07 18:34:42 -070031// dlopen_ext support from bionic.
Bilyan Borisovbb661c02016-04-04 16:27:32 +010032#ifdef ART_TARGET_ANDROID
Andreas Gampefa8429b2015-04-07 18:34:42 -070033#include "android/dlext.h"
34#endif
35
Andreas Gampe46ee31b2016-12-14 10:11:49 -080036#include "android-base/stringprintf.h"
37
Andreas Gampec6ea7d02017-02-01 16:46:28 -080038#include "art_method.h"
Brian Carlstromba150c32013-08-27 17:31:03 -070039#include "base/bit_vector.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070040#include "base/enums.h"
David Sehr891a50e2017-10-27 17:01:07 -070041#include "base/file_utils.h"
Andreas Gampe170331f2017-12-07 18:41:03 -080042#include "base/logging.h" // For VLOG_IS_ON.
Elliott Hughes1aa246d2012-12-13 09:29:36 -080043#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080044#include "base/systrace.h"
Elliott Hughes76160052012-12-12 16:31:20 -080045#include "base/unix_file/fd_file.h"
David Sehr013fd802018-01-11 22:55:24 -080046#include "dex/art_dex_file_loader.h"
David Sehr9e734c72018-01-04 17:56:19 -080047#include "dex/dex_file_loader.h"
48#include "dex/dex_file_types.h"
49#include "dex/standard_dex_file.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080050#include "elf_file.h"
Alex Light84d76052014-08-22 17:49:35 -070051#include "elf_utils.h"
Vladimir Markoaad75c62016-10-03 08:46:48 +000052#include "gc_root.h"
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +010053#include "gc/space/image_space.h"
David Srbecky1baabf02015-06-16 17:12:34 +000054#include "mem_map.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080055#include "mirror/class.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070056#include "mirror/object-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070057#include "oat.h"
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +010058#include "oat_file-inl.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070059#include "oat_file_manager.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070060#include "os.h"
Andreas Gampe22f8e5c2014-07-09 11:38:21 -070061#include "runtime.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000062#include "type_lookup_table.h"
David Sehr9aa352e2016-09-15 18:13:52 -070063#include "utf-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080064#include "utils.h"
Vladimir Marko97d7e1c2016-10-04 14:44:28 +010065#include "vdex_file.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070066
67namespace art {
68
Andreas Gampe46ee31b2016-12-14 10:11:49 -080069using android::base::StringPrintf;
70
Andreas Gampe049cff02015-12-01 23:27:12 -080071// Whether OatFile::Open will try dlopen. Fallback is our own ELF loader.
David Srbecky1baabf02015-06-16 17:12:34 +000072static constexpr bool kUseDlopen = true;
Andreas Gampefa8429b2015-04-07 18:34:42 -070073
Andreas Gampe049cff02015-12-01 23:27:12 -080074// Whether OatFile::Open will try dlopen on the host. On the host we're not linking against
Andreas Gampefa8429b2015-04-07 18:34:42 -070075// bionic, so cannot take advantage of the support for changed semantics (loading the same soname
76// multiple times). However, if/when we switch the above, we likely want to switch this, too,
77// to get test coverage of the code paths.
David Srbecky1baabf02015-06-16 17:12:34 +000078static constexpr bool kUseDlopenOnHost = true;
Andreas Gampefa8429b2015-04-07 18:34:42 -070079
80// For debugging, Open will print DlOpen error message if set to true.
81static constexpr bool kPrintDlOpenErrorMessage = false;
82
Andreas Gampe049cff02015-12-01 23:27:12 -080083// Note for OatFileBase and descendents:
84//
85// These are used in OatFile::Open to try all our loaders.
86//
87// The process is simple:
88//
89// 1) Allocate an instance through the standard constructor (location, executable)
90// 2) Load() to try to open the file.
91// 3) ComputeFields() to populate the OatFile fields like begin_, using FindDynamicSymbolAddress.
92// 4) PreSetup() for any steps that should be done before the final setup.
93// 5) Setup() to complete the procedure.
Richard Uhlere5fed032015-03-18 08:21:11 -070094
Andreas Gampe049cff02015-12-01 23:27:12 -080095class OatFileBase : public OatFile {
96 public:
97 virtual ~OatFileBase() {}
Richard Uhlere5fed032015-03-18 08:21:11 -070098
Andreas Gampe049cff02015-12-01 23:27:12 -080099 template <typename kOatFileBaseSubType>
David Brazdil7b49e6c2016-09-01 11:06:18 +0100100 static OatFileBase* OpenOatFile(const std::string& vdex_filename,
101 const std::string& elf_filename,
Alex Light84d76052014-08-22 17:49:35 -0700102 const std::string& location,
Andreas Gampe049cff02015-12-01 23:27:12 -0800103 uint8_t* requested_base,
104 uint8_t* oat_file_begin,
105 bool writable,
106 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800107 bool low_4gb,
Richard Uhlere5fed032015-03-18 08:21:11 -0700108 const char* abs_dex_location,
Andreas Gampe049cff02015-12-01 23:27:12 -0800109 std::string* error_msg);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800110
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700111 template <typename kOatFileBaseSubType>
112 static OatFileBase* OpenOatFile(int vdex_fd,
113 int oat_fd,
114 const std::string& vdex_filename,
115 const std::string& oat_filename,
116 uint8_t* requested_base,
117 uint8_t* oat_file_begin,
118 bool writable,
119 bool executable,
120 bool low_4gb,
121 const char* abs_dex_location,
122 std::string* error_msg);
123
Andreas Gampe049cff02015-12-01 23:27:12 -0800124 protected:
125 OatFileBase(const std::string& filename, bool executable) : OatFile(filename, executable) {}
Andreas Gampefa8429b2015-04-07 18:34:42 -0700126
Andreas Gampe049cff02015-12-01 23:27:12 -0800127 virtual const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
128 std::string* error_msg) const = 0;
129
Andreas Gampe4075f832016-05-18 13:09:54 -0700130 virtual void PreLoad() = 0;
131
David Brazdil7b49e6c2016-09-01 11:06:18 +0100132 bool LoadVdex(const std::string& vdex_filename,
133 bool writable,
134 bool low_4gb,
135 std::string* error_msg);
136
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700137 bool LoadVdex(int vdex_fd,
138 const std::string& vdex_filename,
139 bool writable,
140 bool low_4gb,
141 std::string* error_msg);
142
Andreas Gampe049cff02015-12-01 23:27:12 -0800143 virtual bool Load(const std::string& elf_filename,
144 uint8_t* oat_file_begin,
145 bool writable,
146 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800147 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800148 std::string* error_msg) = 0;
149
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700150 virtual bool Load(int oat_fd,
151 uint8_t* oat_file_begin,
152 bool writable,
153 bool executable,
154 bool low_4gb,
155 std::string* error_msg) = 0;
156
Andreas Gampe049cff02015-12-01 23:27:12 -0800157 bool ComputeFields(uint8_t* requested_base,
158 const std::string& file_path,
159 std::string* error_msg);
160
161 virtual void PreSetup(const std::string& elf_filename) = 0;
162
163 bool Setup(const char* abs_dex_location, std::string* error_msg);
164
165 // Setters exposed for ElfOatFile.
166
167 void SetBegin(const uint8_t* begin) {
168 begin_ = begin;
Andreas Gampefa8429b2015-04-07 18:34:42 -0700169 }
170
Andreas Gampe049cff02015-12-01 23:27:12 -0800171 void SetEnd(const uint8_t* end) {
172 end_ = end;
173 }
174
David Brazdilc93b3be2016-09-12 18:49:58 +0100175 void SetVdex(VdexFile* vdex) {
176 vdex_.reset(vdex);
177 }
178
Andreas Gampe049cff02015-12-01 23:27:12 -0800179 private:
180 DISALLOW_COPY_AND_ASSIGN(OatFileBase);
181};
182
183template <typename kOatFileBaseSubType>
David Brazdil7b49e6c2016-09-01 11:06:18 +0100184OatFileBase* OatFileBase::OpenOatFile(const std::string& vdex_filename,
185 const std::string& elf_filename,
Andreas Gampe049cff02015-12-01 23:27:12 -0800186 const std::string& location,
187 uint8_t* requested_base,
188 uint8_t* oat_file_begin,
189 bool writable,
190 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800191 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800192 const char* abs_dex_location,
193 std::string* error_msg) {
194 std::unique_ptr<OatFileBase> ret(new kOatFileBaseSubType(location, executable));
Andreas Gampe4075f832016-05-18 13:09:54 -0700195
196 ret->PreLoad();
197
Andreas Gampe049cff02015-12-01 23:27:12 -0800198 if (!ret->Load(elf_filename,
199 oat_file_begin,
200 writable,
201 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800202 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800203 error_msg)) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800204 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800205 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800206
Andreas Gampe049cff02015-12-01 23:27:12 -0800207 if (!ret->ComputeFields(requested_base, elf_filename, error_msg)) {
208 return nullptr;
209 }
Andreas Gampe4075f832016-05-18 13:09:54 -0700210
David Srbeckyec2cdf42017-12-08 16:21:25 +0000211 if (!ret->LoadVdex(vdex_filename, writable, low_4gb, error_msg)) {
212 return nullptr;
213 }
214
Andreas Gampe049cff02015-12-01 23:27:12 -0800215 ret->PreSetup(elf_filename);
216
217 if (!ret->Setup(abs_dex_location, error_msg)) {
218 return nullptr;
219 }
220
Dave Allison69dfe512014-07-11 17:11:58 +0000221 return ret.release();
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800222}
223
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700224template <typename kOatFileBaseSubType>
225OatFileBase* OatFileBase::OpenOatFile(int vdex_fd,
226 int oat_fd,
227 const std::string& vdex_location,
228 const std::string& oat_location,
229 uint8_t* requested_base,
230 uint8_t* oat_file_begin,
231 bool writable,
232 bool executable,
233 bool low_4gb,
234 const char* abs_dex_location,
235 std::string* error_msg) {
236 std::unique_ptr<OatFileBase> ret(new kOatFileBaseSubType(oat_location, executable));
237
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700238 if (!ret->Load(oat_fd,
239 oat_file_begin,
240 writable,
241 executable,
242 low_4gb,
243 error_msg)) {
244 return nullptr;
245 }
246
247 if (!ret->ComputeFields(requested_base, oat_location, error_msg)) {
248 return nullptr;
249 }
250
David Srbeckyec2cdf42017-12-08 16:21:25 +0000251 if (!ret->LoadVdex(vdex_fd, vdex_location, writable, low_4gb, error_msg)) {
252 return nullptr;
253 }
254
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700255 ret->PreSetup(oat_location);
256
257 if (!ret->Setup(abs_dex_location, error_msg)) {
258 return nullptr;
259 }
260
261 return ret.release();
262}
263
David Brazdil7b49e6c2016-09-01 11:06:18 +0100264bool OatFileBase::LoadVdex(const std::string& vdex_filename,
265 bool writable,
266 bool low_4gb,
267 std::string* error_msg) {
David Srbeckyec2cdf42017-12-08 16:21:25 +0000268 vdex_ = VdexFile::OpenAtAddress(vdex_begin_,
269 vdex_end_ - vdex_begin_,
Andreas Gampec1fc4492018-01-10 14:19:36 -0800270 vdex_begin_ != nullptr /* mmap_reuse */,
David Srbeckyec2cdf42017-12-08 16:21:25 +0000271 vdex_filename,
272 writable,
273 low_4gb,
274 /* unquicken*/ false,
275 error_msg);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100276 if (vdex_.get() == nullptr) {
277 *error_msg = StringPrintf("Failed to load vdex file '%s' %s",
278 vdex_filename.c_str(),
279 error_msg->c_str());
280 return false;
281 }
282 return true;
283}
284
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700285bool OatFileBase::LoadVdex(int vdex_fd,
286 const std::string& vdex_filename,
287 bool writable,
288 bool low_4gb,
289 std::string* error_msg) {
290 if (vdex_fd != -1) {
291 struct stat s;
292 int rc = TEMP_FAILURE_RETRY(fstat(vdex_fd, &s));
293 if (rc == -1) {
294 PLOG(WARNING) << "Failed getting length of vdex file";
295 } else {
David Srbeckyec2cdf42017-12-08 16:21:25 +0000296 vdex_ = VdexFile::OpenAtAddress(vdex_begin_,
297 vdex_end_ - vdex_begin_,
Andreas Gampec1fc4492018-01-10 14:19:36 -0800298 vdex_begin_ != nullptr /* mmap_reuse */,
David Srbeckyec2cdf42017-12-08 16:21:25 +0000299 vdex_fd,
300 s.st_size,
301 vdex_filename,
302 writable,
303 low_4gb,
304 false /* unquicken */,
305 error_msg);
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700306 if (vdex_.get() == nullptr) {
307 *error_msg = "Failed opening vdex file.";
308 return false;
309 }
310 }
311 }
312 return true;
313}
314
Andreas Gampe049cff02015-12-01 23:27:12 -0800315bool OatFileBase::ComputeFields(uint8_t* requested_base,
316 const std::string& file_path,
317 std::string* error_msg) {
318 std::string symbol_error_msg;
319 begin_ = FindDynamicSymbolAddress("oatdata", &symbol_error_msg);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700320 if (begin_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800321 *error_msg = StringPrintf("Failed to find oatdata symbol in '%s' %s",
322 file_path.c_str(),
323 symbol_error_msg.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700324 return false;
325 }
326 if (requested_base != nullptr && begin_ != requested_base) {
Nicolas Geoffrayf97cf2a2016-03-09 15:36:23 +0000327 // Host can fail this check. Do not dump there to avoid polluting the output.
Andreas Gampe7ec09042016-04-01 17:20:49 -0700328 if (kIsTargetBuild && (kIsDebugBuild || VLOG_IS_ON(oat))) {
Andreas Gampe170331f2017-12-07 18:41:03 -0800329 PrintFileToLog("/proc/self/maps", android::base::LogSeverity::WARNING);
Nicolas Geoffrayf97cf2a2016-03-09 15:36:23 +0000330 }
Andreas Gampefa8429b2015-04-07 18:34:42 -0700331 *error_msg = StringPrintf("Failed to find oatdata symbol at expected address: "
Andreas Gampe049cff02015-12-01 23:27:12 -0800332 "oatdata=%p != expected=%p. See process maps in the log.",
333 begin_, requested_base);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700334 return false;
335 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800336 end_ = FindDynamicSymbolAddress("oatlastword", &symbol_error_msg);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700337 if (end_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800338 *error_msg = StringPrintf("Failed to find oatlastword symbol in '%s' %s",
339 file_path.c_str(),
340 symbol_error_msg.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700341 return false;
342 }
343 // Readjust to be non-inclusive upper bound.
344 end_ += sizeof(uint32_t);
345
Andreas Gampe049cff02015-12-01 23:27:12 -0800346 bss_begin_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbss", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700347 if (bss_begin_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800348 // No .bss section.
Andreas Gampefa8429b2015-04-07 18:34:42 -0700349 bss_end_ = nullptr;
Andreas Gampefa8429b2015-04-07 18:34:42 -0700350 } else {
Andreas Gampe049cff02015-12-01 23:27:12 -0800351 bss_end_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbsslastword", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700352 if (bss_end_ == nullptr) {
David Srbeckyec2cdf42017-12-08 16:21:25 +0000353 *error_msg = StringPrintf("Failed to find oatbsslastword symbol in '%s'", file_path.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700354 return false;
355 }
356 // Readjust to be non-inclusive upper bound.
357 bss_end_ += sizeof(uint32_t);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100358 // Find bss methods if present.
359 bss_methods_ =
360 const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbssmethods", &symbol_error_msg));
Vladimir Markoaad75c62016-10-03 08:46:48 +0000361 // Find bss roots if present.
362 bss_roots_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbssroots", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700363 }
364
David Srbeckyec2cdf42017-12-08 16:21:25 +0000365 vdex_begin_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatdex", &symbol_error_msg));
366 if (vdex_begin_ == nullptr) {
367 // No .vdex section.
368 vdex_end_ = nullptr;
369 } else {
370 vdex_end_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatdexlastword", &symbol_error_msg));
371 if (vdex_end_ == nullptr) {
372 *error_msg = StringPrintf("Failed to find oatdexlastword symbol in '%s'", file_path.c_str());
373 return false;
374 }
375 // Readjust to be non-inclusive upper bound.
376 vdex_end_ += sizeof(uint32_t);
377 }
378
Andreas Gampe049cff02015-12-01 23:27:12 -0800379 return true;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800380}
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800381
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100382// Read an unaligned entry from the OatDexFile data in OatFile and advance the read
383// position by the number of bytes read, i.e. sizeof(T).
384// Return true on success, false if the read would go beyond the end of the OatFile.
385template <typename T>
Vladimir Marko722fa982015-10-19 18:18:27 +0100386inline static bool ReadOatDexFileData(const OatFile& oat_file,
387 /*inout*/const uint8_t** oat,
388 /*out*/T* value) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100389 DCHECK(oat != nullptr);
390 DCHECK(value != nullptr);
391 DCHECK_LE(*oat, oat_file.End());
392 if (UNLIKELY(static_cast<size_t>(oat_file.End() - *oat) < sizeof(T))) {
393 return false;
394 }
395 static_assert(std::is_trivial<T>::value, "T must be a trivial type");
396 typedef __attribute__((__aligned__(1))) T unaligned_type;
397 *value = *reinterpret_cast<const unaligned_type*>(*oat);
398 *oat += sizeof(T);
399 return true;
400}
401
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100402static inline bool MapConstantTables(const gc::space::ImageSpace* space,
403 uint8_t* address) {
404 // If MREMAP_DUP is ever merged to Linux kernel, use it to avoid the unnecessary open()/close().
405 // Note: The current approach relies on the filename still referencing the same inode.
406
407 File file(space->GetImageFilename(), O_RDONLY, /* checkUsage */ false);
408 if (!file.IsOpened()) {
409 LOG(ERROR) << "Failed to open boot image file " << space->GetImageFilename();
410 return false;
411 }
412
413 uint32_t offset = space->GetImageHeader().GetBootImageConstantTablesOffset();
414 uint32_t size = space->GetImageHeader().GetBootImageConstantTablesSize();
415 std::string error_msg;
416 std::unique_ptr<MemMap> mem_map(MemMap::MapFileAtAddress(address,
417 size,
418 PROT_READ,
419 MAP_PRIVATE,
420 file.Fd(),
421 offset,
422 /* low_4gb */ false,
423 /* reuse */ true,
424 file.GetPath().c_str(),
425 &error_msg));
426 if (mem_map == nullptr) {
427 LOG(ERROR) << "Failed to mmap boot image tables from file " << space->GetImageFilename();
428 return false;
429 }
430 return true;
431}
432
Vladimir Markof3c52b42017-11-17 17:32:12 +0000433static bool ReadIndexBssMapping(OatFile* oat_file,
434 /*inout*/const uint8_t** oat,
435 size_t dex_file_index,
436 const std::string& dex_file_location,
437 const char* tag,
438 /*out*/const IndexBssMapping** mapping,
439 std::string* error_msg) {
440 uint32_t index_bss_mapping_offset;
441 if (UNLIKELY(!ReadOatDexFileData(*oat_file, oat, &index_bss_mapping_offset))) {
442 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zd for '%s' truncated "
443 "after %s bss mapping offset",
444 oat_file->GetLocation().c_str(),
445 dex_file_index,
446 dex_file_location.c_str(),
447 tag);
448 return false;
449 }
450 const bool readable_index_bss_mapping_size =
451 index_bss_mapping_offset != 0u &&
452 index_bss_mapping_offset <= oat_file->Size() &&
453 IsAligned<alignof(IndexBssMapping)>(index_bss_mapping_offset) &&
454 oat_file->Size() - index_bss_mapping_offset >= IndexBssMapping::ComputeSize(0);
455 const IndexBssMapping* index_bss_mapping = readable_index_bss_mapping_size
456 ? reinterpret_cast<const IndexBssMapping*>(oat_file->Begin() + index_bss_mapping_offset)
457 : nullptr;
458 if (index_bss_mapping_offset != 0u &&
459 (UNLIKELY(index_bss_mapping == nullptr) ||
460 UNLIKELY(index_bss_mapping->size() == 0u) ||
461 UNLIKELY(oat_file->Size() - index_bss_mapping_offset <
462 IndexBssMapping::ComputeSize(index_bss_mapping->size())))) {
463 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with unaligned or "
464 " truncated %s bss mapping, offset %u of %zu, length %zu",
465 oat_file->GetLocation().c_str(),
466 dex_file_index,
467 dex_file_location.c_str(),
468 tag,
469 index_bss_mapping_offset,
470 oat_file->Size(),
471 index_bss_mapping != nullptr ? index_bss_mapping->size() : 0u);
472 return false;
473 }
474
475 *mapping = index_bss_mapping;
476 return true;
477}
478
479static void DCheckIndexToBssMapping(OatFile* oat_file,
480 uint32_t number_of_indexes,
481 size_t slot_size,
482 const IndexBssMapping* index_bss_mapping) {
483 if (kIsDebugBuild && index_bss_mapping != nullptr) {
484 size_t index_bits = IndexBssMappingEntry::IndexBits(number_of_indexes);
485 const IndexBssMappingEntry* prev_entry = nullptr;
486 for (const IndexBssMappingEntry& entry : *index_bss_mapping) {
487 CHECK_ALIGNED_PARAM(entry.bss_offset, slot_size);
488 // When loading a non-executable ElfOatFile, .bss symbols are not even
489 // looked up, so we cannot verify the offset against BssSize().
490 if (oat_file->IsExecutable()) {
491 CHECK_LT(entry.bss_offset, oat_file->BssSize());
492 }
493 uint32_t mask = entry.GetMask(index_bits);
494 CHECK_LE(POPCOUNT(mask) * slot_size, entry.bss_offset);
495 size_t index_mask_span = (mask != 0u) ? 32u - index_bits - CTZ(mask) : 0u;
496 CHECK_LE(index_mask_span, entry.GetIndex(index_bits));
497 if (prev_entry != nullptr) {
498 CHECK_LT(prev_entry->GetIndex(index_bits), entry.GetIndex(index_bits) - index_mask_span);
499 }
500 prev_entry = &entry;
501 }
502 CHECK_LT(prev_entry->GetIndex(index_bits), number_of_indexes);
503 }
504}
505
Andreas Gampe049cff02015-12-01 23:27:12 -0800506bool OatFileBase::Setup(const char* abs_dex_location, std::string* error_msg) {
Brian Carlstromf1b30302013-03-28 10:35:32 -0700507 if (!GetOatHeader().IsValid()) {
Andreas Gampe2bcb3b22014-12-12 15:25:14 -0800508 std::string cause = GetOatHeader().GetValidationErrorMessage();
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100509 *error_msg = StringPrintf("Invalid oat header for '%s': %s",
510 GetLocation().c_str(),
Andreas Gampe2bcb3b22014-12-12 15:25:14 -0800511 cause.c_str());
Brian Carlstromf1b30302013-03-28 10:35:32 -0700512 return false;
513 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100514 PointerSize pointer_size = GetInstructionSetPointerSize(GetOatHeader().GetInstructionSet());
515 size_t key_value_store_size =
516 (Size() >= sizeof(OatHeader)) ? GetOatHeader().GetKeyValueStoreSize() : 0u;
517 if (Size() < sizeof(OatHeader) + key_value_store_size) {
518 *error_msg = StringPrintf("In oat file '%s' found truncated OatHeader, "
519 "size = %zu < %zu + %zu",
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100520 GetLocation().c_str(),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100521 Size(),
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100522 sizeof(OatHeader),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100523 key_value_store_size);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700524 return false;
525 }
526
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100527 size_t oat_dex_files_offset = GetOatHeader().GetOatDexFilesOffset();
528 if (oat_dex_files_offset < GetOatHeader().GetHeaderSize() || oat_dex_files_offset > Size()) {
529 *error_msg = StringPrintf("In oat file '%s' found invalid oat dex files offset: "
530 "%zu is not in [%zu, %zu]",
531 GetLocation().c_str(),
532 oat_dex_files_offset,
533 GetOatHeader().GetHeaderSize(),
534 Size());
535 return false;
536 }
537 const uint8_t* oat = Begin() + oat_dex_files_offset; // Jump to the OatDexFile records.
538
539 DCHECK_GE(static_cast<size_t>(pointer_size), alignof(GcRoot<mirror::Object>));
540 if (!IsAligned<kPageSize>(bss_begin_) ||
541 !IsAlignedParam(bss_methods_, static_cast<size_t>(pointer_size)) ||
542 !IsAlignedParam(bss_roots_, static_cast<size_t>(pointer_size)) ||
Vladimir Markoaad75c62016-10-03 08:46:48 +0000543 !IsAligned<alignof(GcRoot<mirror::Object>)>(bss_end_)) {
544 *error_msg = StringPrintf("In oat file '%s' found unaligned bss symbol(s): "
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100545 "begin = %p, methods_ = %p, roots = %p, end = %p",
Vladimir Markoaad75c62016-10-03 08:46:48 +0000546 GetLocation().c_str(),
547 bss_begin_,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100548 bss_methods_,
Vladimir Markoaad75c62016-10-03 08:46:48 +0000549 bss_roots_,
550 bss_end_);
551 return false;
552 }
553
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100554 if ((bss_methods_ != nullptr && (bss_methods_ < bss_begin_ || bss_methods_ > bss_end_)) ||
555 (bss_roots_ != nullptr && (bss_roots_ < bss_begin_ || bss_roots_ > bss_end_)) ||
556 (bss_methods_ != nullptr && bss_roots_ != nullptr && bss_methods_ > bss_roots_)) {
557 *error_msg = StringPrintf("In oat file '%s' found bss symbol(s) outside .bss or unordered: "
Vladimir Marko0f3c7002017-09-07 14:15:56 +0100558 "begin = %p, methods = %p, roots = %p, end = %p",
Vladimir Markoaad75c62016-10-03 08:46:48 +0000559 GetLocation().c_str(),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000560 bss_begin_,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100561 bss_methods_,
562 bss_roots_,
Vladimir Markoaad75c62016-10-03 08:46:48 +0000563 bss_end_);
564 return false;
565 }
566
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100567 uint8_t* after_tables =
568 (bss_methods_ != nullptr) ? bss_methods_ : bss_roots_; // May be null.
569 uint8_t* boot_image_tables = (bss_begin_ == after_tables) ? nullptr : bss_begin_;
570 uint8_t* boot_image_tables_end =
571 (bss_begin_ == after_tables) ? nullptr : (after_tables != nullptr) ? after_tables : bss_end_;
572 DCHECK_EQ(boot_image_tables != nullptr, boot_image_tables_end != nullptr);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100573 uint32_t dex_file_count = GetOatHeader().GetDexFileCount();
574 oat_dex_files_storage_.reserve(dex_file_count);
575 for (size_t i = 0; i < dex_file_count; i++) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100576 uint32_t dex_file_location_size;
577 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_location_size))) {
578 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu truncated after dex file "
579 "location size",
580 GetLocation().c_str(),
581 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700582 return false;
583 }
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100584 if (UNLIKELY(dex_file_location_size == 0U)) {
585 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu with empty location name",
586 GetLocation().c_str(),
587 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700588 return false;
589 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000590 if (UNLIKELY(static_cast<size_t>(End() - oat) < dex_file_location_size)) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100591 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu with truncated dex file "
592 "location",
593 GetLocation().c_str(),
594 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700595 return false;
596 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000597 const char* dex_file_location_data = reinterpret_cast<const char*>(oat);
598 oat += dex_file_location_size;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700599
Richard Uhlere5fed032015-03-18 08:21:11 -0700600 std::string dex_file_location = ResolveRelativeEncodedDexLocation(
601 abs_dex_location,
602 std::string(dex_file_location_data, dex_file_location_size));
Brian Carlstrome24fa612011-09-29 00:53:55 -0700603
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100604 uint32_t dex_file_checksum;
605 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_checksum))) {
606 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated after "
607 "dex file checksum",
608 GetLocation().c_str(),
609 i,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700610 dex_file_location.c_str());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700611 return false;
612 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700613
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100614 uint32_t dex_file_offset;
615 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_offset))) {
616 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated "
617 "after dex file offsets",
618 GetLocation().c_str(),
619 i,
620 dex_file_location.c_str());
621 return false;
622 }
Andreas Gampee166e672017-12-19 18:59:29 +0000623 if (UNLIKELY(dex_file_offset == 0U)) {
624 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with zero dex "
625 "file offset",
626 GetLocation().c_str(),
627 i,
628 dex_file_location.c_str());
629 return false;
630 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100631 if (UNLIKELY(dex_file_offset > DexSize())) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100632 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
633 "offset %u > %zu",
634 GetLocation().c_str(),
635 i,
636 dex_file_location.c_str(),
637 dex_file_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100638 DexSize());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700639 return false;
640 }
Andreas Gampee166e672017-12-19 18:59:29 +0000641 if (UNLIKELY(DexSize() - dex_file_offset < sizeof(DexFile::Header))) {
642 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
643 "offset %u of %zu but the size of dex file header is %zu",
644 GetLocation().c_str(),
645 i,
646 dex_file_location.c_str(),
647 dex_file_offset,
648 DexSize(),
649 sizeof(DexFile::Header));
650 return false;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000651 }
Brian Carlstrom89521892011-12-07 22:05:07 -0800652
Andreas Gampee166e672017-12-19 18:59:29 +0000653 const uint8_t* dex_file_pointer = DexBegin() + dex_file_offset;
654
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700655 const bool valid_magic = DexFileLoader::IsMagicValid(dex_file_pointer);
Mathieu Chartier7b074bf2017-09-25 16:22:36 -0700656 if (UNLIKELY(!valid_magic)) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100657 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with invalid "
658 "dex file magic '%s'",
659 GetLocation().c_str(),
660 i,
661 dex_file_location.c_str(),
662 dex_file_pointer);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700663 return false;
664 }
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700665 if (UNLIKELY(!DexFileLoader::IsVersionAndMagicValid(dex_file_pointer))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100666 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with invalid "
667 "dex file version '%s'",
668 GetLocation().c_str(),
669 i,
670 dex_file_location.c_str(),
671 dex_file_pointer);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700672 return false;
673 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800674 const DexFile::Header* header = reinterpret_cast<const DexFile::Header*>(dex_file_pointer);
Andreas Gampee166e672017-12-19 18:59:29 +0000675 if (DexSize() - dex_file_offset < header->file_size_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000676 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
677 "offset %u and size %u truncated at %zu",
678 GetLocation().c_str(),
679 i,
680 dex_file_location.c_str(),
681 dex_file_offset,
682 header->file_size_,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100683 DexSize());
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000684 return false;
685 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300686
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000687 uint32_t class_offsets_offset;
688 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &class_offsets_offset))) {
689 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated "
690 "after class offsets offset",
691 GetLocation().c_str(),
692 i,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300693 dex_file_location.c_str());
694 return false;
695 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000696 if (UNLIKELY(class_offsets_offset > Size()) ||
697 UNLIKELY((Size() - class_offsets_offset) / sizeof(uint32_t) < header->class_defs_size_)) {
698 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with truncated "
699 "class offsets, offset %u of %zu, class defs %u",
700 GetLocation().c_str(),
701 i,
702 dex_file_location.c_str(),
703 class_offsets_offset,
704 Size(),
705 header->class_defs_size_);
706 return false;
707 }
708 if (UNLIKELY(!IsAligned<alignof(uint32_t)>(class_offsets_offset))) {
709 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with unaligned "
710 "class offsets, offset %u",
711 GetLocation().c_str(),
712 i,
713 dex_file_location.c_str(),
714 class_offsets_offset);
715 return false;
716 }
717 const uint32_t* class_offsets_pointer =
718 reinterpret_cast<const uint32_t*>(Begin() + class_offsets_offset);
719
720 uint32_t lookup_table_offset;
721 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &lookup_table_offset))) {
722 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zd for '%s' truncated "
723 "after lookup table offset",
724 GetLocation().c_str(),
725 i,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300726 dex_file_location.c_str());
727 return false;
728 }
729 const uint8_t* lookup_table_data = lookup_table_offset != 0u
730 ? Begin() + lookup_table_offset
731 : nullptr;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000732 if (lookup_table_offset != 0u &&
733 (UNLIKELY(lookup_table_offset > Size()) ||
734 UNLIKELY(Size() - lookup_table_offset <
735 TypeLookupTable::RawDataLength(header->class_defs_size_)))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100736 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with truncated "
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000737 "type lookup table, offset %u of %zu, class defs %u",
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100738 GetLocation().c_str(),
739 i,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000740 dex_file_location.c_str(),
741 lookup_table_offset,
742 Size(),
743 header->class_defs_size_);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700744 return false;
745 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700746
Mathieu Chartier120aa282017-08-05 16:03:03 -0700747 uint32_t dex_layout_sections_offset;
748 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_layout_sections_offset))) {
749 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zd for '%s' truncated "
750 "after dex layout sections offset",
751 GetLocation().c_str(),
752 i,
753 dex_file_location.c_str());
754 return false;
755 }
756 const DexLayoutSections* const dex_layout_sections = dex_layout_sections_offset != 0
757 ? reinterpret_cast<const DexLayoutSections*>(Begin() + dex_layout_sections_offset)
758 : nullptr;
759
Vladimir Markof3c52b42017-11-17 17:32:12 +0000760 const IndexBssMapping* method_bss_mapping;
761 const IndexBssMapping* type_bss_mapping;
762 const IndexBssMapping* string_bss_mapping;
763 if (!ReadIndexBssMapping(
764 this, &oat, i, dex_file_location, "method", &method_bss_mapping, error_msg) ||
765 !ReadIndexBssMapping(
766 this, &oat, i, dex_file_location, "type", &type_bss_mapping, error_msg) ||
767 !ReadIndexBssMapping(
768 this, &oat, i, dex_file_location, "string", &string_bss_mapping, error_msg)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100769 return false;
770 }
Vladimir Markof3c52b42017-11-17 17:32:12 +0000771 DCheckIndexToBssMapping(
772 this, header->method_ids_size_, static_cast<size_t>(pointer_size), method_bss_mapping);
773 DCheckIndexToBssMapping(
774 this, header->type_ids_size_, sizeof(GcRoot<mirror::Class>), type_bss_mapping);
775 DCheckIndexToBssMapping(
776 this, header->string_ids_size_, sizeof(GcRoot<mirror::String>), string_bss_mapping);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100777
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700778 std::string canonical_location =
779 DexFileLoader::GetDexCanonicalLocation(dex_file_location.c_str());
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100780
781 // Create the OatDexFile and add it to the owning container.
Vladimir Marko539690a2014-06-05 18:36:42 +0100782 OatDexFile* oat_dex_file = new OatDexFile(this,
783 dex_file_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100784 canonical_location,
Vladimir Marko539690a2014-06-05 18:36:42 +0100785 dex_file_checksum,
786 dex_file_pointer,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300787 lookup_table_data,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100788 method_bss_mapping,
Vladimir Markof3c52b42017-11-17 17:32:12 +0000789 type_bss_mapping,
790 string_bss_mapping,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000791 class_offsets_pointer,
Mathieu Chartier120aa282017-08-05 16:03:03 -0700792 dex_layout_sections);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100793 oat_dex_files_storage_.push_back(oat_dex_file);
794
795 // Add the location and canonical location (if different) to the oat_dex_files_ table.
Vladimir Marko3f5838d2014-08-07 18:07:18 +0100796 StringPiece key(oat_dex_file->GetDexFileLocation());
Vladimir Marko539690a2014-06-05 18:36:42 +0100797 oat_dex_files_.Put(key, oat_dex_file);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100798 if (canonical_location != dex_file_location) {
799 StringPiece canonical_key(oat_dex_file->GetCanonicalDexFileLocation());
800 oat_dex_files_.Put(canonical_key, oat_dex_file);
801 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700802 }
Vladimir Marko09d09432015-09-08 13:47:48 +0100803
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100804 if (boot_image_tables != nullptr) {
Vladimir Marko667585a2017-09-29 10:42:31 +0100805 Runtime* runtime = Runtime::Current();
806 if (UNLIKELY(runtime == nullptr)) {
807 // This must be oatdump without boot image. Make sure the .bss is inaccessible.
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700808 CheckedCall(mprotect, "protect bss", const_cast<uint8_t*>(BssBegin()), BssSize(), PROT_NONE);
Vladimir Marko667585a2017-09-29 10:42:31 +0100809 } else {
810 // Map boot image tables into the .bss. The reserved size must match size of the tables.
811 size_t reserved_size = static_cast<size_t>(boot_image_tables_end - boot_image_tables);
812 size_t tables_size = 0u;
813 for (gc::space::ImageSpace* space : runtime->GetHeap()->GetBootImageSpaces()) {
814 tables_size += space->GetImageHeader().GetBootImageConstantTablesSize();
815 DCHECK_ALIGNED(tables_size, kPageSize);
816 }
817 if (tables_size != reserved_size) {
818 *error_msg = StringPrintf("In oat file '%s' found unexpected boot image table sizes, "
819 " %zu bytes, should be %zu.",
820 GetLocation().c_str(),
821 reserved_size,
822 tables_size);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100823 return false;
824 }
Vladimir Marko667585a2017-09-29 10:42:31 +0100825 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
826 uint32_t current_tables_size = space->GetImageHeader().GetBootImageConstantTablesSize();
827 if (current_tables_size != 0u && !MapConstantTables(space, boot_image_tables)) {
828 return false;
829 }
830 boot_image_tables += current_tables_size;
831 }
832 DCHECK(boot_image_tables == boot_image_tables_end);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100833 }
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100834 }
Brian Carlstromf1b30302013-03-28 10:35:32 -0700835 return true;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700836}
837
Andreas Gampe049cff02015-12-01 23:27:12 -0800838////////////////////////
839// OatFile via dlopen //
840////////////////////////
841
Andreas Gampe049cff02015-12-01 23:27:12 -0800842class DlOpenOatFile FINAL : public OatFileBase {
843 public:
844 DlOpenOatFile(const std::string& filename, bool executable)
845 : OatFileBase(filename, executable),
846 dlopen_handle_(nullptr),
Richard Uhlera206c742016-05-24 15:04:22 -0700847 shared_objects_before_(0) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800848 }
849
850 ~DlOpenOatFile() {
851 if (dlopen_handle_ != nullptr) {
Richard Uhlera206c742016-05-24 15:04:22 -0700852 if (!kIsTargetBuild) {
853 MutexLock mu(Thread::Current(), *Locks::host_dlopen_handles_lock_);
854 host_dlopen_handles_.erase(dlopen_handle_);
Mathieu Chartierc7d3f4b2016-06-01 10:48:19 -0700855 dlclose(dlopen_handle_);
856 } else {
857 dlclose(dlopen_handle_);
Richard Uhlera206c742016-05-24 15:04:22 -0700858 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800859 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800860 }
861
862 protected:
863 const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
864 std::string* error_msg) const OVERRIDE {
865 const uint8_t* ptr =
866 reinterpret_cast<const uint8_t*>(dlsym(dlopen_handle_, symbol_name.c_str()));
867 if (ptr == nullptr) {
868 *error_msg = dlerror();
869 }
870 return ptr;
871 }
872
Andreas Gampe4075f832016-05-18 13:09:54 -0700873 void PreLoad() OVERRIDE;
874
Andreas Gampe049cff02015-12-01 23:27:12 -0800875 bool Load(const std::string& elf_filename,
876 uint8_t* oat_file_begin,
877 bool writable,
878 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800879 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800880 std::string* error_msg) OVERRIDE;
881
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700882 bool Load(int, uint8_t*, bool, bool, bool, std::string*) {
883 return false;
884 }
885
Andreas Gampe049cff02015-12-01 23:27:12 -0800886 // Ask the linker where it mmaped the file and notify our mmap wrapper of the regions.
887 void PreSetup(const std::string& elf_filename) OVERRIDE;
888
889 private:
890 bool Dlopen(const std::string& elf_filename,
891 uint8_t* oat_file_begin,
892 std::string* error_msg);
893
Richard Uhlera206c742016-05-24 15:04:22 -0700894 // On the host, if the same library is loaded again with dlopen the same
895 // file handle is returned. This differs from the behavior of dlopen on the
896 // target, where dlopen reloads the library at a different address every
897 // time you load it. The runtime relies on the target behavior to ensure
898 // each instance of the loaded library has a unique dex cache. To avoid
899 // problems, we fall back to our own linker in the case when the same
900 // library is opened multiple times on host. dlopen_handles_ is used to
901 // detect that case.
902 // Guarded by host_dlopen_handles_lock_;
903 static std::unordered_set<void*> host_dlopen_handles_;
904
Andreas Gampe049cff02015-12-01 23:27:12 -0800905 // dlopen handle during runtime.
906 void* dlopen_handle_; // TODO: Unique_ptr with custom deleter.
907
908 // Dummy memory map objects corresponding to the regions mapped by dlopen.
909 std::vector<std::unique_ptr<MemMap>> dlopen_mmaps_;
910
Andreas Gampe4075f832016-05-18 13:09:54 -0700911 // The number of shared objects the linker told us about before loading. Used to
912 // (optimistically) optimize the PreSetup stage (see comment there).
913 size_t shared_objects_before_;
914
Andreas Gampe049cff02015-12-01 23:27:12 -0800915 DISALLOW_COPY_AND_ASSIGN(DlOpenOatFile);
916};
917
Richard Uhlera206c742016-05-24 15:04:22 -0700918std::unordered_set<void*> DlOpenOatFile::host_dlopen_handles_;
919
Andreas Gampe4075f832016-05-18 13:09:54 -0700920void DlOpenOatFile::PreLoad() {
921#ifdef __APPLE__
Andreas Gampe39004a62016-05-18 21:27:00 -0700922 UNUSED(shared_objects_before_);
Andreas Gampe4075f832016-05-18 13:09:54 -0700923 LOG(FATAL) << "Should not reach here.";
924 UNREACHABLE();
925#else
926 // Count the entries in dl_iterate_phdr we get at this point in time.
927 struct dl_iterate_context {
928 static int callback(struct dl_phdr_info *info ATTRIBUTE_UNUSED,
929 size_t size ATTRIBUTE_UNUSED,
930 void *data) {
931 reinterpret_cast<dl_iterate_context*>(data)->count++;
932 return 0; // Continue iteration.
933 }
934 size_t count = 0;
935 } context;
936
937 dl_iterate_phdr(dl_iterate_context::callback, &context);
938 shared_objects_before_ = context.count;
939#endif
940}
941
Andreas Gampe049cff02015-12-01 23:27:12 -0800942bool DlOpenOatFile::Load(const std::string& elf_filename,
943 uint8_t* oat_file_begin,
944 bool writable,
945 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800946 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800947 std::string* error_msg) {
948 // Use dlopen only when flagged to do so, and when it's OK to load things executable.
949 // TODO: Also try when not executable? The issue here could be re-mapping as writable (as
950 // !executable is a sign that we may want to patch), which may not be allowed for
951 // various reasons.
952 if (!kUseDlopen) {
953 *error_msg = "DlOpen is disabled.";
954 return false;
955 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800956 if (low_4gb) {
957 *error_msg = "DlOpen does not support low 4gb loading.";
958 return false;
959 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800960 if (writable) {
961 *error_msg = "DlOpen does not support writable loading.";
962 return false;
963 }
964 if (!executable) {
965 *error_msg = "DlOpen does not support non-executable loading.";
966 return false;
967 }
968
969 // dlopen always returns the same library if it is already opened on the host. For this reason
970 // we only use dlopen if we are the target or we do not already have the dex file opened. Having
971 // the same library loaded multiple times at different addresses is required for class unloading
972 // and for having dex caches arrays in the .bss section.
973 if (!kIsTargetBuild) {
974 if (!kUseDlopenOnHost) {
975 *error_msg = "DlOpen disabled for host.";
976 return false;
977 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800978 }
979
980 bool success = Dlopen(elf_filename, oat_file_begin, error_msg);
981 DCHECK(dlopen_handle_ != nullptr || !success);
982
983 return success;
984}
985
986bool DlOpenOatFile::Dlopen(const std::string& elf_filename,
987 uint8_t* oat_file_begin,
988 std::string* error_msg) {
989#ifdef __APPLE__
990 // The dl_iterate_phdr syscall is missing. There is similar API on OSX,
991 // but let's fallback to the custom loading code for the time being.
992 UNUSED(elf_filename, oat_file_begin);
993 *error_msg = "Dlopen unsupported on Mac.";
994 return false;
995#else
996 {
997 UniqueCPtr<char> absolute_path(realpath(elf_filename.c_str(), nullptr));
998 if (absolute_path == nullptr) {
999 *error_msg = StringPrintf("Failed to find absolute path for '%s'", elf_filename.c_str());
1000 return false;
1001 }
Bilyan Borisovbb661c02016-04-04 16:27:32 +01001002#ifdef ART_TARGET_ANDROID
Anton Kirilov3a2e78e2017-01-06 13:33:42 +00001003 android_dlextinfo extinfo = {};
Andreas Gampe049cff02015-12-01 23:27:12 -08001004 extinfo.flags = ANDROID_DLEXT_FORCE_LOAD | // Force-load, don't reuse handle
1005 // (open oat files multiple
1006 // times).
1007 ANDROID_DLEXT_FORCE_FIXED_VADDR; // Take a non-zero vaddr as absolute
1008 // (non-pic boot image).
Andreas Gampe226b91e2015-12-02 10:29:33 -08001009 if (oat_file_begin != nullptr) { //
1010 extinfo.flags |= ANDROID_DLEXT_LOAD_AT_FIXED_ADDRESS; // Use the requested addr if
1011 extinfo.reserved_addr = oat_file_begin; // vaddr = 0.
1012 } // (pic boot image).
Andreas Gampe049cff02015-12-01 23:27:12 -08001013 dlopen_handle_ = android_dlopen_ext(absolute_path.get(), RTLD_NOW, &extinfo);
1014#else
Andreas Gampe049cff02015-12-01 23:27:12 -08001015 UNUSED(oat_file_begin);
Julien Duraj1af0c4f2016-11-16 14:05:48 +00001016 static_assert(!kIsTargetBuild || kIsTargetLinux, "host_dlopen_handles_ will leak handles");
Mathieu Chartierc7d3f4b2016-06-01 10:48:19 -07001017 MutexLock mu(Thread::Current(), *Locks::host_dlopen_handles_lock_);
Richard Uhlera206c742016-05-24 15:04:22 -07001018 dlopen_handle_ = dlopen(absolute_path.get(), RTLD_NOW);
1019 if (dlopen_handle_ != nullptr) {
Richard Uhlera206c742016-05-24 15:04:22 -07001020 if (!host_dlopen_handles_.insert(dlopen_handle_).second) {
1021 dlclose(dlopen_handle_);
1022 dlopen_handle_ = nullptr;
1023 *error_msg = StringPrintf("host dlopen re-opened '%s'", elf_filename.c_str());
1024 return false;
1025 }
1026 }
Bilyan Borisovbb661c02016-04-04 16:27:32 +01001027#endif // ART_TARGET_ANDROID
Andreas Gampe049cff02015-12-01 23:27:12 -08001028 }
1029 if (dlopen_handle_ == nullptr) {
1030 *error_msg = StringPrintf("Failed to dlopen '%s': %s", elf_filename.c_str(), dlerror());
1031 return false;
1032 }
1033 return true;
1034#endif
1035}
1036
1037void DlOpenOatFile::PreSetup(const std::string& elf_filename) {
Andreas Gampe74f07b52015-12-02 11:53:26 -08001038#ifdef __APPLE__
1039 UNUSED(elf_filename);
1040 LOG(FATAL) << "Should not reach here.";
1041 UNREACHABLE();
1042#else
Andreas Gampe049cff02015-12-01 23:27:12 -08001043 struct dl_iterate_context {
1044 static int callback(struct dl_phdr_info *info, size_t /* size */, void *data) {
1045 auto* context = reinterpret_cast<dl_iterate_context*>(data);
Andreas Gampe4075f832016-05-18 13:09:54 -07001046 context->shared_objects_seen++;
1047 if (context->shared_objects_seen < context->shared_objects_before) {
1048 // We haven't been called yet for anything we haven't seen before. Just continue.
1049 // Note: this is aggressively optimistic. If another thread was unloading a library,
1050 // we may miss out here. However, this does not happen often in practice.
1051 return 0;
1052 }
1053
Andreas Gampe049cff02015-12-01 23:27:12 -08001054 // See whether this callback corresponds to the file which we have just loaded.
1055 bool contains_begin = false;
1056 for (int i = 0; i < info->dlpi_phnum; i++) {
1057 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
1058 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
1059 info->dlpi_phdr[i].p_vaddr);
1060 size_t memsz = info->dlpi_phdr[i].p_memsz;
1061 if (vaddr <= context->begin_ && context->begin_ < vaddr + memsz) {
1062 contains_begin = true;
1063 break;
1064 }
1065 }
1066 }
1067 // Add dummy mmaps for this file.
1068 if (contains_begin) {
1069 for (int i = 0; i < info->dlpi_phnum; i++) {
1070 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
1071 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
1072 info->dlpi_phdr[i].p_vaddr);
1073 size_t memsz = info->dlpi_phdr[i].p_memsz;
1074 MemMap* mmap = MemMap::MapDummy(info->dlpi_name, vaddr, memsz);
1075 context->dlopen_mmaps_->push_back(std::unique_ptr<MemMap>(mmap));
1076 }
1077 }
1078 return 1; // Stop iteration and return 1 from dl_iterate_phdr.
1079 }
1080 return 0; // Continue iteration and return 0 from dl_iterate_phdr when finished.
1081 }
1082 const uint8_t* const begin_;
1083 std::vector<std::unique_ptr<MemMap>>* const dlopen_mmaps_;
Andreas Gampe4075f832016-05-18 13:09:54 -07001084 const size_t shared_objects_before;
1085 size_t shared_objects_seen;
1086 };
1087 dl_iterate_context context = { Begin(), &dlopen_mmaps_, shared_objects_before_, 0};
Andreas Gampe049cff02015-12-01 23:27:12 -08001088
1089 if (dl_iterate_phdr(dl_iterate_context::callback, &context) == 0) {
Andreas Gampe4075f832016-05-18 13:09:54 -07001090 // Hm. Maybe our optimization went wrong. Try another time with shared_objects_before == 0
1091 // before giving up. This should be unusual.
1092 VLOG(oat) << "Need a second run in PreSetup, didn't find with shared_objects_before="
1093 << shared_objects_before_;
1094 dl_iterate_context context0 = { Begin(), &dlopen_mmaps_, 0, 0};
1095 if (dl_iterate_phdr(dl_iterate_context::callback, &context0) == 0) {
1096 // OK, give up and print an error.
Andreas Gampe170331f2017-12-07 18:41:03 -08001097 PrintFileToLog("/proc/self/maps", android::base::LogSeverity::WARNING);
Andreas Gampe4075f832016-05-18 13:09:54 -07001098 LOG(ERROR) << "File " << elf_filename << " loaded with dlopen but cannot find its mmaps.";
1099 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001100 }
Andreas Gampe74f07b52015-12-02 11:53:26 -08001101#endif
Andreas Gampe049cff02015-12-01 23:27:12 -08001102}
1103
1104////////////////////////////////////////////////
1105// OatFile via our own ElfFile implementation //
1106////////////////////////////////////////////////
1107
1108class ElfOatFile FINAL : public OatFileBase {
1109 public:
1110 ElfOatFile(const std::string& filename, bool executable) : OatFileBase(filename, executable) {}
1111
1112 static ElfOatFile* OpenElfFile(File* file,
1113 const std::string& location,
1114 uint8_t* requested_base,
1115 uint8_t* oat_file_begin, // Override base if not null
1116 bool writable,
1117 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001118 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001119 const char* abs_dex_location,
1120 std::string* error_msg);
1121
1122 bool InitializeFromElfFile(ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +01001123 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001124 const char* abs_dex_location,
1125 std::string* error_msg);
1126
1127 protected:
1128 const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
1129 std::string* error_msg) const OVERRIDE {
1130 const uint8_t* ptr = elf_file_->FindDynamicSymbolAddress(symbol_name);
1131 if (ptr == nullptr) {
1132 *error_msg = "(Internal implementation could not find symbol)";
1133 }
1134 return ptr;
1135 }
1136
Andreas Gampe4075f832016-05-18 13:09:54 -07001137 void PreLoad() OVERRIDE {
1138 }
1139
Andreas Gampe049cff02015-12-01 23:27:12 -08001140 bool Load(const std::string& elf_filename,
1141 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1142 bool writable,
1143 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001144 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001145 std::string* error_msg) OVERRIDE;
1146
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001147 bool Load(int oat_fd,
1148 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1149 bool writable,
1150 bool executable,
1151 bool low_4gb,
1152 std::string* error_msg) OVERRIDE;
1153
Andreas Gampe049cff02015-12-01 23:27:12 -08001154 void PreSetup(const std::string& elf_filename ATTRIBUTE_UNUSED) OVERRIDE {
1155 }
1156
1157 private:
1158 bool ElfFileOpen(File* file,
1159 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1160 bool writable,
1161 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001162 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001163 std::string* error_msg);
1164
1165 private:
1166 // Backing memory map for oat file during cross compilation.
1167 std::unique_ptr<ElfFile> elf_file_;
1168
1169 DISALLOW_COPY_AND_ASSIGN(ElfOatFile);
1170};
1171
1172ElfOatFile* ElfOatFile::OpenElfFile(File* file,
1173 const std::string& location,
1174 uint8_t* requested_base,
1175 uint8_t* oat_file_begin, // Override base if not null
1176 bool writable,
1177 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001178 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001179 const char* abs_dex_location,
1180 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001181 ScopedTrace trace("Open elf file " + location);
Andreas Gampe049cff02015-12-01 23:27:12 -08001182 std::unique_ptr<ElfOatFile> oat_file(new ElfOatFile(location, executable));
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001183 bool success = oat_file->ElfFileOpen(file,
1184 oat_file_begin,
1185 writable,
1186 low_4gb,
1187 executable,
1188 error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -08001189 if (!success) {
1190 CHECK(!error_msg->empty());
1191 return nullptr;
1192 }
1193
1194 // Complete the setup.
1195 if (!oat_file->ComputeFields(requested_base, file->GetPath(), error_msg)) {
1196 return nullptr;
1197 }
1198
1199 if (!oat_file->Setup(abs_dex_location, error_msg)) {
1200 return nullptr;
1201 }
1202
1203 return oat_file.release();
1204}
1205
1206bool ElfOatFile::InitializeFromElfFile(ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +01001207 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001208 const char* abs_dex_location,
1209 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001210 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -08001211 if (IsExecutable()) {
1212 *error_msg = "Cannot initialize from elf file in executable mode.";
1213 return false;
1214 }
1215 elf_file_.reset(elf_file);
David Brazdilc93b3be2016-09-12 18:49:58 +01001216 SetVdex(vdex_file);
Andreas Gampe049cff02015-12-01 23:27:12 -08001217 uint64_t offset, size;
1218 bool has_section = elf_file->GetSectionOffsetAndSize(".rodata", &offset, &size);
1219 CHECK(has_section);
1220 SetBegin(elf_file->Begin() + offset);
1221 SetEnd(elf_file->Begin() + size + offset);
1222 // Ignore the optional .bss section when opening non-executable.
1223 return Setup(abs_dex_location, error_msg);
1224}
1225
1226bool ElfOatFile::Load(const std::string& elf_filename,
1227 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1228 bool writable,
1229 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001230 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001231 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001232 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -08001233 std::unique_ptr<File> file(OS::OpenFileForReading(elf_filename.c_str()));
1234 if (file == nullptr) {
1235 *error_msg = StringPrintf("Failed to open oat filename for reading: %s", strerror(errno));
1236 return false;
1237 }
1238 return ElfOatFile::ElfFileOpen(file.get(),
1239 oat_file_begin,
1240 writable,
1241 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001242 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001243 error_msg);
1244}
1245
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001246bool ElfOatFile::Load(int oat_fd,
1247 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1248 bool writable,
1249 bool executable,
1250 bool low_4gb,
1251 std::string* error_msg) {
1252 ScopedTrace trace(__PRETTY_FUNCTION__);
1253 if (oat_fd != -1) {
1254 std::unique_ptr<File> file = std::make_unique<File>(oat_fd, false);
1255 file->DisableAutoClose();
1256 if (file == nullptr) {
1257 *error_msg = StringPrintf("Failed to open oat filename for reading: %s",
1258 strerror(errno));
1259 return false;
1260 }
1261 return ElfOatFile::ElfFileOpen(file.get(),
1262 oat_file_begin,
1263 writable,
1264 executable,
1265 low_4gb,
1266 error_msg);
1267 }
1268 return false;
1269}
1270
Andreas Gampe049cff02015-12-01 23:27:12 -08001271bool ElfOatFile::ElfFileOpen(File* file,
1272 uint8_t* oat_file_begin,
1273 bool writable,
1274 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001275 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001276 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001277 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -08001278 // TODO: rename requested_base to oat_data_begin
1279 elf_file_.reset(ElfFile::Open(file,
1280 writable,
1281 /*program_header_only*/true,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001282 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001283 error_msg,
1284 oat_file_begin));
1285 if (elf_file_ == nullptr) {
1286 DCHECK(!error_msg->empty());
1287 return false;
1288 }
Brian Carlstromf5b0f2c2016-10-14 01:04:26 -07001289 bool loaded = elf_file_->Load(file, executable, low_4gb, error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -08001290 DCHECK(loaded || !error_msg->empty());
1291 return loaded;
1292}
1293
1294//////////////////////////
1295// General OatFile code //
1296//////////////////////////
1297
1298std::string OatFile::ResolveRelativeEncodedDexLocation(
1299 const char* abs_dex_location, const std::string& rel_dex_location) {
1300 if (abs_dex_location != nullptr && rel_dex_location[0] != '/') {
1301 // Strip :classes<N>.dex used for secondary multidex files.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001302 std::string base = DexFileLoader::GetBaseLocation(rel_dex_location);
1303 std::string multidex_suffix = DexFileLoader::GetMultiDexSuffix(rel_dex_location);
Andreas Gampe049cff02015-12-01 23:27:12 -08001304
1305 // Check if the base is a suffix of the provided abs_dex_location.
1306 std::string target_suffix = "/" + base;
1307 std::string abs_location(abs_dex_location);
1308 if (abs_location.size() > target_suffix.size()) {
1309 size_t pos = abs_location.size() - target_suffix.size();
1310 if (abs_location.compare(pos, std::string::npos, target_suffix) == 0) {
1311 return abs_location + multidex_suffix;
1312 }
1313 }
1314 }
1315 return rel_dex_location;
1316}
1317
1318static void CheckLocation(const std::string& location) {
1319 CHECK(!location.empty());
1320}
1321
1322OatFile* OatFile::OpenWithElfFile(ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +01001323 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001324 const std::string& location,
1325 const char* abs_dex_location,
1326 std::string* error_msg) {
1327 std::unique_ptr<ElfOatFile> oat_file(new ElfOatFile(location, false /* executable */));
David Brazdilc93b3be2016-09-12 18:49:58 +01001328 return oat_file->InitializeFromElfFile(elf_file, vdex_file, abs_dex_location, error_msg)
Andreas Gampe049cff02015-12-01 23:27:12 -08001329 ? oat_file.release()
1330 : nullptr;
1331}
1332
David Brazdil7b49e6c2016-09-01 11:06:18 +01001333OatFile* OatFile::Open(const std::string& oat_filename,
1334 const std::string& oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001335 uint8_t* requested_base,
1336 uint8_t* oat_file_begin,
1337 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001338 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001339 const char* abs_dex_location,
1340 std::string* error_msg) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001341 ScopedTrace trace("Open oat file " + oat_location);
1342 CHECK(!oat_filename.empty()) << oat_location;
1343 CheckLocation(oat_location);
Andreas Gampe54315c72016-05-18 21:10:42 -07001344
Calin Juravle367b9d82017-05-15 18:18:39 -07001345 std::string vdex_filename = GetVdexFilename(oat_filename);
David Brazdil7b49e6c2016-09-01 11:06:18 +01001346
1347 // Check that the files even exist, fast-fail.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001348 if (!OS::FileExists(vdex_filename.c_str())) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001349 *error_msg = StringPrintf("File %s does not exist.", vdex_filename.c_str());
1350 return nullptr;
1351 } else if (!OS::FileExists(oat_filename.c_str())) {
1352 *error_msg = StringPrintf("File %s does not exist.", oat_filename.c_str());
Andreas Gampe54315c72016-05-18 21:10:42 -07001353 return nullptr;
1354 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001355
1356 // Try dlopen first, as it is required for native debuggability. This will fail fast if dlopen is
1357 // disabled.
David Brazdil7b49e6c2016-09-01 11:06:18 +01001358 OatFile* with_dlopen = OatFileBase::OpenOatFile<DlOpenOatFile>(vdex_filename,
1359 oat_filename,
1360 oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001361 requested_base,
1362 oat_file_begin,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001363 false /* writable */,
Andreas Gampe049cff02015-12-01 23:27:12 -08001364 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001365 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001366 abs_dex_location,
1367 error_msg);
1368 if (with_dlopen != nullptr) {
1369 return with_dlopen;
1370 }
1371 if (kPrintDlOpenErrorMessage) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001372 LOG(ERROR) << "Failed to dlopen: " << oat_filename << " with error " << *error_msg;
Andreas Gampe049cff02015-12-01 23:27:12 -08001373 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001374 // If we aren't trying to execute, we just use our own ElfFile loader for a couple reasons:
1375 //
1376 // On target, dlopen may fail when compiling due to selinux restrictions on installd.
1377 //
1378 // We use our own ELF loader for Quick to deal with legacy apps that
1379 // open a generated dex file by name, remove the file, then open
1380 // another generated dex file with the same name. http://b/10614658
1381 //
1382 // On host, dlopen is expected to fail when cross compiling, so fall back to OpenElfFile.
1383 //
1384 //
1385 // Another independent reason is the absolute placement of boot.oat. dlopen on the host usually
1386 // 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 +01001387 OatFile* with_internal = OatFileBase::OpenOatFile<ElfOatFile>(vdex_filename,
1388 oat_filename,
1389 oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001390 requested_base,
1391 oat_file_begin,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001392 false /* writable */,
Andreas Gampe049cff02015-12-01 23:27:12 -08001393 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001394 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001395 abs_dex_location,
1396 error_msg);
1397 return with_internal;
1398}
1399
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001400OatFile* OatFile::Open(int vdex_fd,
1401 int oat_fd,
1402 const std::string& oat_location,
1403 uint8_t* requested_base,
1404 uint8_t* oat_file_begin,
1405 bool executable,
1406 bool low_4gb,
1407 const char* abs_dex_location,
1408 std::string* error_msg) {
1409 CHECK(!oat_location.empty()) << oat_location;
1410
1411 std::string vdex_location = GetVdexFilename(oat_location);
1412
1413 OatFile* with_internal = OatFileBase::OpenOatFile<ElfOatFile>(vdex_fd,
1414 oat_fd,
1415 vdex_location,
1416 oat_location,
1417 requested_base,
1418 oat_file_begin,
1419 false /* writable */,
1420 executable,
1421 low_4gb,
1422 abs_dex_location,
1423 error_msg);
1424 return with_internal;
1425}
1426
Andreas Gampe049cff02015-12-01 23:27:12 -08001427OatFile* OatFile::OpenWritable(File* file,
1428 const std::string& location,
1429 const char* abs_dex_location,
1430 std::string* error_msg) {
1431 CheckLocation(location);
1432 return ElfOatFile::OpenElfFile(file,
1433 location,
1434 nullptr,
1435 nullptr,
1436 true,
1437 false,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001438 /*low_4gb*/false,
Andreas Gampe049cff02015-12-01 23:27:12 -08001439 abs_dex_location,
1440 error_msg);
1441}
1442
1443OatFile* OatFile::OpenReadable(File* file,
1444 const std::string& location,
1445 const char* abs_dex_location,
1446 std::string* error_msg) {
1447 CheckLocation(location);
1448 return ElfOatFile::OpenElfFile(file,
1449 location,
1450 nullptr,
1451 nullptr,
1452 false,
1453 false,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001454 /*low_4gb*/false,
Andreas Gampe049cff02015-12-01 23:27:12 -08001455 abs_dex_location,
1456 error_msg);
1457}
1458
1459OatFile::OatFile(const std::string& location, bool is_executable)
1460 : location_(location),
David Brazdil7b49e6c2016-09-01 11:06:18 +01001461 vdex_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001462 begin_(nullptr),
1463 end_(nullptr),
1464 bss_begin_(nullptr),
1465 bss_end_(nullptr),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001466 bss_methods_(nullptr),
Vladimir Markoaad75c62016-10-03 08:46:48 +00001467 bss_roots_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001468 is_executable_(is_executable),
David Srbeckyec2cdf42017-12-08 16:21:25 +00001469 vdex_begin_(nullptr),
1470 vdex_end_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001471 secondary_lookup_lock_("OatFile secondary lookup lock", kOatFileSecondaryLookupLock) {
1472 CHECK(!location_.empty());
1473}
1474
1475OatFile::~OatFile() {
1476 STLDeleteElements(&oat_dex_files_storage_);
1477}
1478
Brian Carlstrome24fa612011-09-29 00:53:55 -07001479const OatHeader& OatFile::GetOatHeader() const {
Ian Rogers30fab402012-01-23 15:43:46 -08001480 return *reinterpret_cast<const OatHeader*>(Begin());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001481}
1482
Ian Rogers13735952014-10-08 12:43:28 -07001483const uint8_t* OatFile::Begin() const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001484 CHECK(begin_ != nullptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001485 return begin_;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001486}
1487
Ian Rogers13735952014-10-08 12:43:28 -07001488const uint8_t* OatFile::End() const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001489 CHECK(end_ != nullptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001490 return end_;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001491}
1492
Vladimir Marko5c42c292015-02-25 12:02:49 +00001493const uint8_t* OatFile::BssBegin() const {
1494 return bss_begin_;
1495}
1496
1497const uint8_t* OatFile::BssEnd() const {
1498 return bss_end_;
1499}
1500
David Srbeckyec2cdf42017-12-08 16:21:25 +00001501const uint8_t* OatFile::VdexBegin() const {
1502 return vdex_begin_;
1503}
1504
1505const uint8_t* OatFile::VdexEnd() const {
1506 return vdex_end_;
1507}
1508
David Brazdil7b49e6c2016-09-01 11:06:18 +01001509const uint8_t* OatFile::DexBegin() const {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001510 return vdex_->Begin();
David Brazdil7b49e6c2016-09-01 11:06:18 +01001511}
1512
1513const uint8_t* OatFile::DexEnd() const {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001514 return vdex_->End();
David Brazdil7b49e6c2016-09-01 11:06:18 +01001515}
1516
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001517ArrayRef<ArtMethod*> OatFile::GetBssMethods() const {
1518 if (bss_methods_ != nullptr) {
1519 ArtMethod** methods = reinterpret_cast<ArtMethod**>(bss_methods_);
1520 ArtMethod** methods_end =
1521 reinterpret_cast<ArtMethod**>(bss_roots_ != nullptr ? bss_roots_ : bss_end_);
1522 return ArrayRef<ArtMethod*>(methods, methods_end - methods);
1523 } else {
1524 return ArrayRef<ArtMethod*>();
1525 }
1526}
1527
Vladimir Markoaad75c62016-10-03 08:46:48 +00001528ArrayRef<GcRoot<mirror::Object>> OatFile::GetBssGcRoots() const {
1529 if (bss_roots_ != nullptr) {
1530 auto* roots = reinterpret_cast<GcRoot<mirror::Object>*>(bss_roots_);
1531 auto* roots_end = reinterpret_cast<GcRoot<mirror::Object>*>(bss_end_);
1532 return ArrayRef<GcRoot<mirror::Object>>(roots, roots_end - roots);
1533 } else {
1534 return ArrayRef<GcRoot<mirror::Object>>();
1535 }
1536}
1537
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001538const OatFile::OatDexFile* OatFile::GetOatDexFile(const char* dex_location,
1539 const uint32_t* dex_location_checksum,
Richard Uhler9a37efc2016-08-05 16:32:55 -07001540 std::string* error_msg) const {
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001541 // NOTE: We assume here that the canonical location for a given dex_location never
1542 // changes. If it does (i.e. some symlink used by the filename changes) we may return
1543 // an incorrect OatDexFile. As long as we have a checksum to check, we shall return
1544 // an identical file or fail; otherwise we may see some unpredictable failures.
Calin Juravle4e1d5792014-07-15 23:56:47 +01001545
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001546 // TODO: Additional analysis of usage patterns to see if this can be simplified
1547 // without any performance loss, for example by not doing the first lock-free lookup.
1548
1549 const OatFile::OatDexFile* oat_dex_file = nullptr;
1550 StringPiece key(dex_location);
1551 // Try to find the key cheaply in the oat_dex_files_ map which holds dex locations
1552 // directly mentioned in the oat file and doesn't require locking.
1553 auto primary_it = oat_dex_files_.find(key);
1554 if (primary_it != oat_dex_files_.end()) {
1555 oat_dex_file = primary_it->second;
1556 DCHECK(oat_dex_file != nullptr);
1557 } else {
1558 // This dex_location is not one of the dex locations directly mentioned in the
1559 // oat file. The correct lookup is via the canonical location but first see in
1560 // the secondary_oat_dex_files_ whether we've looked up this location before.
1561 MutexLock mu(Thread::Current(), secondary_lookup_lock_);
1562 auto secondary_lb = secondary_oat_dex_files_.lower_bound(key);
1563 if (secondary_lb != secondary_oat_dex_files_.end() && key == secondary_lb->first) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001564 oat_dex_file = secondary_lb->second; // May be null.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001565 } else {
1566 // We haven't seen this dex_location before, we must check the canonical location.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001567 std::string dex_canonical_location = DexFileLoader::GetDexCanonicalLocation(dex_location);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001568 if (dex_canonical_location != dex_location) {
1569 StringPiece canonical_key(dex_canonical_location);
1570 auto canonical_it = oat_dex_files_.find(canonical_key);
1571 if (canonical_it != oat_dex_files_.end()) {
1572 oat_dex_file = canonical_it->second;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001573 } // else keep null.
1574 } // else keep null.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001575
1576 // Copy the key to the string_cache_ and store the result in secondary map.
1577 string_cache_.emplace_back(key.data(), key.length());
1578 StringPiece key_copy(string_cache_.back());
1579 secondary_oat_dex_files_.PutBefore(secondary_lb, key_copy, oat_dex_file);
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001580 }
1581 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001582
1583 if (oat_dex_file == nullptr) {
1584 if (error_msg != nullptr) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001585 std::string dex_canonical_location = DexFileLoader::GetDexCanonicalLocation(dex_location);
Richard Uhler9a37efc2016-08-05 16:32:55 -07001586 *error_msg = "Failed to find OatDexFile for DexFile " + std::string(dex_location)
1587 + " (canonical path " + dex_canonical_location + ") in OatFile " + GetLocation();
1588 }
1589 return nullptr;
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001590 }
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001591
Richard Uhler9a37efc2016-08-05 16:32:55 -07001592 if (dex_location_checksum != nullptr &&
1593 oat_dex_file->GetDexFileLocationChecksum() != *dex_location_checksum) {
1594 if (error_msg != nullptr) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001595 std::string dex_canonical_location = DexFileLoader::GetDexCanonicalLocation(dex_location);
Richard Uhler9a37efc2016-08-05 16:32:55 -07001596 std::string checksum = StringPrintf("0x%08x", oat_dex_file->GetDexFileLocationChecksum());
1597 std::string required_checksum = StringPrintf("0x%08x", *dex_location_checksum);
1598 *error_msg = "OatDexFile for DexFile " + std::string(dex_location)
1599 + " (canonical path " + dex_canonical_location + ") in OatFile " + GetLocation()
1600 + " has checksum " + checksum + " but " + required_checksum + " was required";
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001601 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001602 return nullptr;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001603 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001604 return oat_dex_file;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001605}
1606
Brian Carlstrome24fa612011-09-29 00:53:55 -07001607OatFile::OatDexFile::OatDexFile(const OatFile* oat_file,
Elliott Hughesaa6a5882012-01-13 19:39:16 -08001608 const std::string& dex_file_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001609 const std::string& canonical_dex_file_location,
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001610 uint32_t dex_file_location_checksum,
Ian Rogers13735952014-10-08 12:43:28 -07001611 const uint8_t* dex_file_pointer,
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001612 const uint8_t* lookup_table_data,
Vladimir Markof3c52b42017-11-17 17:32:12 +00001613 const IndexBssMapping* method_bss_mapping_data,
1614 const IndexBssMapping* type_bss_mapping_data,
1615 const IndexBssMapping* string_bss_mapping_data,
Vladimir Marko09d09432015-09-08 13:47:48 +01001616 const uint32_t* oat_class_offsets_pointer,
Mathieu Chartier120aa282017-08-05 16:03:03 -07001617 const DexLayoutSections* dex_layout_sections)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001618 : oat_file_(oat_file),
1619 dex_file_location_(dex_file_location),
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001620 canonical_dex_file_location_(canonical_dex_file_location),
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001621 dex_file_location_checksum_(dex_file_location_checksum),
Brian Carlstrom89521892011-12-07 22:05:07 -08001622 dex_file_pointer_(dex_file_pointer),
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001623 lookup_table_data_(lookup_table_data),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001624 method_bss_mapping_(method_bss_mapping_data),
Vladimir Markof3c52b42017-11-17 17:32:12 +00001625 type_bss_mapping_(type_bss_mapping_data),
1626 string_bss_mapping_(string_bss_mapping_data),
Vladimir Marko09d09432015-09-08 13:47:48 +01001627 oat_class_offsets_pointer_(oat_class_offsets_pointer),
Mathieu Chartier120aa282017-08-05 16:03:03 -07001628 dex_layout_sections_(dex_layout_sections) {
David Sehr9aa352e2016-09-15 18:13:52 -07001629 // Initialize TypeLookupTable.
1630 if (lookup_table_data_ != nullptr) {
1631 // Peek the number of classes from the DexFile.
1632 const DexFile::Header* dex_header = reinterpret_cast<const DexFile::Header*>(dex_file_pointer_);
1633 const uint32_t num_class_defs = dex_header->class_defs_size_;
1634 if (lookup_table_data_ + TypeLookupTable::RawDataLength(num_class_defs) > GetOatFile()->End()) {
1635 LOG(WARNING) << "found truncated lookup table in " << dex_file_location_;
1636 } else {
Mathieu Chartier1b868492016-11-16 16:22:37 -08001637 lookup_table_ = TypeLookupTable::Open(dex_file_pointer_, lookup_table_data_, num_class_defs);
David Sehr9aa352e2016-09-15 18:13:52 -07001638 }
1639 }
1640}
Brian Carlstrome24fa612011-09-29 00:53:55 -07001641
Mathieu Chartier1b868492016-11-16 16:22:37 -08001642OatFile::OatDexFile::OatDexFile(std::unique_ptr<TypeLookupTable>&& lookup_table)
1643 : lookup_table_(std::move(lookup_table)) {}
1644
Brian Carlstrome24fa612011-09-29 00:53:55 -07001645OatFile::OatDexFile::~OatDexFile() {}
1646
Ian Rogers05f28c62012-10-23 18:12:13 -07001647size_t OatFile::OatDexFile::FileSize() const {
1648 return reinterpret_cast<const DexFile::Header*>(dex_file_pointer_)->file_size_;
1649}
1650
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001651std::unique_ptr<const DexFile> OatFile::OatDexFile::OpenDexFile(std::string* error_msg) const {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001652 ScopedTrace trace(__PRETTY_FUNCTION__);
Aart Bik37d6a3b2016-06-21 18:30:10 -07001653 static constexpr bool kVerify = false;
1654 static constexpr bool kVerifyChecksum = false;
David Sehr013fd802018-01-11 22:55:24 -08001655 const ArtDexFileLoader dex_file_loader;
1656 return dex_file_loader.Open(dex_file_pointer_,
1657 FileSize(),
1658 dex_file_location_,
1659 dex_file_location_checksum_,
1660 this,
1661 kVerify,
1662 kVerifyChecksum,
1663 error_msg);
Brian Carlstrom89521892011-12-07 22:05:07 -08001664}
1665
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001666uint32_t OatFile::OatDexFile::GetOatClassOffset(uint16_t class_def_index) const {
1667 return oat_class_offsets_pointer_[class_def_index];
1668}
1669
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001670OatFile::OatClass OatFile::OatDexFile::GetOatClass(uint16_t class_def_index) const {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001671 uint32_t oat_class_offset = GetOatClassOffset(class_def_index);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001672
Ian Rogers13735952014-10-08 12:43:28 -07001673 const uint8_t* oat_class_pointer = oat_file_->Begin() + oat_class_offset;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001674 CHECK_LT(oat_class_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001675
Ian Rogers13735952014-10-08 12:43:28 -07001676 const uint8_t* status_pointer = oat_class_pointer;
Brian Carlstromba150c32013-08-27 17:31:03 -07001677 CHECK_LT(status_pointer, oat_file_->End()) << oat_file_->GetLocation();
Vladimir Marko2c64a832018-01-04 11:31:56 +00001678 ClassStatus status = enum_cast<ClassStatus>(*reinterpret_cast<const int16_t*>(status_pointer));
1679 CHECK_LE(status, ClassStatus::kLast);
Brian Carlstromba150c32013-08-27 17:31:03 -07001680
Ian Rogers13735952014-10-08 12:43:28 -07001681 const uint8_t* type_pointer = status_pointer + sizeof(uint16_t);
Brian Carlstromba150c32013-08-27 17:31:03 -07001682 CHECK_LT(type_pointer, oat_file_->End()) << oat_file_->GetLocation();
1683 OatClassType type = static_cast<OatClassType>(*reinterpret_cast<const uint16_t*>(type_pointer));
1684 CHECK_LT(type, kOatClassMax);
1685
Ian Rogers13735952014-10-08 12:43:28 -07001686 const uint8_t* after_type_pointer = type_pointer + sizeof(int16_t);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001687 CHECK_LE(after_type_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07001688
Brian Carlstromcd937a92014-03-04 22:53:23 -08001689 uint32_t bitmap_size = 0;
Ian Rogers13735952014-10-08 12:43:28 -07001690 const uint8_t* bitmap_pointer = nullptr;
1691 const uint8_t* methods_pointer = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07001692 if (type != kOatClassNoneCompiled) {
1693 if (type == kOatClassSomeCompiled) {
1694 bitmap_size = static_cast<uint32_t>(*reinterpret_cast<const uint32_t*>(after_type_pointer));
1695 bitmap_pointer = after_type_pointer + sizeof(bitmap_size);
1696 CHECK_LE(bitmap_pointer, oat_file_->End()) << oat_file_->GetLocation();
1697 methods_pointer = bitmap_pointer + bitmap_size;
1698 } else {
1699 methods_pointer = after_type_pointer;
1700 }
1701 CHECK_LE(methods_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstromcd937a92014-03-04 22:53:23 -08001702 }
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001703
Richard Uhler07b3c232015-03-31 15:57:54 -07001704 return OatFile::OatClass(oat_file_,
1705 status,
1706 type,
1707 bitmap_size,
1708 reinterpret_cast<const uint32_t*>(bitmap_pointer),
1709 reinterpret_cast<const OatMethodOffsets*>(methods_pointer));
Brian Carlstrome24fa612011-09-29 00:53:55 -07001710}
1711
David Sehr9aa352e2016-09-15 18:13:52 -07001712const DexFile::ClassDef* OatFile::OatDexFile::FindClassDef(const DexFile& dex_file,
1713 const char* descriptor,
1714 size_t hash) {
1715 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1716 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
1717 if (LIKELY((oat_dex_file != nullptr) && (oat_dex_file->GetTypeLookupTable() != nullptr))) {
1718 const uint32_t class_def_idx = oat_dex_file->GetTypeLookupTable()->Lookup(descriptor, hash);
Andreas Gampee2abbc62017-09-15 11:59:26 -07001719 return (class_def_idx != dex::kDexNoIndex) ? &dex_file.GetClassDef(class_def_idx) : nullptr;
David Sehr9aa352e2016-09-15 18:13:52 -07001720 }
1721 // Fast path for rare no class defs case.
1722 const uint32_t num_class_defs = dex_file.NumClassDefs();
1723 if (num_class_defs == 0) {
1724 return nullptr;
1725 }
1726 const DexFile::TypeId* type_id = dex_file.FindTypeId(descriptor);
1727 if (type_id != nullptr) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001728 dex::TypeIndex type_idx = dex_file.GetIndexForTypeId(*type_id);
David Sehr9aa352e2016-09-15 18:13:52 -07001729 return dex_file.FindClassDef(type_idx);
1730 }
1731 return nullptr;
1732}
1733
Mathieu Chartier120aa282017-08-05 16:03:03 -07001734// Madvise the dex file based on the state we are moving to.
1735void OatDexFile::MadviseDexFile(const DexFile& dex_file, MadviseState state) {
Mathieu Chartierc42cb0e2017-10-13 11:35:00 -07001736 Runtime* const runtime = Runtime::Current();
1737 const bool low_ram = runtime->GetHeap()->IsLowMemoryMode();
Mathieu Chartier150d25d2017-08-28 09:52:55 -07001738 // TODO: Also do madvise hints for non low ram devices.
Mathieu Chartierc42cb0e2017-10-13 11:35:00 -07001739 if (!low_ram) {
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001740 return;
1741 }
Mathieu Chartierc42cb0e2017-10-13 11:35:00 -07001742 if (state == MadviseState::kMadviseStateAtLoad && runtime->MAdviseRandomAccess()) {
1743 // Default every dex file to MADV_RANDOM when its loaded by default for low ram devices.
1744 // Other devices have enough page cache to get performance benefits from loading more pages
1745 // into the page cache.
1746 MadviseLargestPageAlignedRegion(dex_file.Begin(),
1747 dex_file.Begin() + dex_file.Size(),
1748 MADV_RANDOM);
Mathieu Chartier120aa282017-08-05 16:03:03 -07001749 }
1750 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1751 if (oat_dex_file != nullptr) {
1752 // Should always be there.
1753 const DexLayoutSections* const sections = oat_dex_file->GetDexLayoutSections();
1754 CHECK(sections != nullptr);
1755 sections->Madvise(&dex_file, state);
1756 }
1757}
1758
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001759OatFile::OatClass::OatClass(const OatFile* oat_file,
Vladimir Marko2c64a832018-01-04 11:31:56 +00001760 ClassStatus status,
Brian Carlstromba150c32013-08-27 17:31:03 -07001761 OatClassType type,
1762 uint32_t bitmap_size,
1763 const uint32_t* bitmap_pointer,
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001764 const OatMethodOffsets* methods_pointer)
Brian Carlstromba150c32013-08-27 17:31:03 -07001765 : oat_file_(oat_file), status_(status), type_(type),
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001766 bitmap_(bitmap_pointer), methods_pointer_(methods_pointer) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001767 switch (type_) {
1768 case kOatClassAllCompiled: {
1769 CHECK_EQ(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001770 CHECK(bitmap_pointer == nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001771 CHECK(methods_pointer != nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001772 break;
1773 }
1774 case kOatClassSomeCompiled: {
1775 CHECK_NE(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001776 CHECK(bitmap_pointer != nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001777 CHECK(methods_pointer != nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001778 break;
1779 }
1780 case kOatClassNoneCompiled: {
1781 CHECK_EQ(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001782 CHECK(bitmap_pointer == nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001783 CHECK(methods_pointer_ == nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001784 break;
1785 }
1786 case kOatClassMax: {
1787 LOG(FATAL) << "Invalid OatClassType " << type_;
1788 break;
1789 }
1790 }
1791}
Brian Carlstrome24fa612011-09-29 00:53:55 -07001792
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001793uint32_t OatFile::OatClass::GetOatMethodOffsetsOffset(uint32_t method_index) const {
1794 const OatMethodOffsets* oat_method_offsets = GetOatMethodOffsets(method_index);
1795 if (oat_method_offsets == nullptr) {
1796 return 0u;
1797 }
1798 return reinterpret_cast<const uint8_t*>(oat_method_offsets) - oat_file_->Begin();
1799}
1800
1801const OatMethodOffsets* OatFile::OatClass::GetOatMethodOffsets(uint32_t method_index) const {
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001802 // 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 -07001803 if (methods_pointer_ == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001804 CHECK_EQ(kOatClassNoneCompiled, type_);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001805 return nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07001806 }
1807 size_t methods_pointer_index;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001808 if (bitmap_ == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001809 CHECK_EQ(kOatClassAllCompiled, type_);
1810 methods_pointer_index = method_index;
1811 } else {
1812 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001813 if (!BitVector::IsBitSet(bitmap_, method_index)) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001814 return nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07001815 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001816 size_t num_set_bits = BitVector::NumSetBits(bitmap_, method_index);
1817 methods_pointer_index = num_set_bits;
Brian Carlstromba150c32013-08-27 17:31:03 -07001818 }
1819 const OatMethodOffsets& oat_method_offsets = methods_pointer_[methods_pointer_index];
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001820 return &oat_method_offsets;
1821}
1822
1823const OatFile::OatMethod OatFile::OatClass::GetOatMethod(uint32_t method_index) const {
1824 const OatMethodOffsets* oat_method_offsets = GetOatMethodOffsets(method_index);
1825 if (oat_method_offsets == nullptr) {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001826 return OatMethod(nullptr, 0);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001827 }
1828 if (oat_file_->IsExecutable() ||
1829 Runtime::Current() == nullptr || // This case applies for oatdump.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001830 Runtime::Current()->IsAotCompiler()) {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001831 return OatMethod(oat_file_->Begin(), oat_method_offsets->code_offset_);
Alex Light9dcc4572014-08-14 14:16:26 -07001832 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001833 // We aren't allowed to use the compiled code. We just force it down the interpreted / jit
1834 // version.
1835 return OatMethod(oat_file_->Begin(), 0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001836}
1837
Mathieu Chartiere401d142015-04-22 13:56:20 -07001838void OatFile::OatMethod::LinkMethod(ArtMethod* method) const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001839 CHECK(method != nullptr);
Ian Rogersef7d42f2014-01-06 12:55:46 -08001840 method->SetEntryPointFromQuickCompiledCode(GetQuickCode());
Brian Carlstromae826982011-11-09 01:33:42 -08001841}
1842
Andreas Gampe7ba64962014-10-23 11:37:40 -07001843bool OatFile::IsPic() const {
Igor Murashkin46774762014-10-22 11:37:02 -07001844 return GetOatHeader().IsPic();
Andreas Gampe7ba64962014-10-23 11:37:40 -07001845 // TODO: Check against oat_patches. b/18144996
1846}
1847
Sebastien Hertz0de11332015-05-13 12:14:05 +02001848bool OatFile::IsDebuggable() const {
1849 return GetOatHeader().IsDebuggable();
1850}
1851
Andreas Gampe29d38e72016-03-23 15:31:51 +00001852CompilerFilter::Filter OatFile::GetCompilerFilter() const {
1853 return GetOatHeader().GetCompilerFilter();
Calin Juravleb077e152016-02-18 18:47:37 +00001854}
1855
Calin Juravle44e5efa2017-09-12 00:54:26 -07001856std::string OatFile::GetClassLoaderContext() const {
1857 return GetOatHeader().GetStoreValueByKey(OatHeader::kClassPathKey);
Igor Murashkin2ffb7032017-11-08 13:35:21 -08001858}
Calin Juravle44e5efa2017-09-12 00:54:26 -07001859
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001860OatFile::OatClass OatFile::FindOatClass(const DexFile& dex_file,
1861 uint16_t class_def_idx,
1862 bool* found) {
1863 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
1864 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Mathieu Chartier1b868492016-11-16 16:22:37 -08001865 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001866 *found = false;
1867 return OatFile::OatClass::Invalid();
1868 }
1869 *found = true;
1870 return oat_dex_file->GetOatClass(class_def_idx);
1871}
1872
Mathieu Chartier1b868492016-11-16 16:22:37 -08001873void OatFile::OatDexFile::AssertAotCompiler() {
1874 CHECK(Runtime::Current()->IsAotCompiler());
1875}
1876
Brian Carlstrome24fa612011-09-29 00:53:55 -07001877} // namespace art