blob: 9fd99057a13289b49944d585bd4df129dac50263 [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 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100623 if (UNLIKELY(dex_file_offset > DexSize())) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100624 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
625 "offset %u > %zu",
626 GetLocation().c_str(),
627 i,
628 dex_file_location.c_str(),
629 dex_file_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100630 DexSize());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700631 return false;
632 }
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000633 const uint8_t* dex_file_pointer = nullptr;
634 if (UNLIKELY(dex_file_offset == 0U)) {
635 if (uncompressed_dex_files_ == nullptr) {
636 uncompressed_dex_files_.reset(new std::vector<std::unique_ptr<const DexFile>>());
637 // No dex files, load it from location.
638 const ArtDexFileLoader dex_file_loader;
639 if (!dex_file_loader.Open(dex_file_location.c_str(),
640 dex_file_location,
641 /* verify */ false,
642 /* verify_checksum */ false,
643 error_msg,
644 uncompressed_dex_files_.get())) {
645 if (Runtime::Current() == nullptr) {
646 // If there's no runtime, we're running oatdump, so return
647 // a half constructed oat file that oatdump knows how to deal with.
648 LOG(WARNING) << "Could not find associated dex files of oat file. "
649 << "Oatdump will only dump the header.";
650 return true;
651 } else {
652 return false;
653 }
654 }
655 }
656 dex_file_pointer = uncompressed_dex_files_.get()->at(i)->Begin();
657 } else {
658 if (UNLIKELY(DexSize() - dex_file_offset < sizeof(DexFile::Header))) {
659 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
660 "offset %u of %zu but the size of dex file header is %zu",
661 GetLocation().c_str(),
662 i,
663 dex_file_location.c_str(),
664 dex_file_offset,
665 DexSize(),
666 sizeof(DexFile::Header));
667 return false;
668 }
669 dex_file_pointer = DexBegin() + dex_file_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000670 }
Brian Carlstrom89521892011-12-07 22:05:07 -0800671
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700672 const bool valid_magic = DexFileLoader::IsMagicValid(dex_file_pointer);
Mathieu Chartier7b074bf2017-09-25 16:22:36 -0700673 if (UNLIKELY(!valid_magic)) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100674 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with invalid "
675 "dex file magic '%s'",
676 GetLocation().c_str(),
677 i,
678 dex_file_location.c_str(),
679 dex_file_pointer);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700680 return false;
681 }
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700682 if (UNLIKELY(!DexFileLoader::IsVersionAndMagicValid(dex_file_pointer))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100683 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with invalid "
684 "dex file version '%s'",
685 GetLocation().c_str(),
686 i,
687 dex_file_location.c_str(),
688 dex_file_pointer);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700689 return false;
690 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800691 const DexFile::Header* header = reinterpret_cast<const DexFile::Header*>(dex_file_pointer);
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000692 if (dex_file_offset != 0 && (DexSize() - dex_file_offset < header->file_size_)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000693 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
694 "offset %u and size %u truncated at %zu",
695 GetLocation().c_str(),
696 i,
697 dex_file_location.c_str(),
698 dex_file_offset,
699 header->file_size_,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100700 DexSize());
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000701 return false;
702 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300703
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000704 uint32_t class_offsets_offset;
705 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &class_offsets_offset))) {
706 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated "
707 "after class offsets offset",
708 GetLocation().c_str(),
709 i,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300710 dex_file_location.c_str());
711 return false;
712 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000713 if (UNLIKELY(class_offsets_offset > Size()) ||
714 UNLIKELY((Size() - class_offsets_offset) / sizeof(uint32_t) < header->class_defs_size_)) {
715 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with truncated "
716 "class offsets, offset %u of %zu, class defs %u",
717 GetLocation().c_str(),
718 i,
719 dex_file_location.c_str(),
720 class_offsets_offset,
721 Size(),
722 header->class_defs_size_);
723 return false;
724 }
725 if (UNLIKELY(!IsAligned<alignof(uint32_t)>(class_offsets_offset))) {
726 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with unaligned "
727 "class offsets, offset %u",
728 GetLocation().c_str(),
729 i,
730 dex_file_location.c_str(),
731 class_offsets_offset);
732 return false;
733 }
734 const uint32_t* class_offsets_pointer =
735 reinterpret_cast<const uint32_t*>(Begin() + class_offsets_offset);
736
737 uint32_t lookup_table_offset;
738 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &lookup_table_offset))) {
739 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zd for '%s' truncated "
740 "after lookup table offset",
741 GetLocation().c_str(),
742 i,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300743 dex_file_location.c_str());
744 return false;
745 }
746 const uint8_t* lookup_table_data = lookup_table_offset != 0u
747 ? Begin() + lookup_table_offset
748 : nullptr;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000749 if (lookup_table_offset != 0u &&
750 (UNLIKELY(lookup_table_offset > Size()) ||
751 UNLIKELY(Size() - lookup_table_offset <
752 TypeLookupTable::RawDataLength(header->class_defs_size_)))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100753 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with truncated "
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000754 "type lookup table, offset %u of %zu, class defs %u",
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100755 GetLocation().c_str(),
756 i,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000757 dex_file_location.c_str(),
758 lookup_table_offset,
759 Size(),
760 header->class_defs_size_);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700761 return false;
762 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700763
Mathieu Chartier120aa282017-08-05 16:03:03 -0700764 uint32_t dex_layout_sections_offset;
765 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_layout_sections_offset))) {
766 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zd for '%s' truncated "
767 "after dex layout sections offset",
768 GetLocation().c_str(),
769 i,
770 dex_file_location.c_str());
771 return false;
772 }
773 const DexLayoutSections* const dex_layout_sections = dex_layout_sections_offset != 0
774 ? reinterpret_cast<const DexLayoutSections*>(Begin() + dex_layout_sections_offset)
775 : nullptr;
776
Vladimir Markof3c52b42017-11-17 17:32:12 +0000777 const IndexBssMapping* method_bss_mapping;
778 const IndexBssMapping* type_bss_mapping;
779 const IndexBssMapping* string_bss_mapping;
780 if (!ReadIndexBssMapping(
781 this, &oat, i, dex_file_location, "method", &method_bss_mapping, error_msg) ||
782 !ReadIndexBssMapping(
783 this, &oat, i, dex_file_location, "type", &type_bss_mapping, error_msg) ||
784 !ReadIndexBssMapping(
785 this, &oat, i, dex_file_location, "string", &string_bss_mapping, error_msg)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100786 return false;
787 }
Vladimir Markof3c52b42017-11-17 17:32:12 +0000788 DCheckIndexToBssMapping(
789 this, header->method_ids_size_, static_cast<size_t>(pointer_size), method_bss_mapping);
790 DCheckIndexToBssMapping(
791 this, header->type_ids_size_, sizeof(GcRoot<mirror::Class>), type_bss_mapping);
792 DCheckIndexToBssMapping(
793 this, header->string_ids_size_, sizeof(GcRoot<mirror::String>), string_bss_mapping);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100794
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700795 std::string canonical_location =
796 DexFileLoader::GetDexCanonicalLocation(dex_file_location.c_str());
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100797
798 // Create the OatDexFile and add it to the owning container.
Vladimir Marko539690a2014-06-05 18:36:42 +0100799 OatDexFile* oat_dex_file = new OatDexFile(this,
800 dex_file_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100801 canonical_location,
Vladimir Marko539690a2014-06-05 18:36:42 +0100802 dex_file_checksum,
803 dex_file_pointer,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300804 lookup_table_data,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100805 method_bss_mapping,
Vladimir Markof3c52b42017-11-17 17:32:12 +0000806 type_bss_mapping,
807 string_bss_mapping,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000808 class_offsets_pointer,
Mathieu Chartier120aa282017-08-05 16:03:03 -0700809 dex_layout_sections);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100810 oat_dex_files_storage_.push_back(oat_dex_file);
811
812 // Add the location and canonical location (if different) to the oat_dex_files_ table.
Vladimir Marko3f5838d2014-08-07 18:07:18 +0100813 StringPiece key(oat_dex_file->GetDexFileLocation());
Vladimir Marko539690a2014-06-05 18:36:42 +0100814 oat_dex_files_.Put(key, oat_dex_file);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100815 if (canonical_location != dex_file_location) {
816 StringPiece canonical_key(oat_dex_file->GetCanonicalDexFileLocation());
817 oat_dex_files_.Put(canonical_key, oat_dex_file);
818 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700819 }
Vladimir Marko09d09432015-09-08 13:47:48 +0100820
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100821 if (boot_image_tables != nullptr) {
Vladimir Marko667585a2017-09-29 10:42:31 +0100822 Runtime* runtime = Runtime::Current();
823 if (UNLIKELY(runtime == nullptr)) {
824 // This must be oatdump without boot image. Make sure the .bss is inaccessible.
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700825 CheckedCall(mprotect, "protect bss", const_cast<uint8_t*>(BssBegin()), BssSize(), PROT_NONE);
Vladimir Marko667585a2017-09-29 10:42:31 +0100826 } else {
827 // Map boot image tables into the .bss. The reserved size must match size of the tables.
828 size_t reserved_size = static_cast<size_t>(boot_image_tables_end - boot_image_tables);
829 size_t tables_size = 0u;
830 for (gc::space::ImageSpace* space : runtime->GetHeap()->GetBootImageSpaces()) {
831 tables_size += space->GetImageHeader().GetBootImageConstantTablesSize();
832 DCHECK_ALIGNED(tables_size, kPageSize);
833 }
834 if (tables_size != reserved_size) {
835 *error_msg = StringPrintf("In oat file '%s' found unexpected boot image table sizes, "
836 " %zu bytes, should be %zu.",
837 GetLocation().c_str(),
838 reserved_size,
839 tables_size);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100840 return false;
841 }
Vladimir Marko667585a2017-09-29 10:42:31 +0100842 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
843 uint32_t current_tables_size = space->GetImageHeader().GetBootImageConstantTablesSize();
844 if (current_tables_size != 0u && !MapConstantTables(space, boot_image_tables)) {
845 return false;
846 }
847 boot_image_tables += current_tables_size;
848 }
849 DCHECK(boot_image_tables == boot_image_tables_end);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100850 }
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100851 }
Brian Carlstromf1b30302013-03-28 10:35:32 -0700852 return true;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700853}
854
Andreas Gampe049cff02015-12-01 23:27:12 -0800855////////////////////////
856// OatFile via dlopen //
857////////////////////////
858
Andreas Gampe049cff02015-12-01 23:27:12 -0800859class DlOpenOatFile FINAL : public OatFileBase {
860 public:
861 DlOpenOatFile(const std::string& filename, bool executable)
862 : OatFileBase(filename, executable),
863 dlopen_handle_(nullptr),
Richard Uhlera206c742016-05-24 15:04:22 -0700864 shared_objects_before_(0) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800865 }
866
867 ~DlOpenOatFile() {
868 if (dlopen_handle_ != nullptr) {
Richard Uhlera206c742016-05-24 15:04:22 -0700869 if (!kIsTargetBuild) {
870 MutexLock mu(Thread::Current(), *Locks::host_dlopen_handles_lock_);
871 host_dlopen_handles_.erase(dlopen_handle_);
Mathieu Chartierc7d3f4b2016-06-01 10:48:19 -0700872 dlclose(dlopen_handle_);
873 } else {
874 dlclose(dlopen_handle_);
Richard Uhlera206c742016-05-24 15:04:22 -0700875 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800876 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800877 }
878
879 protected:
880 const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
881 std::string* error_msg) const OVERRIDE {
882 const uint8_t* ptr =
883 reinterpret_cast<const uint8_t*>(dlsym(dlopen_handle_, symbol_name.c_str()));
884 if (ptr == nullptr) {
885 *error_msg = dlerror();
886 }
887 return ptr;
888 }
889
Andreas Gampe4075f832016-05-18 13:09:54 -0700890 void PreLoad() OVERRIDE;
891
Andreas Gampe049cff02015-12-01 23:27:12 -0800892 bool Load(const std::string& elf_filename,
893 uint8_t* oat_file_begin,
894 bool writable,
895 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800896 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800897 std::string* error_msg) OVERRIDE;
898
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700899 bool Load(int, uint8_t*, bool, bool, bool, std::string*) {
900 return false;
901 }
902
Andreas Gampe049cff02015-12-01 23:27:12 -0800903 // Ask the linker where it mmaped the file and notify our mmap wrapper of the regions.
904 void PreSetup(const std::string& elf_filename) OVERRIDE;
905
906 private:
907 bool Dlopen(const std::string& elf_filename,
908 uint8_t* oat_file_begin,
909 std::string* error_msg);
910
Richard Uhlera206c742016-05-24 15:04:22 -0700911 // On the host, if the same library is loaded again with dlopen the same
912 // file handle is returned. This differs from the behavior of dlopen on the
913 // target, where dlopen reloads the library at a different address every
914 // time you load it. The runtime relies on the target behavior to ensure
915 // each instance of the loaded library has a unique dex cache. To avoid
916 // problems, we fall back to our own linker in the case when the same
917 // library is opened multiple times on host. dlopen_handles_ is used to
918 // detect that case.
919 // Guarded by host_dlopen_handles_lock_;
920 static std::unordered_set<void*> host_dlopen_handles_;
921
Andreas Gampe049cff02015-12-01 23:27:12 -0800922 // dlopen handle during runtime.
923 void* dlopen_handle_; // TODO: Unique_ptr with custom deleter.
924
925 // Dummy memory map objects corresponding to the regions mapped by dlopen.
926 std::vector<std::unique_ptr<MemMap>> dlopen_mmaps_;
927
Andreas Gampe4075f832016-05-18 13:09:54 -0700928 // The number of shared objects the linker told us about before loading. Used to
929 // (optimistically) optimize the PreSetup stage (see comment there).
930 size_t shared_objects_before_;
931
Andreas Gampe049cff02015-12-01 23:27:12 -0800932 DISALLOW_COPY_AND_ASSIGN(DlOpenOatFile);
933};
934
Richard Uhlera206c742016-05-24 15:04:22 -0700935std::unordered_set<void*> DlOpenOatFile::host_dlopen_handles_;
936
Andreas Gampe4075f832016-05-18 13:09:54 -0700937void DlOpenOatFile::PreLoad() {
938#ifdef __APPLE__
Andreas Gampe39004a62016-05-18 21:27:00 -0700939 UNUSED(shared_objects_before_);
Andreas Gampe4075f832016-05-18 13:09:54 -0700940 LOG(FATAL) << "Should not reach here.";
941 UNREACHABLE();
942#else
943 // Count the entries in dl_iterate_phdr we get at this point in time.
944 struct dl_iterate_context {
945 static int callback(struct dl_phdr_info *info ATTRIBUTE_UNUSED,
946 size_t size ATTRIBUTE_UNUSED,
947 void *data) {
948 reinterpret_cast<dl_iterate_context*>(data)->count++;
949 return 0; // Continue iteration.
950 }
951 size_t count = 0;
952 } context;
953
954 dl_iterate_phdr(dl_iterate_context::callback, &context);
955 shared_objects_before_ = context.count;
956#endif
957}
958
Andreas Gampe049cff02015-12-01 23:27:12 -0800959bool DlOpenOatFile::Load(const std::string& elf_filename,
960 uint8_t* oat_file_begin,
961 bool writable,
962 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800963 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800964 std::string* error_msg) {
965 // Use dlopen only when flagged to do so, and when it's OK to load things executable.
966 // TODO: Also try when not executable? The issue here could be re-mapping as writable (as
967 // !executable is a sign that we may want to patch), which may not be allowed for
968 // various reasons.
969 if (!kUseDlopen) {
970 *error_msg = "DlOpen is disabled.";
971 return false;
972 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800973 if (low_4gb) {
974 *error_msg = "DlOpen does not support low 4gb loading.";
975 return false;
976 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800977 if (writable) {
978 *error_msg = "DlOpen does not support writable loading.";
979 return false;
980 }
981 if (!executable) {
982 *error_msg = "DlOpen does not support non-executable loading.";
983 return false;
984 }
985
986 // dlopen always returns the same library if it is already opened on the host. For this reason
987 // we only use dlopen if we are the target or we do not already have the dex file opened. Having
988 // the same library loaded multiple times at different addresses is required for class unloading
989 // and for having dex caches arrays in the .bss section.
990 if (!kIsTargetBuild) {
991 if (!kUseDlopenOnHost) {
992 *error_msg = "DlOpen disabled for host.";
993 return false;
994 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800995 }
996
997 bool success = Dlopen(elf_filename, oat_file_begin, error_msg);
998 DCHECK(dlopen_handle_ != nullptr || !success);
999
1000 return success;
1001}
1002
1003bool DlOpenOatFile::Dlopen(const std::string& elf_filename,
1004 uint8_t* oat_file_begin,
1005 std::string* error_msg) {
1006#ifdef __APPLE__
1007 // The dl_iterate_phdr syscall is missing. There is similar API on OSX,
1008 // but let's fallback to the custom loading code for the time being.
1009 UNUSED(elf_filename, oat_file_begin);
1010 *error_msg = "Dlopen unsupported on Mac.";
1011 return false;
1012#else
1013 {
1014 UniqueCPtr<char> absolute_path(realpath(elf_filename.c_str(), nullptr));
1015 if (absolute_path == nullptr) {
1016 *error_msg = StringPrintf("Failed to find absolute path for '%s'", elf_filename.c_str());
1017 return false;
1018 }
Bilyan Borisovbb661c02016-04-04 16:27:32 +01001019#ifdef ART_TARGET_ANDROID
Anton Kirilov3a2e78e2017-01-06 13:33:42 +00001020 android_dlextinfo extinfo = {};
Andreas Gampe049cff02015-12-01 23:27:12 -08001021 extinfo.flags = ANDROID_DLEXT_FORCE_LOAD | // Force-load, don't reuse handle
1022 // (open oat files multiple
1023 // times).
1024 ANDROID_DLEXT_FORCE_FIXED_VADDR; // Take a non-zero vaddr as absolute
1025 // (non-pic boot image).
Andreas Gampe226b91e2015-12-02 10:29:33 -08001026 if (oat_file_begin != nullptr) { //
1027 extinfo.flags |= ANDROID_DLEXT_LOAD_AT_FIXED_ADDRESS; // Use the requested addr if
1028 extinfo.reserved_addr = oat_file_begin; // vaddr = 0.
1029 } // (pic boot image).
Andreas Gampe049cff02015-12-01 23:27:12 -08001030 dlopen_handle_ = android_dlopen_ext(absolute_path.get(), RTLD_NOW, &extinfo);
1031#else
Andreas Gampe049cff02015-12-01 23:27:12 -08001032 UNUSED(oat_file_begin);
Julien Duraj1af0c4f2016-11-16 14:05:48 +00001033 static_assert(!kIsTargetBuild || kIsTargetLinux, "host_dlopen_handles_ will leak handles");
Mathieu Chartierc7d3f4b2016-06-01 10:48:19 -07001034 MutexLock mu(Thread::Current(), *Locks::host_dlopen_handles_lock_);
Richard Uhlera206c742016-05-24 15:04:22 -07001035 dlopen_handle_ = dlopen(absolute_path.get(), RTLD_NOW);
1036 if (dlopen_handle_ != nullptr) {
Richard Uhlera206c742016-05-24 15:04:22 -07001037 if (!host_dlopen_handles_.insert(dlopen_handle_).second) {
1038 dlclose(dlopen_handle_);
1039 dlopen_handle_ = nullptr;
1040 *error_msg = StringPrintf("host dlopen re-opened '%s'", elf_filename.c_str());
1041 return false;
1042 }
1043 }
Bilyan Borisovbb661c02016-04-04 16:27:32 +01001044#endif // ART_TARGET_ANDROID
Andreas Gampe049cff02015-12-01 23:27:12 -08001045 }
1046 if (dlopen_handle_ == nullptr) {
1047 *error_msg = StringPrintf("Failed to dlopen '%s': %s", elf_filename.c_str(), dlerror());
1048 return false;
1049 }
1050 return true;
1051#endif
1052}
1053
1054void DlOpenOatFile::PreSetup(const std::string& elf_filename) {
Andreas Gampe74f07b52015-12-02 11:53:26 -08001055#ifdef __APPLE__
1056 UNUSED(elf_filename);
1057 LOG(FATAL) << "Should not reach here.";
1058 UNREACHABLE();
1059#else
Andreas Gampe049cff02015-12-01 23:27:12 -08001060 struct dl_iterate_context {
1061 static int callback(struct dl_phdr_info *info, size_t /* size */, void *data) {
1062 auto* context = reinterpret_cast<dl_iterate_context*>(data);
Andreas Gampe4075f832016-05-18 13:09:54 -07001063 context->shared_objects_seen++;
1064 if (context->shared_objects_seen < context->shared_objects_before) {
1065 // We haven't been called yet for anything we haven't seen before. Just continue.
1066 // Note: this is aggressively optimistic. If another thread was unloading a library,
1067 // we may miss out here. However, this does not happen often in practice.
1068 return 0;
1069 }
1070
Andreas Gampe049cff02015-12-01 23:27:12 -08001071 // See whether this callback corresponds to the file which we have just loaded.
1072 bool contains_begin = false;
1073 for (int i = 0; i < info->dlpi_phnum; i++) {
1074 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
1075 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
1076 info->dlpi_phdr[i].p_vaddr);
1077 size_t memsz = info->dlpi_phdr[i].p_memsz;
1078 if (vaddr <= context->begin_ && context->begin_ < vaddr + memsz) {
1079 contains_begin = true;
1080 break;
1081 }
1082 }
1083 }
1084 // Add dummy mmaps for this file.
1085 if (contains_begin) {
1086 for (int i = 0; i < info->dlpi_phnum; i++) {
1087 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
1088 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
1089 info->dlpi_phdr[i].p_vaddr);
1090 size_t memsz = info->dlpi_phdr[i].p_memsz;
1091 MemMap* mmap = MemMap::MapDummy(info->dlpi_name, vaddr, memsz);
1092 context->dlopen_mmaps_->push_back(std::unique_ptr<MemMap>(mmap));
1093 }
1094 }
1095 return 1; // Stop iteration and return 1 from dl_iterate_phdr.
1096 }
1097 return 0; // Continue iteration and return 0 from dl_iterate_phdr when finished.
1098 }
1099 const uint8_t* const begin_;
1100 std::vector<std::unique_ptr<MemMap>>* const dlopen_mmaps_;
Andreas Gampe4075f832016-05-18 13:09:54 -07001101 const size_t shared_objects_before;
1102 size_t shared_objects_seen;
1103 };
1104 dl_iterate_context context = { Begin(), &dlopen_mmaps_, shared_objects_before_, 0};
Andreas Gampe049cff02015-12-01 23:27:12 -08001105
1106 if (dl_iterate_phdr(dl_iterate_context::callback, &context) == 0) {
Andreas Gampe4075f832016-05-18 13:09:54 -07001107 // Hm. Maybe our optimization went wrong. Try another time with shared_objects_before == 0
1108 // before giving up. This should be unusual.
1109 VLOG(oat) << "Need a second run in PreSetup, didn't find with shared_objects_before="
1110 << shared_objects_before_;
1111 dl_iterate_context context0 = { Begin(), &dlopen_mmaps_, 0, 0};
1112 if (dl_iterate_phdr(dl_iterate_context::callback, &context0) == 0) {
1113 // OK, give up and print an error.
Andreas Gampe170331f2017-12-07 18:41:03 -08001114 PrintFileToLog("/proc/self/maps", android::base::LogSeverity::WARNING);
Andreas Gampe4075f832016-05-18 13:09:54 -07001115 LOG(ERROR) << "File " << elf_filename << " loaded with dlopen but cannot find its mmaps.";
1116 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001117 }
Andreas Gampe74f07b52015-12-02 11:53:26 -08001118#endif
Andreas Gampe049cff02015-12-01 23:27:12 -08001119}
1120
1121////////////////////////////////////////////////
1122// OatFile via our own ElfFile implementation //
1123////////////////////////////////////////////////
1124
1125class ElfOatFile FINAL : public OatFileBase {
1126 public:
1127 ElfOatFile(const std::string& filename, bool executable) : OatFileBase(filename, executable) {}
1128
1129 static ElfOatFile* OpenElfFile(File* file,
1130 const std::string& location,
1131 uint8_t* requested_base,
1132 uint8_t* oat_file_begin, // Override base if not null
1133 bool writable,
1134 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001135 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001136 const char* abs_dex_location,
1137 std::string* error_msg);
1138
1139 bool InitializeFromElfFile(ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +01001140 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001141 const char* abs_dex_location,
1142 std::string* error_msg);
1143
1144 protected:
1145 const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
1146 std::string* error_msg) const OVERRIDE {
1147 const uint8_t* ptr = elf_file_->FindDynamicSymbolAddress(symbol_name);
1148 if (ptr == nullptr) {
1149 *error_msg = "(Internal implementation could not find symbol)";
1150 }
1151 return ptr;
1152 }
1153
Andreas Gampe4075f832016-05-18 13:09:54 -07001154 void PreLoad() OVERRIDE {
1155 }
1156
Andreas Gampe049cff02015-12-01 23:27:12 -08001157 bool Load(const std::string& elf_filename,
1158 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1159 bool writable,
1160 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001161 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001162 std::string* error_msg) OVERRIDE;
1163
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001164 bool Load(int oat_fd,
1165 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1166 bool writable,
1167 bool executable,
1168 bool low_4gb,
1169 std::string* error_msg) OVERRIDE;
1170
Andreas Gampe049cff02015-12-01 23:27:12 -08001171 void PreSetup(const std::string& elf_filename ATTRIBUTE_UNUSED) OVERRIDE {
1172 }
1173
1174 private:
1175 bool ElfFileOpen(File* file,
1176 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1177 bool writable,
1178 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001179 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001180 std::string* error_msg);
1181
1182 private:
1183 // Backing memory map for oat file during cross compilation.
1184 std::unique_ptr<ElfFile> elf_file_;
1185
1186 DISALLOW_COPY_AND_ASSIGN(ElfOatFile);
1187};
1188
1189ElfOatFile* ElfOatFile::OpenElfFile(File* file,
1190 const std::string& location,
1191 uint8_t* requested_base,
1192 uint8_t* oat_file_begin, // Override base if not null
1193 bool writable,
1194 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001195 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001196 const char* abs_dex_location,
1197 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001198 ScopedTrace trace("Open elf file " + location);
Andreas Gampe049cff02015-12-01 23:27:12 -08001199 std::unique_ptr<ElfOatFile> oat_file(new ElfOatFile(location, executable));
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001200 bool success = oat_file->ElfFileOpen(file,
1201 oat_file_begin,
1202 writable,
1203 low_4gb,
1204 executable,
1205 error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -08001206 if (!success) {
1207 CHECK(!error_msg->empty());
1208 return nullptr;
1209 }
1210
1211 // Complete the setup.
1212 if (!oat_file->ComputeFields(requested_base, file->GetPath(), error_msg)) {
1213 return nullptr;
1214 }
1215
1216 if (!oat_file->Setup(abs_dex_location, error_msg)) {
1217 return nullptr;
1218 }
1219
1220 return oat_file.release();
1221}
1222
1223bool ElfOatFile::InitializeFromElfFile(ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +01001224 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001225 const char* abs_dex_location,
1226 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001227 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -08001228 if (IsExecutable()) {
1229 *error_msg = "Cannot initialize from elf file in executable mode.";
1230 return false;
1231 }
1232 elf_file_.reset(elf_file);
David Brazdilc93b3be2016-09-12 18:49:58 +01001233 SetVdex(vdex_file);
Andreas Gampe049cff02015-12-01 23:27:12 -08001234 uint64_t offset, size;
1235 bool has_section = elf_file->GetSectionOffsetAndSize(".rodata", &offset, &size);
1236 CHECK(has_section);
1237 SetBegin(elf_file->Begin() + offset);
1238 SetEnd(elf_file->Begin() + size + offset);
1239 // Ignore the optional .bss section when opening non-executable.
1240 return Setup(abs_dex_location, error_msg);
1241}
1242
1243bool ElfOatFile::Load(const std::string& elf_filename,
1244 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1245 bool writable,
1246 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001247 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001248 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001249 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -08001250 std::unique_ptr<File> file(OS::OpenFileForReading(elf_filename.c_str()));
1251 if (file == nullptr) {
1252 *error_msg = StringPrintf("Failed to open oat filename for reading: %s", strerror(errno));
1253 return false;
1254 }
1255 return ElfOatFile::ElfFileOpen(file.get(),
1256 oat_file_begin,
1257 writable,
1258 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001259 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001260 error_msg);
1261}
1262
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001263bool ElfOatFile::Load(int oat_fd,
1264 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1265 bool writable,
1266 bool executable,
1267 bool low_4gb,
1268 std::string* error_msg) {
1269 ScopedTrace trace(__PRETTY_FUNCTION__);
1270 if (oat_fd != -1) {
1271 std::unique_ptr<File> file = std::make_unique<File>(oat_fd, false);
1272 file->DisableAutoClose();
1273 if (file == nullptr) {
1274 *error_msg = StringPrintf("Failed to open oat filename for reading: %s",
1275 strerror(errno));
1276 return false;
1277 }
1278 return ElfOatFile::ElfFileOpen(file.get(),
1279 oat_file_begin,
1280 writable,
1281 executable,
1282 low_4gb,
1283 error_msg);
1284 }
1285 return false;
1286}
1287
Andreas Gampe049cff02015-12-01 23:27:12 -08001288bool ElfOatFile::ElfFileOpen(File* file,
1289 uint8_t* oat_file_begin,
1290 bool writable,
1291 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001292 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001293 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001294 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -08001295 // TODO: rename requested_base to oat_data_begin
1296 elf_file_.reset(ElfFile::Open(file,
1297 writable,
1298 /*program_header_only*/true,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001299 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001300 error_msg,
1301 oat_file_begin));
1302 if (elf_file_ == nullptr) {
1303 DCHECK(!error_msg->empty());
1304 return false;
1305 }
Brian Carlstromf5b0f2c2016-10-14 01:04:26 -07001306 bool loaded = elf_file_->Load(file, executable, low_4gb, error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -08001307 DCHECK(loaded || !error_msg->empty());
1308 return loaded;
1309}
1310
1311//////////////////////////
1312// General OatFile code //
1313//////////////////////////
1314
1315std::string OatFile::ResolveRelativeEncodedDexLocation(
1316 const char* abs_dex_location, const std::string& rel_dex_location) {
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00001317 // For host, we still do resolution as the rel_dex_location might be absolute
1318 // for a target dex (for example /system/foo/foo.apk).
1319 if (abs_dex_location != nullptr && (rel_dex_location[0] != '/' || !kIsTargetBuild)) {
Andreas Gampe049cff02015-12-01 23:27:12 -08001320 // Strip :classes<N>.dex used for secondary multidex files.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001321 std::string base = DexFileLoader::GetBaseLocation(rel_dex_location);
1322 std::string multidex_suffix = DexFileLoader::GetMultiDexSuffix(rel_dex_location);
Andreas Gampe049cff02015-12-01 23:27:12 -08001323
1324 // Check if the base is a suffix of the provided abs_dex_location.
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00001325 std::string target_suffix = ((rel_dex_location[0] != '/') ? "/" : "") + base;
Andreas Gampe049cff02015-12-01 23:27:12 -08001326 std::string abs_location(abs_dex_location);
1327 if (abs_location.size() > target_suffix.size()) {
1328 size_t pos = abs_location.size() - target_suffix.size();
1329 if (abs_location.compare(pos, std::string::npos, target_suffix) == 0) {
1330 return abs_location + multidex_suffix;
1331 }
1332 }
1333 }
1334 return rel_dex_location;
1335}
1336
1337static void CheckLocation(const std::string& location) {
1338 CHECK(!location.empty());
1339}
1340
1341OatFile* OatFile::OpenWithElfFile(ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +01001342 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001343 const std::string& location,
1344 const char* abs_dex_location,
1345 std::string* error_msg) {
1346 std::unique_ptr<ElfOatFile> oat_file(new ElfOatFile(location, false /* executable */));
David Brazdilc93b3be2016-09-12 18:49:58 +01001347 return oat_file->InitializeFromElfFile(elf_file, vdex_file, abs_dex_location, error_msg)
Andreas Gampe049cff02015-12-01 23:27:12 -08001348 ? oat_file.release()
1349 : nullptr;
1350}
1351
David Brazdil7b49e6c2016-09-01 11:06:18 +01001352OatFile* OatFile::Open(const std::string& oat_filename,
1353 const std::string& oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001354 uint8_t* requested_base,
1355 uint8_t* oat_file_begin,
1356 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001357 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001358 const char* abs_dex_location,
1359 std::string* error_msg) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001360 ScopedTrace trace("Open oat file " + oat_location);
1361 CHECK(!oat_filename.empty()) << oat_location;
1362 CheckLocation(oat_location);
Andreas Gampe54315c72016-05-18 21:10:42 -07001363
Calin Juravle367b9d82017-05-15 18:18:39 -07001364 std::string vdex_filename = GetVdexFilename(oat_filename);
David Brazdil7b49e6c2016-09-01 11:06:18 +01001365
1366 // Check that the files even exist, fast-fail.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001367 if (!OS::FileExists(vdex_filename.c_str())) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001368 *error_msg = StringPrintf("File %s does not exist.", vdex_filename.c_str());
1369 return nullptr;
1370 } else if (!OS::FileExists(oat_filename.c_str())) {
1371 *error_msg = StringPrintf("File %s does not exist.", oat_filename.c_str());
Andreas Gampe54315c72016-05-18 21:10:42 -07001372 return nullptr;
1373 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001374
1375 // Try dlopen first, as it is required for native debuggability. This will fail fast if dlopen is
1376 // disabled.
David Brazdil7b49e6c2016-09-01 11:06:18 +01001377 OatFile* with_dlopen = OatFileBase::OpenOatFile<DlOpenOatFile>(vdex_filename,
1378 oat_filename,
1379 oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001380 requested_base,
1381 oat_file_begin,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001382 false /* writable */,
Andreas Gampe049cff02015-12-01 23:27:12 -08001383 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001384 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001385 abs_dex_location,
1386 error_msg);
1387 if (with_dlopen != nullptr) {
1388 return with_dlopen;
1389 }
1390 if (kPrintDlOpenErrorMessage) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001391 LOG(ERROR) << "Failed to dlopen: " << oat_filename << " with error " << *error_msg;
Andreas Gampe049cff02015-12-01 23:27:12 -08001392 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001393 // If we aren't trying to execute, we just use our own ElfFile loader for a couple reasons:
1394 //
1395 // On target, dlopen may fail when compiling due to selinux restrictions on installd.
1396 //
1397 // We use our own ELF loader for Quick to deal with legacy apps that
1398 // open a generated dex file by name, remove the file, then open
1399 // another generated dex file with the same name. http://b/10614658
1400 //
1401 // On host, dlopen is expected to fail when cross compiling, so fall back to OpenElfFile.
1402 //
1403 //
1404 // Another independent reason is the absolute placement of boot.oat. dlopen on the host usually
1405 // 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 +01001406 OatFile* with_internal = OatFileBase::OpenOatFile<ElfOatFile>(vdex_filename,
1407 oat_filename,
1408 oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001409 requested_base,
1410 oat_file_begin,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001411 false /* writable */,
Andreas Gampe049cff02015-12-01 23:27:12 -08001412 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001413 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001414 abs_dex_location,
1415 error_msg);
1416 return with_internal;
1417}
1418
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001419OatFile* OatFile::Open(int vdex_fd,
1420 int oat_fd,
1421 const std::string& oat_location,
1422 uint8_t* requested_base,
1423 uint8_t* oat_file_begin,
1424 bool executable,
1425 bool low_4gb,
1426 const char* abs_dex_location,
1427 std::string* error_msg) {
1428 CHECK(!oat_location.empty()) << oat_location;
1429
1430 std::string vdex_location = GetVdexFilename(oat_location);
1431
1432 OatFile* with_internal = OatFileBase::OpenOatFile<ElfOatFile>(vdex_fd,
1433 oat_fd,
1434 vdex_location,
1435 oat_location,
1436 requested_base,
1437 oat_file_begin,
1438 false /* writable */,
1439 executable,
1440 low_4gb,
1441 abs_dex_location,
1442 error_msg);
1443 return with_internal;
1444}
1445
Andreas Gampe049cff02015-12-01 23:27:12 -08001446OatFile* OatFile::OpenWritable(File* file,
1447 const std::string& location,
1448 const char* abs_dex_location,
1449 std::string* error_msg) {
1450 CheckLocation(location);
1451 return ElfOatFile::OpenElfFile(file,
1452 location,
1453 nullptr,
1454 nullptr,
1455 true,
1456 false,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001457 /*low_4gb*/false,
Andreas Gampe049cff02015-12-01 23:27:12 -08001458 abs_dex_location,
1459 error_msg);
1460}
1461
1462OatFile* OatFile::OpenReadable(File* file,
1463 const std::string& location,
1464 const char* abs_dex_location,
1465 std::string* error_msg) {
1466 CheckLocation(location);
1467 return ElfOatFile::OpenElfFile(file,
1468 location,
1469 nullptr,
1470 nullptr,
1471 false,
1472 false,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001473 /*low_4gb*/false,
Andreas Gampe049cff02015-12-01 23:27:12 -08001474 abs_dex_location,
1475 error_msg);
1476}
1477
1478OatFile::OatFile(const std::string& location, bool is_executable)
1479 : location_(location),
David Brazdil7b49e6c2016-09-01 11:06:18 +01001480 vdex_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001481 begin_(nullptr),
1482 end_(nullptr),
1483 bss_begin_(nullptr),
1484 bss_end_(nullptr),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001485 bss_methods_(nullptr),
Vladimir Markoaad75c62016-10-03 08:46:48 +00001486 bss_roots_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001487 is_executable_(is_executable),
David Srbeckyec2cdf42017-12-08 16:21:25 +00001488 vdex_begin_(nullptr),
1489 vdex_end_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001490 secondary_lookup_lock_("OatFile secondary lookup lock", kOatFileSecondaryLookupLock) {
1491 CHECK(!location_.empty());
1492}
1493
1494OatFile::~OatFile() {
1495 STLDeleteElements(&oat_dex_files_storage_);
1496}
1497
Brian Carlstrome24fa612011-09-29 00:53:55 -07001498const OatHeader& OatFile::GetOatHeader() const {
Ian Rogers30fab402012-01-23 15:43:46 -08001499 return *reinterpret_cast<const OatHeader*>(Begin());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001500}
1501
Ian Rogers13735952014-10-08 12:43:28 -07001502const uint8_t* OatFile::Begin() const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001503 CHECK(begin_ != nullptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001504 return begin_;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001505}
1506
Ian Rogers13735952014-10-08 12:43:28 -07001507const uint8_t* OatFile::End() const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001508 CHECK(end_ != nullptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001509 return end_;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001510}
1511
Vladimir Marko5c42c292015-02-25 12:02:49 +00001512const uint8_t* OatFile::BssBegin() const {
1513 return bss_begin_;
1514}
1515
1516const uint8_t* OatFile::BssEnd() const {
1517 return bss_end_;
1518}
1519
David Srbeckyec2cdf42017-12-08 16:21:25 +00001520const uint8_t* OatFile::VdexBegin() const {
1521 return vdex_begin_;
1522}
1523
1524const uint8_t* OatFile::VdexEnd() const {
1525 return vdex_end_;
1526}
1527
David Brazdil7b49e6c2016-09-01 11:06:18 +01001528const uint8_t* OatFile::DexBegin() const {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001529 return vdex_->Begin();
David Brazdil7b49e6c2016-09-01 11:06:18 +01001530}
1531
1532const uint8_t* OatFile::DexEnd() const {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001533 return vdex_->End();
David Brazdil7b49e6c2016-09-01 11:06:18 +01001534}
1535
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001536ArrayRef<ArtMethod*> OatFile::GetBssMethods() const {
1537 if (bss_methods_ != nullptr) {
1538 ArtMethod** methods = reinterpret_cast<ArtMethod**>(bss_methods_);
1539 ArtMethod** methods_end =
1540 reinterpret_cast<ArtMethod**>(bss_roots_ != nullptr ? bss_roots_ : bss_end_);
1541 return ArrayRef<ArtMethod*>(methods, methods_end - methods);
1542 } else {
1543 return ArrayRef<ArtMethod*>();
1544 }
1545}
1546
Vladimir Markoaad75c62016-10-03 08:46:48 +00001547ArrayRef<GcRoot<mirror::Object>> OatFile::GetBssGcRoots() const {
1548 if (bss_roots_ != nullptr) {
1549 auto* roots = reinterpret_cast<GcRoot<mirror::Object>*>(bss_roots_);
1550 auto* roots_end = reinterpret_cast<GcRoot<mirror::Object>*>(bss_end_);
1551 return ArrayRef<GcRoot<mirror::Object>>(roots, roots_end - roots);
1552 } else {
1553 return ArrayRef<GcRoot<mirror::Object>>();
1554 }
1555}
1556
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001557const OatFile::OatDexFile* OatFile::GetOatDexFile(const char* dex_location,
1558 const uint32_t* dex_location_checksum,
Richard Uhler9a37efc2016-08-05 16:32:55 -07001559 std::string* error_msg) const {
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001560 // NOTE: We assume here that the canonical location for a given dex_location never
1561 // changes. If it does (i.e. some symlink used by the filename changes) we may return
1562 // an incorrect OatDexFile. As long as we have a checksum to check, we shall return
1563 // an identical file or fail; otherwise we may see some unpredictable failures.
Calin Juravle4e1d5792014-07-15 23:56:47 +01001564
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001565 // TODO: Additional analysis of usage patterns to see if this can be simplified
1566 // without any performance loss, for example by not doing the first lock-free lookup.
1567
1568 const OatFile::OatDexFile* oat_dex_file = nullptr;
1569 StringPiece key(dex_location);
1570 // Try to find the key cheaply in the oat_dex_files_ map which holds dex locations
1571 // directly mentioned in the oat file and doesn't require locking.
1572 auto primary_it = oat_dex_files_.find(key);
1573 if (primary_it != oat_dex_files_.end()) {
1574 oat_dex_file = primary_it->second;
1575 DCHECK(oat_dex_file != nullptr);
1576 } else {
1577 // This dex_location is not one of the dex locations directly mentioned in the
1578 // oat file. The correct lookup is via the canonical location but first see in
1579 // the secondary_oat_dex_files_ whether we've looked up this location before.
1580 MutexLock mu(Thread::Current(), secondary_lookup_lock_);
1581 auto secondary_lb = secondary_oat_dex_files_.lower_bound(key);
1582 if (secondary_lb != secondary_oat_dex_files_.end() && key == secondary_lb->first) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001583 oat_dex_file = secondary_lb->second; // May be null.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001584 } else {
1585 // We haven't seen this dex_location before, we must check the canonical location.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001586 std::string dex_canonical_location = DexFileLoader::GetDexCanonicalLocation(dex_location);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001587 if (dex_canonical_location != dex_location) {
1588 StringPiece canonical_key(dex_canonical_location);
1589 auto canonical_it = oat_dex_files_.find(canonical_key);
1590 if (canonical_it != oat_dex_files_.end()) {
1591 oat_dex_file = canonical_it->second;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001592 } // else keep null.
1593 } // else keep null.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001594
1595 // Copy the key to the string_cache_ and store the result in secondary map.
1596 string_cache_.emplace_back(key.data(), key.length());
1597 StringPiece key_copy(string_cache_.back());
1598 secondary_oat_dex_files_.PutBefore(secondary_lb, key_copy, oat_dex_file);
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001599 }
1600 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001601
1602 if (oat_dex_file == nullptr) {
1603 if (error_msg != nullptr) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001604 std::string dex_canonical_location = DexFileLoader::GetDexCanonicalLocation(dex_location);
Richard Uhler9a37efc2016-08-05 16:32:55 -07001605 *error_msg = "Failed to find OatDexFile for DexFile " + std::string(dex_location)
1606 + " (canonical path " + dex_canonical_location + ") in OatFile " + GetLocation();
1607 }
1608 return nullptr;
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001609 }
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001610
Richard Uhler9a37efc2016-08-05 16:32:55 -07001611 if (dex_location_checksum != nullptr &&
1612 oat_dex_file->GetDexFileLocationChecksum() != *dex_location_checksum) {
1613 if (error_msg != nullptr) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001614 std::string dex_canonical_location = DexFileLoader::GetDexCanonicalLocation(dex_location);
Richard Uhler9a37efc2016-08-05 16:32:55 -07001615 std::string checksum = StringPrintf("0x%08x", oat_dex_file->GetDexFileLocationChecksum());
1616 std::string required_checksum = StringPrintf("0x%08x", *dex_location_checksum);
1617 *error_msg = "OatDexFile for DexFile " + std::string(dex_location)
1618 + " (canonical path " + dex_canonical_location + ") in OatFile " + GetLocation()
1619 + " has checksum " + checksum + " but " + required_checksum + " was required";
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001620 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001621 return nullptr;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001622 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001623 return oat_dex_file;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001624}
1625
Brian Carlstrome24fa612011-09-29 00:53:55 -07001626OatFile::OatDexFile::OatDexFile(const OatFile* oat_file,
Elliott Hughesaa6a5882012-01-13 19:39:16 -08001627 const std::string& dex_file_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001628 const std::string& canonical_dex_file_location,
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001629 uint32_t dex_file_location_checksum,
Ian Rogers13735952014-10-08 12:43:28 -07001630 const uint8_t* dex_file_pointer,
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001631 const uint8_t* lookup_table_data,
Vladimir Markof3c52b42017-11-17 17:32:12 +00001632 const IndexBssMapping* method_bss_mapping_data,
1633 const IndexBssMapping* type_bss_mapping_data,
1634 const IndexBssMapping* string_bss_mapping_data,
Vladimir Marko09d09432015-09-08 13:47:48 +01001635 const uint32_t* oat_class_offsets_pointer,
Mathieu Chartier120aa282017-08-05 16:03:03 -07001636 const DexLayoutSections* dex_layout_sections)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001637 : oat_file_(oat_file),
1638 dex_file_location_(dex_file_location),
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001639 canonical_dex_file_location_(canonical_dex_file_location),
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001640 dex_file_location_checksum_(dex_file_location_checksum),
Brian Carlstrom89521892011-12-07 22:05:07 -08001641 dex_file_pointer_(dex_file_pointer),
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001642 lookup_table_data_(lookup_table_data),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001643 method_bss_mapping_(method_bss_mapping_data),
Vladimir Markof3c52b42017-11-17 17:32:12 +00001644 type_bss_mapping_(type_bss_mapping_data),
1645 string_bss_mapping_(string_bss_mapping_data),
Vladimir Marko09d09432015-09-08 13:47:48 +01001646 oat_class_offsets_pointer_(oat_class_offsets_pointer),
Mathieu Chartier120aa282017-08-05 16:03:03 -07001647 dex_layout_sections_(dex_layout_sections) {
David Sehr9aa352e2016-09-15 18:13:52 -07001648 // Initialize TypeLookupTable.
1649 if (lookup_table_data_ != nullptr) {
1650 // Peek the number of classes from the DexFile.
1651 const DexFile::Header* dex_header = reinterpret_cast<const DexFile::Header*>(dex_file_pointer_);
1652 const uint32_t num_class_defs = dex_header->class_defs_size_;
1653 if (lookup_table_data_ + TypeLookupTable::RawDataLength(num_class_defs) > GetOatFile()->End()) {
1654 LOG(WARNING) << "found truncated lookup table in " << dex_file_location_;
1655 } else {
Mathieu Chartier1b868492016-11-16 16:22:37 -08001656 lookup_table_ = TypeLookupTable::Open(dex_file_pointer_, lookup_table_data_, num_class_defs);
David Sehr9aa352e2016-09-15 18:13:52 -07001657 }
1658 }
1659}
Brian Carlstrome24fa612011-09-29 00:53:55 -07001660
Mathieu Chartier1b868492016-11-16 16:22:37 -08001661OatFile::OatDexFile::OatDexFile(std::unique_ptr<TypeLookupTable>&& lookup_table)
1662 : lookup_table_(std::move(lookup_table)) {}
1663
Brian Carlstrome24fa612011-09-29 00:53:55 -07001664OatFile::OatDexFile::~OatDexFile() {}
1665
Ian Rogers05f28c62012-10-23 18:12:13 -07001666size_t OatFile::OatDexFile::FileSize() const {
1667 return reinterpret_cast<const DexFile::Header*>(dex_file_pointer_)->file_size_;
1668}
1669
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001670std::unique_ptr<const DexFile> OatFile::OatDexFile::OpenDexFile(std::string* error_msg) const {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001671 ScopedTrace trace(__PRETTY_FUNCTION__);
Aart Bik37d6a3b2016-06-21 18:30:10 -07001672 static constexpr bool kVerify = false;
1673 static constexpr bool kVerifyChecksum = false;
David Sehr013fd802018-01-11 22:55:24 -08001674 const ArtDexFileLoader dex_file_loader;
1675 return dex_file_loader.Open(dex_file_pointer_,
1676 FileSize(),
1677 dex_file_location_,
1678 dex_file_location_checksum_,
1679 this,
1680 kVerify,
1681 kVerifyChecksum,
1682 error_msg);
Brian Carlstrom89521892011-12-07 22:05:07 -08001683}
1684
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001685uint32_t OatFile::OatDexFile::GetOatClassOffset(uint16_t class_def_index) const {
1686 return oat_class_offsets_pointer_[class_def_index];
1687}
1688
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001689OatFile::OatClass OatFile::OatDexFile::GetOatClass(uint16_t class_def_index) const {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001690 uint32_t oat_class_offset = GetOatClassOffset(class_def_index);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001691
Ian Rogers13735952014-10-08 12:43:28 -07001692 const uint8_t* oat_class_pointer = oat_file_->Begin() + oat_class_offset;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001693 CHECK_LT(oat_class_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001694
Ian Rogers13735952014-10-08 12:43:28 -07001695 const uint8_t* status_pointer = oat_class_pointer;
Brian Carlstromba150c32013-08-27 17:31:03 -07001696 CHECK_LT(status_pointer, oat_file_->End()) << oat_file_->GetLocation();
Vladimir Marko2c64a832018-01-04 11:31:56 +00001697 ClassStatus status = enum_cast<ClassStatus>(*reinterpret_cast<const int16_t*>(status_pointer));
1698 CHECK_LE(status, ClassStatus::kLast);
Brian Carlstromba150c32013-08-27 17:31:03 -07001699
Ian Rogers13735952014-10-08 12:43:28 -07001700 const uint8_t* type_pointer = status_pointer + sizeof(uint16_t);
Brian Carlstromba150c32013-08-27 17:31:03 -07001701 CHECK_LT(type_pointer, oat_file_->End()) << oat_file_->GetLocation();
1702 OatClassType type = static_cast<OatClassType>(*reinterpret_cast<const uint16_t*>(type_pointer));
1703 CHECK_LT(type, kOatClassMax);
1704
Ian Rogers13735952014-10-08 12:43:28 -07001705 const uint8_t* after_type_pointer = type_pointer + sizeof(int16_t);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001706 CHECK_LE(after_type_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07001707
Brian Carlstromcd937a92014-03-04 22:53:23 -08001708 uint32_t bitmap_size = 0;
Ian Rogers13735952014-10-08 12:43:28 -07001709 const uint8_t* bitmap_pointer = nullptr;
1710 const uint8_t* methods_pointer = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07001711 if (type != kOatClassNoneCompiled) {
1712 if (type == kOatClassSomeCompiled) {
1713 bitmap_size = static_cast<uint32_t>(*reinterpret_cast<const uint32_t*>(after_type_pointer));
1714 bitmap_pointer = after_type_pointer + sizeof(bitmap_size);
1715 CHECK_LE(bitmap_pointer, oat_file_->End()) << oat_file_->GetLocation();
1716 methods_pointer = bitmap_pointer + bitmap_size;
1717 } else {
1718 methods_pointer = after_type_pointer;
1719 }
1720 CHECK_LE(methods_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstromcd937a92014-03-04 22:53:23 -08001721 }
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001722
Richard Uhler07b3c232015-03-31 15:57:54 -07001723 return OatFile::OatClass(oat_file_,
1724 status,
1725 type,
1726 bitmap_size,
1727 reinterpret_cast<const uint32_t*>(bitmap_pointer),
1728 reinterpret_cast<const OatMethodOffsets*>(methods_pointer));
Brian Carlstrome24fa612011-09-29 00:53:55 -07001729}
1730
David Sehr9aa352e2016-09-15 18:13:52 -07001731const DexFile::ClassDef* OatFile::OatDexFile::FindClassDef(const DexFile& dex_file,
1732 const char* descriptor,
1733 size_t hash) {
1734 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1735 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
1736 if (LIKELY((oat_dex_file != nullptr) && (oat_dex_file->GetTypeLookupTable() != nullptr))) {
1737 const uint32_t class_def_idx = oat_dex_file->GetTypeLookupTable()->Lookup(descriptor, hash);
Andreas Gampee2abbc62017-09-15 11:59:26 -07001738 return (class_def_idx != dex::kDexNoIndex) ? &dex_file.GetClassDef(class_def_idx) : nullptr;
David Sehr9aa352e2016-09-15 18:13:52 -07001739 }
1740 // Fast path for rare no class defs case.
1741 const uint32_t num_class_defs = dex_file.NumClassDefs();
1742 if (num_class_defs == 0) {
1743 return nullptr;
1744 }
1745 const DexFile::TypeId* type_id = dex_file.FindTypeId(descriptor);
1746 if (type_id != nullptr) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001747 dex::TypeIndex type_idx = dex_file.GetIndexForTypeId(*type_id);
David Sehr9aa352e2016-09-15 18:13:52 -07001748 return dex_file.FindClassDef(type_idx);
1749 }
1750 return nullptr;
1751}
1752
Mathieu Chartier120aa282017-08-05 16:03:03 -07001753// Madvise the dex file based on the state we are moving to.
1754void OatDexFile::MadviseDexFile(const DexFile& dex_file, MadviseState state) {
Mathieu Chartierc42cb0e2017-10-13 11:35:00 -07001755 Runtime* const runtime = Runtime::Current();
1756 const bool low_ram = runtime->GetHeap()->IsLowMemoryMode();
Mathieu Chartier150d25d2017-08-28 09:52:55 -07001757 // TODO: Also do madvise hints for non low ram devices.
Mathieu Chartierc42cb0e2017-10-13 11:35:00 -07001758 if (!low_ram) {
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001759 return;
1760 }
Mathieu Chartierc42cb0e2017-10-13 11:35:00 -07001761 if (state == MadviseState::kMadviseStateAtLoad && runtime->MAdviseRandomAccess()) {
1762 // Default every dex file to MADV_RANDOM when its loaded by default for low ram devices.
1763 // Other devices have enough page cache to get performance benefits from loading more pages
1764 // into the page cache.
1765 MadviseLargestPageAlignedRegion(dex_file.Begin(),
1766 dex_file.Begin() + dex_file.Size(),
1767 MADV_RANDOM);
Mathieu Chartier120aa282017-08-05 16:03:03 -07001768 }
1769 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1770 if (oat_dex_file != nullptr) {
1771 // Should always be there.
1772 const DexLayoutSections* const sections = oat_dex_file->GetDexLayoutSections();
1773 CHECK(sections != nullptr);
1774 sections->Madvise(&dex_file, state);
1775 }
1776}
1777
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001778OatFile::OatClass::OatClass(const OatFile* oat_file,
Vladimir Marko2c64a832018-01-04 11:31:56 +00001779 ClassStatus status,
Brian Carlstromba150c32013-08-27 17:31:03 -07001780 OatClassType type,
1781 uint32_t bitmap_size,
1782 const uint32_t* bitmap_pointer,
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001783 const OatMethodOffsets* methods_pointer)
Brian Carlstromba150c32013-08-27 17:31:03 -07001784 : oat_file_(oat_file), status_(status), type_(type),
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001785 bitmap_(bitmap_pointer), methods_pointer_(methods_pointer) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001786 switch (type_) {
1787 case kOatClassAllCompiled: {
1788 CHECK_EQ(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001789 CHECK(bitmap_pointer == nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001790 CHECK(methods_pointer != nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001791 break;
1792 }
1793 case kOatClassSomeCompiled: {
1794 CHECK_NE(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001795 CHECK(bitmap_pointer != nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001796 CHECK(methods_pointer != nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001797 break;
1798 }
1799 case kOatClassNoneCompiled: {
1800 CHECK_EQ(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001801 CHECK(bitmap_pointer == nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001802 CHECK(methods_pointer_ == nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001803 break;
1804 }
1805 case kOatClassMax: {
1806 LOG(FATAL) << "Invalid OatClassType " << type_;
1807 break;
1808 }
1809 }
1810}
Brian Carlstrome24fa612011-09-29 00:53:55 -07001811
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001812uint32_t OatFile::OatClass::GetOatMethodOffsetsOffset(uint32_t method_index) const {
1813 const OatMethodOffsets* oat_method_offsets = GetOatMethodOffsets(method_index);
1814 if (oat_method_offsets == nullptr) {
1815 return 0u;
1816 }
1817 return reinterpret_cast<const uint8_t*>(oat_method_offsets) - oat_file_->Begin();
1818}
1819
1820const OatMethodOffsets* OatFile::OatClass::GetOatMethodOffsets(uint32_t method_index) const {
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001821 // 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 -07001822 if (methods_pointer_ == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001823 CHECK_EQ(kOatClassNoneCompiled, type_);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001824 return nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07001825 }
1826 size_t methods_pointer_index;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001827 if (bitmap_ == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001828 CHECK_EQ(kOatClassAllCompiled, type_);
1829 methods_pointer_index = method_index;
1830 } else {
1831 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001832 if (!BitVector::IsBitSet(bitmap_, method_index)) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001833 return nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07001834 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001835 size_t num_set_bits = BitVector::NumSetBits(bitmap_, method_index);
1836 methods_pointer_index = num_set_bits;
Brian Carlstromba150c32013-08-27 17:31:03 -07001837 }
1838 const OatMethodOffsets& oat_method_offsets = methods_pointer_[methods_pointer_index];
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001839 return &oat_method_offsets;
1840}
1841
1842const OatFile::OatMethod OatFile::OatClass::GetOatMethod(uint32_t method_index) const {
1843 const OatMethodOffsets* oat_method_offsets = GetOatMethodOffsets(method_index);
1844 if (oat_method_offsets == nullptr) {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001845 return OatMethod(nullptr, 0);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001846 }
1847 if (oat_file_->IsExecutable() ||
1848 Runtime::Current() == nullptr || // This case applies for oatdump.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001849 Runtime::Current()->IsAotCompiler()) {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001850 return OatMethod(oat_file_->Begin(), oat_method_offsets->code_offset_);
Alex Light9dcc4572014-08-14 14:16:26 -07001851 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001852 // We aren't allowed to use the compiled code. We just force it down the interpreted / jit
1853 // version.
1854 return OatMethod(oat_file_->Begin(), 0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001855}
1856
Mathieu Chartiere401d142015-04-22 13:56:20 -07001857void OatFile::OatMethod::LinkMethod(ArtMethod* method) const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001858 CHECK(method != nullptr);
Ian Rogersef7d42f2014-01-06 12:55:46 -08001859 method->SetEntryPointFromQuickCompiledCode(GetQuickCode());
Brian Carlstromae826982011-11-09 01:33:42 -08001860}
1861
Andreas Gampe7ba64962014-10-23 11:37:40 -07001862bool OatFile::IsPic() const {
Igor Murashkin46774762014-10-22 11:37:02 -07001863 return GetOatHeader().IsPic();
Andreas Gampe7ba64962014-10-23 11:37:40 -07001864 // TODO: Check against oat_patches. b/18144996
1865}
1866
Sebastien Hertz0de11332015-05-13 12:14:05 +02001867bool OatFile::IsDebuggable() const {
1868 return GetOatHeader().IsDebuggable();
1869}
1870
Andreas Gampe29d38e72016-03-23 15:31:51 +00001871CompilerFilter::Filter OatFile::GetCompilerFilter() const {
1872 return GetOatHeader().GetCompilerFilter();
Calin Juravleb077e152016-02-18 18:47:37 +00001873}
1874
Calin Juravle44e5efa2017-09-12 00:54:26 -07001875std::string OatFile::GetClassLoaderContext() const {
1876 return GetOatHeader().GetStoreValueByKey(OatHeader::kClassPathKey);
Igor Murashkin2ffb7032017-11-08 13:35:21 -08001877}
Calin Juravle44e5efa2017-09-12 00:54:26 -07001878
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001879OatFile::OatClass OatFile::FindOatClass(const DexFile& dex_file,
1880 uint16_t class_def_idx,
1881 bool* found) {
1882 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
1883 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Mathieu Chartier1b868492016-11-16 16:22:37 -08001884 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001885 *found = false;
1886 return OatFile::OatClass::Invalid();
1887 }
1888 *found = true;
1889 return oat_dex_file->GetOatClass(class_def_idx);
1890}
1891
Mathieu Chartier1b868492016-11-16 16:22:37 -08001892void OatFile::OatDexFile::AssertAotCompiler() {
1893 CHECK(Runtime::Current()->IsAotCompiler());
1894}
1895
Brian Carlstrome24fa612011-09-29 00:53:55 -07001896} // namespace art