blob: 73820c10ccfd8266c7dde7fd0ff38a45b03144da [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Brian Carlstrome24fa612011-09-29 00:53:55 -070016
17#include "oat_file.h"
18
Brian Carlstrom700c8d32012-11-05 10:42:02 -080019#include <dlfcn.h>
David Srbecky1baabf02015-06-16 17:12:34 +000020#ifndef __APPLE__
21#include <link.h> // for dl_iterate_phdr.
22#endif
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070023#include <unistd.h>
24
25#include <cstdlib>
26#include <cstring>
Richard Uhlere5fed032015-03-18 08:21:11 -070027#include <sstream>
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070028#include <type_traits>
Shubham Ajmerab22dea02017-10-04 18:36:41 -070029#include <sys/stat.h>
Richard Uhlere5fed032015-03-18 08:21:11 -070030
Andreas Gampefa8429b2015-04-07 18:34:42 -070031// dlopen_ext support from bionic.
Bilyan Borisovbb661c02016-04-04 16:27:32 +010032#ifdef ART_TARGET_ANDROID
Andreas Gampefa8429b2015-04-07 18:34:42 -070033#include "android/dlext.h"
34#endif
35
Andreas Gampe46ee31b2016-12-14 10:11:49 -080036#include "android-base/stringprintf.h"
37
Andreas Gampec6ea7d02017-02-01 16:46:28 -080038#include "art_method.h"
Brian Carlstromba150c32013-08-27 17:31:03 -070039#include "base/bit_vector.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070040#include "base/enums.h"
David Sehr891a50e2017-10-27 17:01:07 -070041#include "base/file_utils.h"
Andreas Gampe170331f2017-12-07 18:41:03 -080042#include "base/logging.h" // For VLOG_IS_ON.
Elliott Hughes1aa246d2012-12-13 09:29:36 -080043#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080044#include "base/systrace.h"
Elliott Hughes76160052012-12-12 16:31:20 -080045#include "base/unix_file/fd_file.h"
Andreas Gampea5b09a62016-11-17 15:21:22 -080046#include "dex_file_types.h"
Mathieu Chartier79c87da2017-10-10 11:54:29 -070047#include "dex_file_loader.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080048#include "elf_file.h"
Alex Light84d76052014-08-22 17:49:35 -070049#include "elf_utils.h"
Vladimir Markoaad75c62016-10-03 08:46:48 +000050#include "gc_root.h"
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +010051#include "gc/space/image_space.h"
David Srbecky1baabf02015-06-16 17:12:34 +000052#include "mem_map.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080053#include "mirror/class.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070054#include "mirror/object-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070055#include "oat.h"
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +010056#include "oat_file-inl.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070057#include "oat_file_manager.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070058#include "os.h"
Andreas Gampe22f8e5c2014-07-09 11:38:21 -070059#include "runtime.h"
Mathieu Chartier292567e2017-10-12 13:24:38 -070060#include "standard_dex_file.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000061#include "type_lookup_table.h"
David Sehr9aa352e2016-09-15 18:13:52 -070062#include "utf-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080063#include "utils.h"
Vladimir Marko97d7e1c2016-10-04 14:44:28 +010064#include "vdex_file.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070065
66namespace art {
67
Andreas Gampe46ee31b2016-12-14 10:11:49 -080068using android::base::StringPrintf;
69
Andreas Gampe049cff02015-12-01 23:27:12 -080070// Whether OatFile::Open will try dlopen. Fallback is our own ELF loader.
David Srbecky1baabf02015-06-16 17:12:34 +000071static constexpr bool kUseDlopen = true;
Andreas Gampefa8429b2015-04-07 18:34:42 -070072
Andreas Gampe049cff02015-12-01 23:27:12 -080073// Whether OatFile::Open will try dlopen on the host. On the host we're not linking against
Andreas Gampefa8429b2015-04-07 18:34:42 -070074// bionic, so cannot take advantage of the support for changed semantics (loading the same soname
75// multiple times). However, if/when we switch the above, we likely want to switch this, too,
76// to get test coverage of the code paths.
David Srbecky1baabf02015-06-16 17:12:34 +000077static constexpr bool kUseDlopenOnHost = true;
Andreas Gampefa8429b2015-04-07 18:34:42 -070078
79// For debugging, Open will print DlOpen error message if set to true.
80static constexpr bool kPrintDlOpenErrorMessage = false;
81
Andreas Gampe049cff02015-12-01 23:27:12 -080082// Note for OatFileBase and descendents:
83//
84// These are used in OatFile::Open to try all our loaders.
85//
86// The process is simple:
87//
88// 1) Allocate an instance through the standard constructor (location, executable)
89// 2) Load() to try to open the file.
90// 3) ComputeFields() to populate the OatFile fields like begin_, using FindDynamicSymbolAddress.
91// 4) PreSetup() for any steps that should be done before the final setup.
92// 5) Setup() to complete the procedure.
Richard Uhlere5fed032015-03-18 08:21:11 -070093
Andreas Gampe049cff02015-12-01 23:27:12 -080094class OatFileBase : public OatFile {
95 public:
96 virtual ~OatFileBase() {}
Richard Uhlere5fed032015-03-18 08:21:11 -070097
Andreas Gampe049cff02015-12-01 23:27:12 -080098 template <typename kOatFileBaseSubType>
David Brazdil7b49e6c2016-09-01 11:06:18 +010099 static OatFileBase* OpenOatFile(const std::string& vdex_filename,
100 const std::string& elf_filename,
Alex Light84d76052014-08-22 17:49:35 -0700101 const std::string& location,
Andreas Gampe049cff02015-12-01 23:27:12 -0800102 uint8_t* requested_base,
103 uint8_t* oat_file_begin,
104 bool writable,
105 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800106 bool low_4gb,
Richard Uhlere5fed032015-03-18 08:21:11 -0700107 const char* abs_dex_location,
Andreas Gampe049cff02015-12-01 23:27:12 -0800108 std::string* error_msg);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800109
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700110 template <typename kOatFileBaseSubType>
111 static OatFileBase* OpenOatFile(int vdex_fd,
112 int oat_fd,
113 const std::string& vdex_filename,
114 const std::string& oat_filename,
115 uint8_t* requested_base,
116 uint8_t* oat_file_begin,
117 bool writable,
118 bool executable,
119 bool low_4gb,
120 const char* abs_dex_location,
121 std::string* error_msg);
122
Andreas Gampe049cff02015-12-01 23:27:12 -0800123 protected:
124 OatFileBase(const std::string& filename, bool executable) : OatFile(filename, executable) {}
Andreas Gampefa8429b2015-04-07 18:34:42 -0700125
Andreas Gampe049cff02015-12-01 23:27:12 -0800126 virtual const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
127 std::string* error_msg) const = 0;
128
Andreas Gampe4075f832016-05-18 13:09:54 -0700129 virtual void PreLoad() = 0;
130
David Brazdil7b49e6c2016-09-01 11:06:18 +0100131 bool LoadVdex(const std::string& vdex_filename,
132 bool writable,
133 bool low_4gb,
134 std::string* error_msg);
135
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700136 bool LoadVdex(int vdex_fd,
137 const std::string& vdex_filename,
138 bool writable,
139 bool low_4gb,
140 std::string* error_msg);
141
Andreas Gampe049cff02015-12-01 23:27:12 -0800142 virtual bool Load(const std::string& elf_filename,
143 uint8_t* oat_file_begin,
144 bool writable,
145 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800146 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800147 std::string* error_msg) = 0;
148
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700149 virtual bool Load(int oat_fd,
150 uint8_t* oat_file_begin,
151 bool writable,
152 bool executable,
153 bool low_4gb,
154 std::string* error_msg) = 0;
155
Andreas Gampe049cff02015-12-01 23:27:12 -0800156 bool ComputeFields(uint8_t* requested_base,
157 const std::string& file_path,
158 std::string* error_msg);
159
160 virtual void PreSetup(const std::string& elf_filename) = 0;
161
162 bool Setup(const char* abs_dex_location, std::string* error_msg);
163
164 // Setters exposed for ElfOatFile.
165
166 void SetBegin(const uint8_t* begin) {
167 begin_ = begin;
Andreas Gampefa8429b2015-04-07 18:34:42 -0700168 }
169
Andreas Gampe049cff02015-12-01 23:27:12 -0800170 void SetEnd(const uint8_t* end) {
171 end_ = end;
172 }
173
David Brazdilc93b3be2016-09-12 18:49:58 +0100174 void SetVdex(VdexFile* vdex) {
175 vdex_.reset(vdex);
176 }
177
Andreas Gampe049cff02015-12-01 23:27:12 -0800178 private:
179 DISALLOW_COPY_AND_ASSIGN(OatFileBase);
180};
181
182template <typename kOatFileBaseSubType>
David Brazdil7b49e6c2016-09-01 11:06:18 +0100183OatFileBase* OatFileBase::OpenOatFile(const std::string& vdex_filename,
184 const std::string& elf_filename,
Andreas Gampe049cff02015-12-01 23:27:12 -0800185 const std::string& location,
186 uint8_t* requested_base,
187 uint8_t* oat_file_begin,
188 bool writable,
189 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800190 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800191 const char* abs_dex_location,
192 std::string* error_msg) {
193 std::unique_ptr<OatFileBase> ret(new kOatFileBaseSubType(location, executable));
Andreas Gampe4075f832016-05-18 13:09:54 -0700194
195 ret->PreLoad();
196
Andreas Gampe049cff02015-12-01 23:27:12 -0800197 if (!ret->Load(elf_filename,
198 oat_file_begin,
199 writable,
200 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800201 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800202 error_msg)) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800203 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800204 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800205
Andreas Gampe049cff02015-12-01 23:27:12 -0800206 if (!ret->ComputeFields(requested_base, elf_filename, error_msg)) {
207 return nullptr;
208 }
Andreas Gampe4075f832016-05-18 13:09:54 -0700209
David Srbeckyec2cdf42017-12-08 16:21:25 +0000210 if (!ret->LoadVdex(vdex_filename, writable, low_4gb, error_msg)) {
211 return nullptr;
212 }
213
Andreas Gampe049cff02015-12-01 23:27:12 -0800214 ret->PreSetup(elf_filename);
215
216 if (!ret->Setup(abs_dex_location, error_msg)) {
217 return nullptr;
218 }
219
Dave Allison69dfe512014-07-11 17:11:58 +0000220 return ret.release();
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800221}
222
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700223template <typename kOatFileBaseSubType>
224OatFileBase* OatFileBase::OpenOatFile(int vdex_fd,
225 int oat_fd,
226 const std::string& vdex_location,
227 const std::string& oat_location,
228 uint8_t* requested_base,
229 uint8_t* oat_file_begin,
230 bool writable,
231 bool executable,
232 bool low_4gb,
233 const char* abs_dex_location,
234 std::string* error_msg) {
235 std::unique_ptr<OatFileBase> ret(new kOatFileBaseSubType(oat_location, executable));
236
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700237 if (!ret->Load(oat_fd,
238 oat_file_begin,
239 writable,
240 executable,
241 low_4gb,
242 error_msg)) {
243 return nullptr;
244 }
245
246 if (!ret->ComputeFields(requested_base, oat_location, error_msg)) {
247 return nullptr;
248 }
249
David Srbeckyec2cdf42017-12-08 16:21:25 +0000250 if (!ret->LoadVdex(vdex_fd, vdex_location, writable, low_4gb, error_msg)) {
251 return nullptr;
252 }
253
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700254 ret->PreSetup(oat_location);
255
256 if (!ret->Setup(abs_dex_location, error_msg)) {
257 return nullptr;
258 }
259
260 return ret.release();
261}
262
David Brazdil7b49e6c2016-09-01 11:06:18 +0100263bool OatFileBase::LoadVdex(const std::string& vdex_filename,
264 bool writable,
265 bool low_4gb,
266 std::string* error_msg) {
David Srbeckyec2cdf42017-12-08 16:21:25 +0000267 vdex_ = VdexFile::OpenAtAddress(vdex_begin_,
268 vdex_end_ - vdex_begin_,
269 true /* mmap_reuse */,
270 vdex_filename,
271 writable,
272 low_4gb,
273 /* unquicken*/ false,
274 error_msg);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100275 if (vdex_.get() == nullptr) {
276 *error_msg = StringPrintf("Failed to load vdex file '%s' %s",
277 vdex_filename.c_str(),
278 error_msg->c_str());
279 return false;
280 }
281 return true;
282}
283
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700284bool OatFileBase::LoadVdex(int vdex_fd,
285 const std::string& vdex_filename,
286 bool writable,
287 bool low_4gb,
288 std::string* error_msg) {
289 if (vdex_fd != -1) {
290 struct stat s;
291 int rc = TEMP_FAILURE_RETRY(fstat(vdex_fd, &s));
292 if (rc == -1) {
293 PLOG(WARNING) << "Failed getting length of vdex file";
294 } else {
David Srbeckyec2cdf42017-12-08 16:21:25 +0000295 vdex_ = VdexFile::OpenAtAddress(vdex_begin_,
296 vdex_end_ - vdex_begin_,
297 true /* mmap_reuse */,
298 vdex_fd,
299 s.st_size,
300 vdex_filename,
301 writable,
302 low_4gb,
303 false /* unquicken */,
304 error_msg);
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700305 if (vdex_.get() == nullptr) {
306 *error_msg = "Failed opening vdex file.";
307 return false;
308 }
309 }
310 }
311 return true;
312}
313
Andreas Gampe049cff02015-12-01 23:27:12 -0800314bool OatFileBase::ComputeFields(uint8_t* requested_base,
315 const std::string& file_path,
316 std::string* error_msg) {
317 std::string symbol_error_msg;
318 begin_ = FindDynamicSymbolAddress("oatdata", &symbol_error_msg);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700319 if (begin_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800320 *error_msg = StringPrintf("Failed to find oatdata symbol in '%s' %s",
321 file_path.c_str(),
322 symbol_error_msg.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700323 return false;
324 }
325 if (requested_base != nullptr && begin_ != requested_base) {
Nicolas Geoffrayf97cf2a2016-03-09 15:36:23 +0000326 // Host can fail this check. Do not dump there to avoid polluting the output.
Andreas Gampe7ec09042016-04-01 17:20:49 -0700327 if (kIsTargetBuild && (kIsDebugBuild || VLOG_IS_ON(oat))) {
Andreas Gampe170331f2017-12-07 18:41:03 -0800328 PrintFileToLog("/proc/self/maps", android::base::LogSeverity::WARNING);
Nicolas Geoffrayf97cf2a2016-03-09 15:36:23 +0000329 }
Andreas Gampefa8429b2015-04-07 18:34:42 -0700330 *error_msg = StringPrintf("Failed to find oatdata symbol at expected address: "
Andreas Gampe049cff02015-12-01 23:27:12 -0800331 "oatdata=%p != expected=%p. See process maps in the log.",
332 begin_, requested_base);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700333 return false;
334 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800335 end_ = FindDynamicSymbolAddress("oatlastword", &symbol_error_msg);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700336 if (end_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800337 *error_msg = StringPrintf("Failed to find oatlastword symbol in '%s' %s",
338 file_path.c_str(),
339 symbol_error_msg.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700340 return false;
341 }
342 // Readjust to be non-inclusive upper bound.
343 end_ += sizeof(uint32_t);
344
Andreas Gampe049cff02015-12-01 23:27:12 -0800345 bss_begin_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbss", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700346 if (bss_begin_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800347 // No .bss section.
Andreas Gampefa8429b2015-04-07 18:34:42 -0700348 bss_end_ = nullptr;
Andreas Gampefa8429b2015-04-07 18:34:42 -0700349 } else {
Andreas Gampe049cff02015-12-01 23:27:12 -0800350 bss_end_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbsslastword", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700351 if (bss_end_ == nullptr) {
David Srbeckyec2cdf42017-12-08 16:21:25 +0000352 *error_msg = StringPrintf("Failed to find oatbsslastword symbol in '%s'", file_path.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700353 return false;
354 }
355 // Readjust to be non-inclusive upper bound.
356 bss_end_ += sizeof(uint32_t);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100357 // Find bss methods if present.
358 bss_methods_ =
359 const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbssmethods", &symbol_error_msg));
Vladimir Markoaad75c62016-10-03 08:46:48 +0000360 // Find bss roots if present.
361 bss_roots_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbssroots", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700362 }
363
David Srbeckyec2cdf42017-12-08 16:21:25 +0000364 vdex_begin_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatdex", &symbol_error_msg));
365 if (vdex_begin_ == nullptr) {
366 // No .vdex section.
367 vdex_end_ = nullptr;
368 } else {
369 vdex_end_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatdexlastword", &symbol_error_msg));
370 if (vdex_end_ == nullptr) {
371 *error_msg = StringPrintf("Failed to find oatdexlastword symbol in '%s'", file_path.c_str());
372 return false;
373 }
374 // Readjust to be non-inclusive upper bound.
375 vdex_end_ += sizeof(uint32_t);
376 }
377
Andreas Gampe049cff02015-12-01 23:27:12 -0800378 return true;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800379}
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800380
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100381// Read an unaligned entry from the OatDexFile data in OatFile and advance the read
382// position by the number of bytes read, i.e. sizeof(T).
383// Return true on success, false if the read would go beyond the end of the OatFile.
384template <typename T>
Vladimir Marko722fa982015-10-19 18:18:27 +0100385inline static bool ReadOatDexFileData(const OatFile& oat_file,
386 /*inout*/const uint8_t** oat,
387 /*out*/T* value) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100388 DCHECK(oat != nullptr);
389 DCHECK(value != nullptr);
390 DCHECK_LE(*oat, oat_file.End());
391 if (UNLIKELY(static_cast<size_t>(oat_file.End() - *oat) < sizeof(T))) {
392 return false;
393 }
394 static_assert(std::is_trivial<T>::value, "T must be a trivial type");
395 typedef __attribute__((__aligned__(1))) T unaligned_type;
396 *value = *reinterpret_cast<const unaligned_type*>(*oat);
397 *oat += sizeof(T);
398 return true;
399}
400
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100401static inline bool MapConstantTables(const gc::space::ImageSpace* space,
402 uint8_t* address) {
403 // If MREMAP_DUP is ever merged to Linux kernel, use it to avoid the unnecessary open()/close().
404 // Note: The current approach relies on the filename still referencing the same inode.
405
406 File file(space->GetImageFilename(), O_RDONLY, /* checkUsage */ false);
407 if (!file.IsOpened()) {
408 LOG(ERROR) << "Failed to open boot image file " << space->GetImageFilename();
409 return false;
410 }
411
412 uint32_t offset = space->GetImageHeader().GetBootImageConstantTablesOffset();
413 uint32_t size = space->GetImageHeader().GetBootImageConstantTablesSize();
414 std::string error_msg;
415 std::unique_ptr<MemMap> mem_map(MemMap::MapFileAtAddress(address,
416 size,
417 PROT_READ,
418 MAP_PRIVATE,
419 file.Fd(),
420 offset,
421 /* low_4gb */ false,
422 /* reuse */ true,
423 file.GetPath().c_str(),
424 &error_msg));
425 if (mem_map == nullptr) {
426 LOG(ERROR) << "Failed to mmap boot image tables from file " << space->GetImageFilename();
427 return false;
428 }
429 return true;
430}
431
Vladimir Markof3c52b42017-11-17 17:32:12 +0000432static bool ReadIndexBssMapping(OatFile* oat_file,
433 /*inout*/const uint8_t** oat,
434 size_t dex_file_index,
435 const std::string& dex_file_location,
436 const char* tag,
437 /*out*/const IndexBssMapping** mapping,
438 std::string* error_msg) {
439 uint32_t index_bss_mapping_offset;
440 if (UNLIKELY(!ReadOatDexFileData(*oat_file, oat, &index_bss_mapping_offset))) {
441 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zd for '%s' truncated "
442 "after %s bss mapping offset",
443 oat_file->GetLocation().c_str(),
444 dex_file_index,
445 dex_file_location.c_str(),
446 tag);
447 return false;
448 }
449 const bool readable_index_bss_mapping_size =
450 index_bss_mapping_offset != 0u &&
451 index_bss_mapping_offset <= oat_file->Size() &&
452 IsAligned<alignof(IndexBssMapping)>(index_bss_mapping_offset) &&
453 oat_file->Size() - index_bss_mapping_offset >= IndexBssMapping::ComputeSize(0);
454 const IndexBssMapping* index_bss_mapping = readable_index_bss_mapping_size
455 ? reinterpret_cast<const IndexBssMapping*>(oat_file->Begin() + index_bss_mapping_offset)
456 : nullptr;
457 if (index_bss_mapping_offset != 0u &&
458 (UNLIKELY(index_bss_mapping == nullptr) ||
459 UNLIKELY(index_bss_mapping->size() == 0u) ||
460 UNLIKELY(oat_file->Size() - index_bss_mapping_offset <
461 IndexBssMapping::ComputeSize(index_bss_mapping->size())))) {
462 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with unaligned or "
463 " truncated %s bss mapping, offset %u of %zu, length %zu",
464 oat_file->GetLocation().c_str(),
465 dex_file_index,
466 dex_file_location.c_str(),
467 tag,
468 index_bss_mapping_offset,
469 oat_file->Size(),
470 index_bss_mapping != nullptr ? index_bss_mapping->size() : 0u);
471 return false;
472 }
473
474 *mapping = index_bss_mapping;
475 return true;
476}
477
478static void DCheckIndexToBssMapping(OatFile* oat_file,
479 uint32_t number_of_indexes,
480 size_t slot_size,
481 const IndexBssMapping* index_bss_mapping) {
482 if (kIsDebugBuild && index_bss_mapping != nullptr) {
483 size_t index_bits = IndexBssMappingEntry::IndexBits(number_of_indexes);
484 const IndexBssMappingEntry* prev_entry = nullptr;
485 for (const IndexBssMappingEntry& entry : *index_bss_mapping) {
486 CHECK_ALIGNED_PARAM(entry.bss_offset, slot_size);
487 // When loading a non-executable ElfOatFile, .bss symbols are not even
488 // looked up, so we cannot verify the offset against BssSize().
489 if (oat_file->IsExecutable()) {
490 CHECK_LT(entry.bss_offset, oat_file->BssSize());
491 }
492 uint32_t mask = entry.GetMask(index_bits);
493 CHECK_LE(POPCOUNT(mask) * slot_size, entry.bss_offset);
494 size_t index_mask_span = (mask != 0u) ? 32u - index_bits - CTZ(mask) : 0u;
495 CHECK_LE(index_mask_span, entry.GetIndex(index_bits));
496 if (prev_entry != nullptr) {
497 CHECK_LT(prev_entry->GetIndex(index_bits), entry.GetIndex(index_bits) - index_mask_span);
498 }
499 prev_entry = &entry;
500 }
501 CHECK_LT(prev_entry->GetIndex(index_bits), number_of_indexes);
502 }
503}
504
Andreas Gampe049cff02015-12-01 23:27:12 -0800505bool OatFileBase::Setup(const char* abs_dex_location, std::string* error_msg) {
Brian Carlstromf1b30302013-03-28 10:35:32 -0700506 if (!GetOatHeader().IsValid()) {
Andreas Gampe2bcb3b22014-12-12 15:25:14 -0800507 std::string cause = GetOatHeader().GetValidationErrorMessage();
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100508 *error_msg = StringPrintf("Invalid oat header for '%s': %s",
509 GetLocation().c_str(),
Andreas Gampe2bcb3b22014-12-12 15:25:14 -0800510 cause.c_str());
Brian Carlstromf1b30302013-03-28 10:35:32 -0700511 return false;
512 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100513 PointerSize pointer_size = GetInstructionSetPointerSize(GetOatHeader().GetInstructionSet());
514 size_t key_value_store_size =
515 (Size() >= sizeof(OatHeader)) ? GetOatHeader().GetKeyValueStoreSize() : 0u;
516 if (Size() < sizeof(OatHeader) + key_value_store_size) {
517 *error_msg = StringPrintf("In oat file '%s' found truncated OatHeader, "
518 "size = %zu < %zu + %zu",
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100519 GetLocation().c_str(),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100520 Size(),
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100521 sizeof(OatHeader),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100522 key_value_store_size);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700523 return false;
524 }
525
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100526 size_t oat_dex_files_offset = GetOatHeader().GetOatDexFilesOffset();
527 if (oat_dex_files_offset < GetOatHeader().GetHeaderSize() || oat_dex_files_offset > Size()) {
528 *error_msg = StringPrintf("In oat file '%s' found invalid oat dex files offset: "
529 "%zu is not in [%zu, %zu]",
530 GetLocation().c_str(),
531 oat_dex_files_offset,
532 GetOatHeader().GetHeaderSize(),
533 Size());
534 return false;
535 }
536 const uint8_t* oat = Begin() + oat_dex_files_offset; // Jump to the OatDexFile records.
537
538 DCHECK_GE(static_cast<size_t>(pointer_size), alignof(GcRoot<mirror::Object>));
539 if (!IsAligned<kPageSize>(bss_begin_) ||
540 !IsAlignedParam(bss_methods_, static_cast<size_t>(pointer_size)) ||
541 !IsAlignedParam(bss_roots_, static_cast<size_t>(pointer_size)) ||
Vladimir Markoaad75c62016-10-03 08:46:48 +0000542 !IsAligned<alignof(GcRoot<mirror::Object>)>(bss_end_)) {
543 *error_msg = StringPrintf("In oat file '%s' found unaligned bss symbol(s): "
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100544 "begin = %p, methods_ = %p, roots = %p, end = %p",
Vladimir Markoaad75c62016-10-03 08:46:48 +0000545 GetLocation().c_str(),
546 bss_begin_,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100547 bss_methods_,
Vladimir Markoaad75c62016-10-03 08:46:48 +0000548 bss_roots_,
549 bss_end_);
550 return false;
551 }
552
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100553 if ((bss_methods_ != nullptr && (bss_methods_ < bss_begin_ || bss_methods_ > bss_end_)) ||
554 (bss_roots_ != nullptr && (bss_roots_ < bss_begin_ || bss_roots_ > bss_end_)) ||
555 (bss_methods_ != nullptr && bss_roots_ != nullptr && bss_methods_ > bss_roots_)) {
556 *error_msg = StringPrintf("In oat file '%s' found bss symbol(s) outside .bss or unordered: "
Vladimir Marko0f3c7002017-09-07 14:15:56 +0100557 "begin = %p, methods = %p, roots = %p, end = %p",
Vladimir Markoaad75c62016-10-03 08:46:48 +0000558 GetLocation().c_str(),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000559 bss_begin_,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100560 bss_methods_,
561 bss_roots_,
Vladimir Markoaad75c62016-10-03 08:46:48 +0000562 bss_end_);
563 return false;
564 }
565
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100566 uint8_t* after_tables =
567 (bss_methods_ != nullptr) ? bss_methods_ : bss_roots_; // May be null.
568 uint8_t* boot_image_tables = (bss_begin_ == after_tables) ? nullptr : bss_begin_;
569 uint8_t* boot_image_tables_end =
570 (bss_begin_ == after_tables) ? nullptr : (after_tables != nullptr) ? after_tables : bss_end_;
571 DCHECK_EQ(boot_image_tables != nullptr, boot_image_tables_end != nullptr);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100572 uint32_t dex_file_count = GetOatHeader().GetDexFileCount();
573 oat_dex_files_storage_.reserve(dex_file_count);
574 for (size_t i = 0; i < dex_file_count; i++) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100575 uint32_t dex_file_location_size;
576 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_location_size))) {
577 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu truncated after dex file "
578 "location size",
579 GetLocation().c_str(),
580 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700581 return false;
582 }
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100583 if (UNLIKELY(dex_file_location_size == 0U)) {
584 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu with empty location name",
585 GetLocation().c_str(),
586 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700587 return false;
588 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000589 if (UNLIKELY(static_cast<size_t>(End() - oat) < dex_file_location_size)) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100590 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu with truncated dex file "
591 "location",
592 GetLocation().c_str(),
593 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700594 return false;
595 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000596 const char* dex_file_location_data = reinterpret_cast<const char*>(oat);
597 oat += dex_file_location_size;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700598
Richard Uhlere5fed032015-03-18 08:21:11 -0700599 std::string dex_file_location = ResolveRelativeEncodedDexLocation(
600 abs_dex_location,
601 std::string(dex_file_location_data, dex_file_location_size));
Brian Carlstrome24fa612011-09-29 00:53:55 -0700602
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100603 uint32_t dex_file_checksum;
604 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_checksum))) {
605 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated after "
606 "dex file checksum",
607 GetLocation().c_str(),
608 i,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700609 dex_file_location.c_str());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700610 return false;
611 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700612
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100613 uint32_t dex_file_offset;
614 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_offset))) {
615 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated "
616 "after dex file offsets",
617 GetLocation().c_str(),
618 i,
619 dex_file_location.c_str());
620 return false;
621 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100622 if (UNLIKELY(dex_file_offset > DexSize())) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100623 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
624 "offset %u > %zu",
625 GetLocation().c_str(),
626 i,
627 dex_file_location.c_str(),
628 dex_file_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100629 DexSize());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700630 return false;
631 }
Nicolas Geoffrayae7e8382017-11-20 15:10:28 +0000632 const uint8_t* dex_file_pointer = nullptr;
633 if (UNLIKELY(dex_file_offset == 0U)) {
634 if (uncompressed_dex_files_ == nullptr) {
635 uncompressed_dex_files_.reset(new std::vector<std::unique_ptr<const DexFile>>());
636 // No dex files, load it from location.
637 if (!DexFileLoader::Open(dex_file_location.c_str(),
638 dex_file_location,
639 /* verify */ false,
640 /* verify_checksum */ false,
641 error_msg,
642 uncompressed_dex_files_.get())) {
643 return false;
644 }
645 }
646 dex_file_pointer = uncompressed_dex_files_.get()->at(i)->Begin();
647 } else {
648 if (UNLIKELY(DexSize() - dex_file_offset < sizeof(DexFile::Header))) {
649 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
650 "offset %u of %zu but the size of dex file header is %zu",
651 GetLocation().c_str(),
652 i,
653 dex_file_location.c_str(),
654 dex_file_offset,
655 DexSize(),
656 sizeof(DexFile::Header));
657 return false;
658 }
659 dex_file_pointer = DexBegin() + dex_file_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000660 }
Brian Carlstrom89521892011-12-07 22:05:07 -0800661
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700662 const bool valid_magic = DexFileLoader::IsMagicValid(dex_file_pointer);
Mathieu Chartier7b074bf2017-09-25 16:22:36 -0700663 if (UNLIKELY(!valid_magic)) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100664 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with invalid "
665 "dex file magic '%s'",
666 GetLocation().c_str(),
667 i,
668 dex_file_location.c_str(),
669 dex_file_pointer);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700670 return false;
671 }
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700672 if (UNLIKELY(!DexFileLoader::IsVersionAndMagicValid(dex_file_pointer))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100673 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with invalid "
674 "dex file version '%s'",
675 GetLocation().c_str(),
676 i,
677 dex_file_location.c_str(),
678 dex_file_pointer);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700679 return false;
680 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800681 const DexFile::Header* header = reinterpret_cast<const DexFile::Header*>(dex_file_pointer);
Nicolas Geoffrayae7e8382017-11-20 15:10:28 +0000682 if (dex_file_offset != 0 && (DexSize() - dex_file_offset < header->file_size_)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000683 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
684 "offset %u and size %u truncated at %zu",
685 GetLocation().c_str(),
686 i,
687 dex_file_location.c_str(),
688 dex_file_offset,
689 header->file_size_,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100690 DexSize());
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000691 return false;
692 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300693
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000694 uint32_t class_offsets_offset;
695 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &class_offsets_offset))) {
696 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated "
697 "after class offsets offset",
698 GetLocation().c_str(),
699 i,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300700 dex_file_location.c_str());
701 return false;
702 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000703 if (UNLIKELY(class_offsets_offset > Size()) ||
704 UNLIKELY((Size() - class_offsets_offset) / sizeof(uint32_t) < header->class_defs_size_)) {
705 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with truncated "
706 "class offsets, offset %u of %zu, class defs %u",
707 GetLocation().c_str(),
708 i,
709 dex_file_location.c_str(),
710 class_offsets_offset,
711 Size(),
712 header->class_defs_size_);
713 return false;
714 }
715 if (UNLIKELY(!IsAligned<alignof(uint32_t)>(class_offsets_offset))) {
716 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with unaligned "
717 "class offsets, offset %u",
718 GetLocation().c_str(),
719 i,
720 dex_file_location.c_str(),
721 class_offsets_offset);
722 return false;
723 }
724 const uint32_t* class_offsets_pointer =
725 reinterpret_cast<const uint32_t*>(Begin() + class_offsets_offset);
726
727 uint32_t lookup_table_offset;
728 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &lookup_table_offset))) {
729 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zd for '%s' truncated "
730 "after lookup table offset",
731 GetLocation().c_str(),
732 i,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300733 dex_file_location.c_str());
734 return false;
735 }
736 const uint8_t* lookup_table_data = lookup_table_offset != 0u
737 ? Begin() + lookup_table_offset
738 : nullptr;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000739 if (lookup_table_offset != 0u &&
740 (UNLIKELY(lookup_table_offset > Size()) ||
741 UNLIKELY(Size() - lookup_table_offset <
742 TypeLookupTable::RawDataLength(header->class_defs_size_)))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100743 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with truncated "
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000744 "type lookup table, offset %u of %zu, class defs %u",
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100745 GetLocation().c_str(),
746 i,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000747 dex_file_location.c_str(),
748 lookup_table_offset,
749 Size(),
750 header->class_defs_size_);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700751 return false;
752 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700753
Mathieu Chartier120aa282017-08-05 16:03:03 -0700754 uint32_t dex_layout_sections_offset;
755 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_layout_sections_offset))) {
756 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zd for '%s' truncated "
757 "after dex layout sections offset",
758 GetLocation().c_str(),
759 i,
760 dex_file_location.c_str());
761 return false;
762 }
763 const DexLayoutSections* const dex_layout_sections = dex_layout_sections_offset != 0
764 ? reinterpret_cast<const DexLayoutSections*>(Begin() + dex_layout_sections_offset)
765 : nullptr;
766
Vladimir Markof3c52b42017-11-17 17:32:12 +0000767 const IndexBssMapping* method_bss_mapping;
768 const IndexBssMapping* type_bss_mapping;
769 const IndexBssMapping* string_bss_mapping;
770 if (!ReadIndexBssMapping(
771 this, &oat, i, dex_file_location, "method", &method_bss_mapping, error_msg) ||
772 !ReadIndexBssMapping(
773 this, &oat, i, dex_file_location, "type", &type_bss_mapping, error_msg) ||
774 !ReadIndexBssMapping(
775 this, &oat, i, dex_file_location, "string", &string_bss_mapping, error_msg)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100776 return false;
777 }
Vladimir Markof3c52b42017-11-17 17:32:12 +0000778 DCheckIndexToBssMapping(
779 this, header->method_ids_size_, static_cast<size_t>(pointer_size), method_bss_mapping);
780 DCheckIndexToBssMapping(
781 this, header->type_ids_size_, sizeof(GcRoot<mirror::Class>), type_bss_mapping);
782 DCheckIndexToBssMapping(
783 this, header->string_ids_size_, sizeof(GcRoot<mirror::String>), string_bss_mapping);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100784
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700785 std::string canonical_location =
786 DexFileLoader::GetDexCanonicalLocation(dex_file_location.c_str());
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100787
788 // Create the OatDexFile and add it to the owning container.
Vladimir Marko539690a2014-06-05 18:36:42 +0100789 OatDexFile* oat_dex_file = new OatDexFile(this,
790 dex_file_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100791 canonical_location,
Vladimir Marko539690a2014-06-05 18:36:42 +0100792 dex_file_checksum,
793 dex_file_pointer,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300794 lookup_table_data,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100795 method_bss_mapping,
Vladimir Markof3c52b42017-11-17 17:32:12 +0000796 type_bss_mapping,
797 string_bss_mapping,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000798 class_offsets_pointer,
Mathieu Chartier120aa282017-08-05 16:03:03 -0700799 dex_layout_sections);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100800 oat_dex_files_storage_.push_back(oat_dex_file);
801
802 // Add the location and canonical location (if different) to the oat_dex_files_ table.
Vladimir Marko3f5838d2014-08-07 18:07:18 +0100803 StringPiece key(oat_dex_file->GetDexFileLocation());
Vladimir Marko539690a2014-06-05 18:36:42 +0100804 oat_dex_files_.Put(key, oat_dex_file);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100805 if (canonical_location != dex_file_location) {
806 StringPiece canonical_key(oat_dex_file->GetCanonicalDexFileLocation());
807 oat_dex_files_.Put(canonical_key, oat_dex_file);
808 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700809 }
Vladimir Marko09d09432015-09-08 13:47:48 +0100810
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100811 if (boot_image_tables != nullptr) {
Vladimir Marko667585a2017-09-29 10:42:31 +0100812 Runtime* runtime = Runtime::Current();
813 if (UNLIKELY(runtime == nullptr)) {
814 // This must be oatdump without boot image. Make sure the .bss is inaccessible.
Mathieu Chartier8d8de0c2017-10-04 09:35:30 -0700815 CheckedCall(mprotect, "protect bss", const_cast<uint8_t*>(BssBegin()), BssSize(), PROT_NONE);
Vladimir Marko667585a2017-09-29 10:42:31 +0100816 } else {
817 // Map boot image tables into the .bss. The reserved size must match size of the tables.
818 size_t reserved_size = static_cast<size_t>(boot_image_tables_end - boot_image_tables);
819 size_t tables_size = 0u;
820 for (gc::space::ImageSpace* space : runtime->GetHeap()->GetBootImageSpaces()) {
821 tables_size += space->GetImageHeader().GetBootImageConstantTablesSize();
822 DCHECK_ALIGNED(tables_size, kPageSize);
823 }
824 if (tables_size != reserved_size) {
825 *error_msg = StringPrintf("In oat file '%s' found unexpected boot image table sizes, "
826 " %zu bytes, should be %zu.",
827 GetLocation().c_str(),
828 reserved_size,
829 tables_size);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100830 return false;
831 }
Vladimir Marko667585a2017-09-29 10:42:31 +0100832 for (gc::space::ImageSpace* space : Runtime::Current()->GetHeap()->GetBootImageSpaces()) {
833 uint32_t current_tables_size = space->GetImageHeader().GetBootImageConstantTablesSize();
834 if (current_tables_size != 0u && !MapConstantTables(space, boot_image_tables)) {
835 return false;
836 }
837 boot_image_tables += current_tables_size;
838 }
839 DCHECK(boot_image_tables == boot_image_tables_end);
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100840 }
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +0100841 }
Brian Carlstromf1b30302013-03-28 10:35:32 -0700842 return true;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700843}
844
Andreas Gampe049cff02015-12-01 23:27:12 -0800845////////////////////////
846// OatFile via dlopen //
847////////////////////////
848
Andreas Gampe049cff02015-12-01 23:27:12 -0800849class DlOpenOatFile FINAL : public OatFileBase {
850 public:
851 DlOpenOatFile(const std::string& filename, bool executable)
852 : OatFileBase(filename, executable),
853 dlopen_handle_(nullptr),
Richard Uhlera206c742016-05-24 15:04:22 -0700854 shared_objects_before_(0) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800855 }
856
857 ~DlOpenOatFile() {
858 if (dlopen_handle_ != nullptr) {
Richard Uhlera206c742016-05-24 15:04:22 -0700859 if (!kIsTargetBuild) {
860 MutexLock mu(Thread::Current(), *Locks::host_dlopen_handles_lock_);
861 host_dlopen_handles_.erase(dlopen_handle_);
Mathieu Chartierc7d3f4b2016-06-01 10:48:19 -0700862 dlclose(dlopen_handle_);
863 } else {
864 dlclose(dlopen_handle_);
Richard Uhlera206c742016-05-24 15:04:22 -0700865 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800866 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800867 }
868
869 protected:
870 const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
871 std::string* error_msg) const OVERRIDE {
872 const uint8_t* ptr =
873 reinterpret_cast<const uint8_t*>(dlsym(dlopen_handle_, symbol_name.c_str()));
874 if (ptr == nullptr) {
875 *error_msg = dlerror();
876 }
877 return ptr;
878 }
879
Andreas Gampe4075f832016-05-18 13:09:54 -0700880 void PreLoad() OVERRIDE;
881
Andreas Gampe049cff02015-12-01 23:27:12 -0800882 bool Load(const std::string& elf_filename,
883 uint8_t* oat_file_begin,
884 bool writable,
885 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800886 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800887 std::string* error_msg) OVERRIDE;
888
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700889 bool Load(int, uint8_t*, bool, bool, bool, std::string*) {
890 return false;
891 }
892
Andreas Gampe049cff02015-12-01 23:27:12 -0800893 // Ask the linker where it mmaped the file and notify our mmap wrapper of the regions.
894 void PreSetup(const std::string& elf_filename) OVERRIDE;
895
896 private:
897 bool Dlopen(const std::string& elf_filename,
898 uint8_t* oat_file_begin,
899 std::string* error_msg);
900
Richard Uhlera206c742016-05-24 15:04:22 -0700901 // On the host, if the same library is loaded again with dlopen the same
902 // file handle is returned. This differs from the behavior of dlopen on the
903 // target, where dlopen reloads the library at a different address every
904 // time you load it. The runtime relies on the target behavior to ensure
905 // each instance of the loaded library has a unique dex cache. To avoid
906 // problems, we fall back to our own linker in the case when the same
907 // library is opened multiple times on host. dlopen_handles_ is used to
908 // detect that case.
909 // Guarded by host_dlopen_handles_lock_;
910 static std::unordered_set<void*> host_dlopen_handles_;
911
Andreas Gampe049cff02015-12-01 23:27:12 -0800912 // dlopen handle during runtime.
913 void* dlopen_handle_; // TODO: Unique_ptr with custom deleter.
914
915 // Dummy memory map objects corresponding to the regions mapped by dlopen.
916 std::vector<std::unique_ptr<MemMap>> dlopen_mmaps_;
917
Andreas Gampe4075f832016-05-18 13:09:54 -0700918 // The number of shared objects the linker told us about before loading. Used to
919 // (optimistically) optimize the PreSetup stage (see comment there).
920 size_t shared_objects_before_;
921
Andreas Gampe049cff02015-12-01 23:27:12 -0800922 DISALLOW_COPY_AND_ASSIGN(DlOpenOatFile);
923};
924
Richard Uhlera206c742016-05-24 15:04:22 -0700925std::unordered_set<void*> DlOpenOatFile::host_dlopen_handles_;
926
Andreas Gampe4075f832016-05-18 13:09:54 -0700927void DlOpenOatFile::PreLoad() {
928#ifdef __APPLE__
Andreas Gampe39004a62016-05-18 21:27:00 -0700929 UNUSED(shared_objects_before_);
Andreas Gampe4075f832016-05-18 13:09:54 -0700930 LOG(FATAL) << "Should not reach here.";
931 UNREACHABLE();
932#else
933 // Count the entries in dl_iterate_phdr we get at this point in time.
934 struct dl_iterate_context {
935 static int callback(struct dl_phdr_info *info ATTRIBUTE_UNUSED,
936 size_t size ATTRIBUTE_UNUSED,
937 void *data) {
938 reinterpret_cast<dl_iterate_context*>(data)->count++;
939 return 0; // Continue iteration.
940 }
941 size_t count = 0;
942 } context;
943
944 dl_iterate_phdr(dl_iterate_context::callback, &context);
945 shared_objects_before_ = context.count;
946#endif
947}
948
Andreas Gampe049cff02015-12-01 23:27:12 -0800949bool DlOpenOatFile::Load(const std::string& elf_filename,
950 uint8_t* oat_file_begin,
951 bool writable,
952 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800953 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800954 std::string* error_msg) {
955 // Use dlopen only when flagged to do so, and when it's OK to load things executable.
956 // TODO: Also try when not executable? The issue here could be re-mapping as writable (as
957 // !executable is a sign that we may want to patch), which may not be allowed for
958 // various reasons.
959 if (!kUseDlopen) {
960 *error_msg = "DlOpen is disabled.";
961 return false;
962 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800963 if (low_4gb) {
964 *error_msg = "DlOpen does not support low 4gb loading.";
965 return false;
966 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800967 if (writable) {
968 *error_msg = "DlOpen does not support writable loading.";
969 return false;
970 }
971 if (!executable) {
972 *error_msg = "DlOpen does not support non-executable loading.";
973 return false;
974 }
975
976 // dlopen always returns the same library if it is already opened on the host. For this reason
977 // we only use dlopen if we are the target or we do not already have the dex file opened. Having
978 // the same library loaded multiple times at different addresses is required for class unloading
979 // and for having dex caches arrays in the .bss section.
980 if (!kIsTargetBuild) {
981 if (!kUseDlopenOnHost) {
982 *error_msg = "DlOpen disabled for host.";
983 return false;
984 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800985 }
986
987 bool success = Dlopen(elf_filename, oat_file_begin, error_msg);
988 DCHECK(dlopen_handle_ != nullptr || !success);
989
990 return success;
991}
992
993bool DlOpenOatFile::Dlopen(const std::string& elf_filename,
994 uint8_t* oat_file_begin,
995 std::string* error_msg) {
996#ifdef __APPLE__
997 // The dl_iterate_phdr syscall is missing. There is similar API on OSX,
998 // but let's fallback to the custom loading code for the time being.
999 UNUSED(elf_filename, oat_file_begin);
1000 *error_msg = "Dlopen unsupported on Mac.";
1001 return false;
1002#else
1003 {
1004 UniqueCPtr<char> absolute_path(realpath(elf_filename.c_str(), nullptr));
1005 if (absolute_path == nullptr) {
1006 *error_msg = StringPrintf("Failed to find absolute path for '%s'", elf_filename.c_str());
1007 return false;
1008 }
Bilyan Borisovbb661c02016-04-04 16:27:32 +01001009#ifdef ART_TARGET_ANDROID
Anton Kirilov3a2e78e2017-01-06 13:33:42 +00001010 android_dlextinfo extinfo = {};
Andreas Gampe049cff02015-12-01 23:27:12 -08001011 extinfo.flags = ANDROID_DLEXT_FORCE_LOAD | // Force-load, don't reuse handle
1012 // (open oat files multiple
1013 // times).
1014 ANDROID_DLEXT_FORCE_FIXED_VADDR; // Take a non-zero vaddr as absolute
1015 // (non-pic boot image).
Andreas Gampe226b91e2015-12-02 10:29:33 -08001016 if (oat_file_begin != nullptr) { //
1017 extinfo.flags |= ANDROID_DLEXT_LOAD_AT_FIXED_ADDRESS; // Use the requested addr if
1018 extinfo.reserved_addr = oat_file_begin; // vaddr = 0.
1019 } // (pic boot image).
Andreas Gampe049cff02015-12-01 23:27:12 -08001020 dlopen_handle_ = android_dlopen_ext(absolute_path.get(), RTLD_NOW, &extinfo);
1021#else
Andreas Gampe049cff02015-12-01 23:27:12 -08001022 UNUSED(oat_file_begin);
Julien Duraj1af0c4f2016-11-16 14:05:48 +00001023 static_assert(!kIsTargetBuild || kIsTargetLinux, "host_dlopen_handles_ will leak handles");
Mathieu Chartierc7d3f4b2016-06-01 10:48:19 -07001024 MutexLock mu(Thread::Current(), *Locks::host_dlopen_handles_lock_);
Richard Uhlera206c742016-05-24 15:04:22 -07001025 dlopen_handle_ = dlopen(absolute_path.get(), RTLD_NOW);
1026 if (dlopen_handle_ != nullptr) {
Richard Uhlera206c742016-05-24 15:04:22 -07001027 if (!host_dlopen_handles_.insert(dlopen_handle_).second) {
1028 dlclose(dlopen_handle_);
1029 dlopen_handle_ = nullptr;
1030 *error_msg = StringPrintf("host dlopen re-opened '%s'", elf_filename.c_str());
1031 return false;
1032 }
1033 }
Bilyan Borisovbb661c02016-04-04 16:27:32 +01001034#endif // ART_TARGET_ANDROID
Andreas Gampe049cff02015-12-01 23:27:12 -08001035 }
1036 if (dlopen_handle_ == nullptr) {
1037 *error_msg = StringPrintf("Failed to dlopen '%s': %s", elf_filename.c_str(), dlerror());
1038 return false;
1039 }
1040 return true;
1041#endif
1042}
1043
1044void DlOpenOatFile::PreSetup(const std::string& elf_filename) {
Andreas Gampe74f07b52015-12-02 11:53:26 -08001045#ifdef __APPLE__
1046 UNUSED(elf_filename);
1047 LOG(FATAL) << "Should not reach here.";
1048 UNREACHABLE();
1049#else
Andreas Gampe049cff02015-12-01 23:27:12 -08001050 struct dl_iterate_context {
1051 static int callback(struct dl_phdr_info *info, size_t /* size */, void *data) {
1052 auto* context = reinterpret_cast<dl_iterate_context*>(data);
Andreas Gampe4075f832016-05-18 13:09:54 -07001053 context->shared_objects_seen++;
1054 if (context->shared_objects_seen < context->shared_objects_before) {
1055 // We haven't been called yet for anything we haven't seen before. Just continue.
1056 // Note: this is aggressively optimistic. If another thread was unloading a library,
1057 // we may miss out here. However, this does not happen often in practice.
1058 return 0;
1059 }
1060
Andreas Gampe049cff02015-12-01 23:27:12 -08001061 // See whether this callback corresponds to the file which we have just loaded.
1062 bool contains_begin = false;
1063 for (int i = 0; i < info->dlpi_phnum; i++) {
1064 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
1065 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
1066 info->dlpi_phdr[i].p_vaddr);
1067 size_t memsz = info->dlpi_phdr[i].p_memsz;
1068 if (vaddr <= context->begin_ && context->begin_ < vaddr + memsz) {
1069 contains_begin = true;
1070 break;
1071 }
1072 }
1073 }
1074 // Add dummy mmaps for this file.
1075 if (contains_begin) {
1076 for (int i = 0; i < info->dlpi_phnum; i++) {
1077 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
1078 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
1079 info->dlpi_phdr[i].p_vaddr);
1080 size_t memsz = info->dlpi_phdr[i].p_memsz;
1081 MemMap* mmap = MemMap::MapDummy(info->dlpi_name, vaddr, memsz);
1082 context->dlopen_mmaps_->push_back(std::unique_ptr<MemMap>(mmap));
1083 }
1084 }
1085 return 1; // Stop iteration and return 1 from dl_iterate_phdr.
1086 }
1087 return 0; // Continue iteration and return 0 from dl_iterate_phdr when finished.
1088 }
1089 const uint8_t* const begin_;
1090 std::vector<std::unique_ptr<MemMap>>* const dlopen_mmaps_;
Andreas Gampe4075f832016-05-18 13:09:54 -07001091 const size_t shared_objects_before;
1092 size_t shared_objects_seen;
1093 };
1094 dl_iterate_context context = { Begin(), &dlopen_mmaps_, shared_objects_before_, 0};
Andreas Gampe049cff02015-12-01 23:27:12 -08001095
1096 if (dl_iterate_phdr(dl_iterate_context::callback, &context) == 0) {
Andreas Gampe4075f832016-05-18 13:09:54 -07001097 // Hm. Maybe our optimization went wrong. Try another time with shared_objects_before == 0
1098 // before giving up. This should be unusual.
1099 VLOG(oat) << "Need a second run in PreSetup, didn't find with shared_objects_before="
1100 << shared_objects_before_;
1101 dl_iterate_context context0 = { Begin(), &dlopen_mmaps_, 0, 0};
1102 if (dl_iterate_phdr(dl_iterate_context::callback, &context0) == 0) {
1103 // OK, give up and print an error.
Andreas Gampe170331f2017-12-07 18:41:03 -08001104 PrintFileToLog("/proc/self/maps", android::base::LogSeverity::WARNING);
Andreas Gampe4075f832016-05-18 13:09:54 -07001105 LOG(ERROR) << "File " << elf_filename << " loaded with dlopen but cannot find its mmaps.";
1106 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001107 }
Andreas Gampe74f07b52015-12-02 11:53:26 -08001108#endif
Andreas Gampe049cff02015-12-01 23:27:12 -08001109}
1110
1111////////////////////////////////////////////////
1112// OatFile via our own ElfFile implementation //
1113////////////////////////////////////////////////
1114
1115class ElfOatFile FINAL : public OatFileBase {
1116 public:
1117 ElfOatFile(const std::string& filename, bool executable) : OatFileBase(filename, executable) {}
1118
1119 static ElfOatFile* OpenElfFile(File* file,
1120 const std::string& location,
1121 uint8_t* requested_base,
1122 uint8_t* oat_file_begin, // Override base if not null
1123 bool writable,
1124 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001125 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001126 const char* abs_dex_location,
1127 std::string* error_msg);
1128
1129 bool InitializeFromElfFile(ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +01001130 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001131 const char* abs_dex_location,
1132 std::string* error_msg);
1133
1134 protected:
1135 const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
1136 std::string* error_msg) const OVERRIDE {
1137 const uint8_t* ptr = elf_file_->FindDynamicSymbolAddress(symbol_name);
1138 if (ptr == nullptr) {
1139 *error_msg = "(Internal implementation could not find symbol)";
1140 }
1141 return ptr;
1142 }
1143
Andreas Gampe4075f832016-05-18 13:09:54 -07001144 void PreLoad() OVERRIDE {
1145 }
1146
Andreas Gampe049cff02015-12-01 23:27:12 -08001147 bool Load(const std::string& elf_filename,
1148 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1149 bool writable,
1150 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001151 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001152 std::string* error_msg) OVERRIDE;
1153
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001154 bool Load(int oat_fd,
1155 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1156 bool writable,
1157 bool executable,
1158 bool low_4gb,
1159 std::string* error_msg) OVERRIDE;
1160
Andreas Gampe049cff02015-12-01 23:27:12 -08001161 void PreSetup(const std::string& elf_filename ATTRIBUTE_UNUSED) OVERRIDE {
1162 }
1163
1164 private:
1165 bool ElfFileOpen(File* file,
1166 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1167 bool writable,
1168 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001169 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001170 std::string* error_msg);
1171
1172 private:
1173 // Backing memory map for oat file during cross compilation.
1174 std::unique_ptr<ElfFile> elf_file_;
1175
1176 DISALLOW_COPY_AND_ASSIGN(ElfOatFile);
1177};
1178
1179ElfOatFile* ElfOatFile::OpenElfFile(File* file,
1180 const std::string& location,
1181 uint8_t* requested_base,
1182 uint8_t* oat_file_begin, // Override base if not null
1183 bool writable,
1184 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001185 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001186 const char* abs_dex_location,
1187 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001188 ScopedTrace trace("Open elf file " + location);
Andreas Gampe049cff02015-12-01 23:27:12 -08001189 std::unique_ptr<ElfOatFile> oat_file(new ElfOatFile(location, executable));
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001190 bool success = oat_file->ElfFileOpen(file,
1191 oat_file_begin,
1192 writable,
1193 low_4gb,
1194 executable,
1195 error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -08001196 if (!success) {
1197 CHECK(!error_msg->empty());
1198 return nullptr;
1199 }
1200
1201 // Complete the setup.
1202 if (!oat_file->ComputeFields(requested_base, file->GetPath(), error_msg)) {
1203 return nullptr;
1204 }
1205
1206 if (!oat_file->Setup(abs_dex_location, error_msg)) {
1207 return nullptr;
1208 }
1209
1210 return oat_file.release();
1211}
1212
1213bool ElfOatFile::InitializeFromElfFile(ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +01001214 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001215 const char* abs_dex_location,
1216 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001217 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -08001218 if (IsExecutable()) {
1219 *error_msg = "Cannot initialize from elf file in executable mode.";
1220 return false;
1221 }
1222 elf_file_.reset(elf_file);
David Brazdilc93b3be2016-09-12 18:49:58 +01001223 SetVdex(vdex_file);
Andreas Gampe049cff02015-12-01 23:27:12 -08001224 uint64_t offset, size;
1225 bool has_section = elf_file->GetSectionOffsetAndSize(".rodata", &offset, &size);
1226 CHECK(has_section);
1227 SetBegin(elf_file->Begin() + offset);
1228 SetEnd(elf_file->Begin() + size + offset);
1229 // Ignore the optional .bss section when opening non-executable.
1230 return Setup(abs_dex_location, error_msg);
1231}
1232
1233bool ElfOatFile::Load(const std::string& elf_filename,
1234 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1235 bool writable,
1236 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001237 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001238 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001239 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -08001240 std::unique_ptr<File> file(OS::OpenFileForReading(elf_filename.c_str()));
1241 if (file == nullptr) {
1242 *error_msg = StringPrintf("Failed to open oat filename for reading: %s", strerror(errno));
1243 return false;
1244 }
1245 return ElfOatFile::ElfFileOpen(file.get(),
1246 oat_file_begin,
1247 writable,
1248 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001249 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001250 error_msg);
1251}
1252
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001253bool ElfOatFile::Load(int oat_fd,
1254 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1255 bool writable,
1256 bool executable,
1257 bool low_4gb,
1258 std::string* error_msg) {
1259 ScopedTrace trace(__PRETTY_FUNCTION__);
1260 if (oat_fd != -1) {
1261 std::unique_ptr<File> file = std::make_unique<File>(oat_fd, false);
1262 file->DisableAutoClose();
1263 if (file == nullptr) {
1264 *error_msg = StringPrintf("Failed to open oat filename for reading: %s",
1265 strerror(errno));
1266 return false;
1267 }
1268 return ElfOatFile::ElfFileOpen(file.get(),
1269 oat_file_begin,
1270 writable,
1271 executable,
1272 low_4gb,
1273 error_msg);
1274 }
1275 return false;
1276}
1277
Andreas Gampe049cff02015-12-01 23:27:12 -08001278bool ElfOatFile::ElfFileOpen(File* file,
1279 uint8_t* oat_file_begin,
1280 bool writable,
1281 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001282 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001283 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001284 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -08001285 // TODO: rename requested_base to oat_data_begin
1286 elf_file_.reset(ElfFile::Open(file,
1287 writable,
1288 /*program_header_only*/true,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001289 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001290 error_msg,
1291 oat_file_begin));
1292 if (elf_file_ == nullptr) {
1293 DCHECK(!error_msg->empty());
1294 return false;
1295 }
Brian Carlstromf5b0f2c2016-10-14 01:04:26 -07001296 bool loaded = elf_file_->Load(file, executable, low_4gb, error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -08001297 DCHECK(loaded || !error_msg->empty());
1298 return loaded;
1299}
1300
1301//////////////////////////
1302// General OatFile code //
1303//////////////////////////
1304
1305std::string OatFile::ResolveRelativeEncodedDexLocation(
1306 const char* abs_dex_location, const std::string& rel_dex_location) {
1307 if (abs_dex_location != nullptr && rel_dex_location[0] != '/') {
1308 // Strip :classes<N>.dex used for secondary multidex files.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001309 std::string base = DexFileLoader::GetBaseLocation(rel_dex_location);
1310 std::string multidex_suffix = DexFileLoader::GetMultiDexSuffix(rel_dex_location);
Andreas Gampe049cff02015-12-01 23:27:12 -08001311
1312 // Check if the base is a suffix of the provided abs_dex_location.
1313 std::string target_suffix = "/" + base;
1314 std::string abs_location(abs_dex_location);
1315 if (abs_location.size() > target_suffix.size()) {
1316 size_t pos = abs_location.size() - target_suffix.size();
1317 if (abs_location.compare(pos, std::string::npos, target_suffix) == 0) {
1318 return abs_location + multidex_suffix;
1319 }
1320 }
1321 }
1322 return rel_dex_location;
1323}
1324
1325static void CheckLocation(const std::string& location) {
1326 CHECK(!location.empty());
1327}
1328
1329OatFile* OatFile::OpenWithElfFile(ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +01001330 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001331 const std::string& location,
1332 const char* abs_dex_location,
1333 std::string* error_msg) {
1334 std::unique_ptr<ElfOatFile> oat_file(new ElfOatFile(location, false /* executable */));
David Brazdilc93b3be2016-09-12 18:49:58 +01001335 return oat_file->InitializeFromElfFile(elf_file, vdex_file, abs_dex_location, error_msg)
Andreas Gampe049cff02015-12-01 23:27:12 -08001336 ? oat_file.release()
1337 : nullptr;
1338}
1339
David Brazdil7b49e6c2016-09-01 11:06:18 +01001340OatFile* OatFile::Open(const std::string& oat_filename,
1341 const std::string& oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001342 uint8_t* requested_base,
1343 uint8_t* oat_file_begin,
1344 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001345 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001346 const char* abs_dex_location,
1347 std::string* error_msg) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001348 ScopedTrace trace("Open oat file " + oat_location);
1349 CHECK(!oat_filename.empty()) << oat_location;
1350 CheckLocation(oat_location);
Andreas Gampe54315c72016-05-18 21:10:42 -07001351
Calin Juravle367b9d82017-05-15 18:18:39 -07001352 std::string vdex_filename = GetVdexFilename(oat_filename);
David Brazdil7b49e6c2016-09-01 11:06:18 +01001353
1354 // Check that the files even exist, fast-fail.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001355 if (!OS::FileExists(vdex_filename.c_str())) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001356 *error_msg = StringPrintf("File %s does not exist.", vdex_filename.c_str());
1357 return nullptr;
1358 } else if (!OS::FileExists(oat_filename.c_str())) {
1359 *error_msg = StringPrintf("File %s does not exist.", oat_filename.c_str());
Andreas Gampe54315c72016-05-18 21:10:42 -07001360 return nullptr;
1361 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001362
1363 // Try dlopen first, as it is required for native debuggability. This will fail fast if dlopen is
1364 // disabled.
David Brazdil7b49e6c2016-09-01 11:06:18 +01001365 OatFile* with_dlopen = OatFileBase::OpenOatFile<DlOpenOatFile>(vdex_filename,
1366 oat_filename,
1367 oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001368 requested_base,
1369 oat_file_begin,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001370 false /* writable */,
Andreas Gampe049cff02015-12-01 23:27:12 -08001371 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001372 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001373 abs_dex_location,
1374 error_msg);
1375 if (with_dlopen != nullptr) {
1376 return with_dlopen;
1377 }
1378 if (kPrintDlOpenErrorMessage) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001379 LOG(ERROR) << "Failed to dlopen: " << oat_filename << " with error " << *error_msg;
Andreas Gampe049cff02015-12-01 23:27:12 -08001380 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001381 // If we aren't trying to execute, we just use our own ElfFile loader for a couple reasons:
1382 //
1383 // On target, dlopen may fail when compiling due to selinux restrictions on installd.
1384 //
1385 // We use our own ELF loader for Quick to deal with legacy apps that
1386 // open a generated dex file by name, remove the file, then open
1387 // another generated dex file with the same name. http://b/10614658
1388 //
1389 // On host, dlopen is expected to fail when cross compiling, so fall back to OpenElfFile.
1390 //
1391 //
1392 // Another independent reason is the absolute placement of boot.oat. dlopen on the host usually
1393 // 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 +01001394 OatFile* with_internal = OatFileBase::OpenOatFile<ElfOatFile>(vdex_filename,
1395 oat_filename,
1396 oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001397 requested_base,
1398 oat_file_begin,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001399 false /* writable */,
Andreas Gampe049cff02015-12-01 23:27:12 -08001400 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001401 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001402 abs_dex_location,
1403 error_msg);
1404 return with_internal;
1405}
1406
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001407OatFile* OatFile::Open(int vdex_fd,
1408 int oat_fd,
1409 const std::string& oat_location,
1410 uint8_t* requested_base,
1411 uint8_t* oat_file_begin,
1412 bool executable,
1413 bool low_4gb,
1414 const char* abs_dex_location,
1415 std::string* error_msg) {
1416 CHECK(!oat_location.empty()) << oat_location;
1417
1418 std::string vdex_location = GetVdexFilename(oat_location);
1419
1420 OatFile* with_internal = OatFileBase::OpenOatFile<ElfOatFile>(vdex_fd,
1421 oat_fd,
1422 vdex_location,
1423 oat_location,
1424 requested_base,
1425 oat_file_begin,
1426 false /* writable */,
1427 executable,
1428 low_4gb,
1429 abs_dex_location,
1430 error_msg);
1431 return with_internal;
1432}
1433
Andreas Gampe049cff02015-12-01 23:27:12 -08001434OatFile* OatFile::OpenWritable(File* file,
1435 const std::string& location,
1436 const char* abs_dex_location,
1437 std::string* error_msg) {
1438 CheckLocation(location);
1439 return ElfOatFile::OpenElfFile(file,
1440 location,
1441 nullptr,
1442 nullptr,
1443 true,
1444 false,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001445 /*low_4gb*/false,
Andreas Gampe049cff02015-12-01 23:27:12 -08001446 abs_dex_location,
1447 error_msg);
1448}
1449
1450OatFile* OatFile::OpenReadable(File* file,
1451 const std::string& location,
1452 const char* abs_dex_location,
1453 std::string* error_msg) {
1454 CheckLocation(location);
1455 return ElfOatFile::OpenElfFile(file,
1456 location,
1457 nullptr,
1458 nullptr,
1459 false,
1460 false,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001461 /*low_4gb*/false,
Andreas Gampe049cff02015-12-01 23:27:12 -08001462 abs_dex_location,
1463 error_msg);
1464}
1465
1466OatFile::OatFile(const std::string& location, bool is_executable)
1467 : location_(location),
David Brazdil7b49e6c2016-09-01 11:06:18 +01001468 vdex_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001469 begin_(nullptr),
1470 end_(nullptr),
1471 bss_begin_(nullptr),
1472 bss_end_(nullptr),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001473 bss_methods_(nullptr),
Vladimir Markoaad75c62016-10-03 08:46:48 +00001474 bss_roots_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001475 is_executable_(is_executable),
David Srbeckyec2cdf42017-12-08 16:21:25 +00001476 vdex_begin_(nullptr),
1477 vdex_end_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001478 secondary_lookup_lock_("OatFile secondary lookup lock", kOatFileSecondaryLookupLock) {
1479 CHECK(!location_.empty());
1480}
1481
1482OatFile::~OatFile() {
1483 STLDeleteElements(&oat_dex_files_storage_);
1484}
1485
Brian Carlstrome24fa612011-09-29 00:53:55 -07001486const OatHeader& OatFile::GetOatHeader() const {
Ian Rogers30fab402012-01-23 15:43:46 -08001487 return *reinterpret_cast<const OatHeader*>(Begin());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001488}
1489
Ian Rogers13735952014-10-08 12:43:28 -07001490const uint8_t* OatFile::Begin() const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001491 CHECK(begin_ != nullptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001492 return begin_;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001493}
1494
Ian Rogers13735952014-10-08 12:43:28 -07001495const uint8_t* OatFile::End() const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001496 CHECK(end_ != nullptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001497 return end_;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001498}
1499
Vladimir Marko5c42c292015-02-25 12:02:49 +00001500const uint8_t* OatFile::BssBegin() const {
1501 return bss_begin_;
1502}
1503
1504const uint8_t* OatFile::BssEnd() const {
1505 return bss_end_;
1506}
1507
David Srbeckyec2cdf42017-12-08 16:21:25 +00001508const uint8_t* OatFile::VdexBegin() const {
1509 return vdex_begin_;
1510}
1511
1512const uint8_t* OatFile::VdexEnd() const {
1513 return vdex_end_;
1514}
1515
David Brazdil7b49e6c2016-09-01 11:06:18 +01001516const uint8_t* OatFile::DexBegin() const {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001517 return vdex_->Begin();
David Brazdil7b49e6c2016-09-01 11:06:18 +01001518}
1519
1520const uint8_t* OatFile::DexEnd() const {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001521 return vdex_->End();
David Brazdil7b49e6c2016-09-01 11:06:18 +01001522}
1523
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001524ArrayRef<ArtMethod*> OatFile::GetBssMethods() const {
1525 if (bss_methods_ != nullptr) {
1526 ArtMethod** methods = reinterpret_cast<ArtMethod**>(bss_methods_);
1527 ArtMethod** methods_end =
1528 reinterpret_cast<ArtMethod**>(bss_roots_ != nullptr ? bss_roots_ : bss_end_);
1529 return ArrayRef<ArtMethod*>(methods, methods_end - methods);
1530 } else {
1531 return ArrayRef<ArtMethod*>();
1532 }
1533}
1534
Vladimir Markoaad75c62016-10-03 08:46:48 +00001535ArrayRef<GcRoot<mirror::Object>> OatFile::GetBssGcRoots() const {
1536 if (bss_roots_ != nullptr) {
1537 auto* roots = reinterpret_cast<GcRoot<mirror::Object>*>(bss_roots_);
1538 auto* roots_end = reinterpret_cast<GcRoot<mirror::Object>*>(bss_end_);
1539 return ArrayRef<GcRoot<mirror::Object>>(roots, roots_end - roots);
1540 } else {
1541 return ArrayRef<GcRoot<mirror::Object>>();
1542 }
1543}
1544
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00001545uint32_t OatFile::GetDebugInfoOffset(const DexFile& dex_file,
Nicolas Geoffray58cc1cb2017-11-20 13:27:29 +00001546 const DexFile::CodeItem* code_item) {
1547 if (code_item == nullptr) {
1548 return 0;
1549 }
Nicolas Geoffrayb4c6acb2017-11-10 12:48:14 +00001550 const uint32_t debug_info_off = code_item->debug_info_off_;
1551 // Note that although the specification says that 0 should be used if there
1552 // is no debug information, some applications incorrectly use 0xFFFFFFFF.
1553 if (debug_info_off < dex_file.Size() || debug_info_off == 0xFFFFFFFF) {
1554 return debug_info_off;
1555 }
1556 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1557 if (oat_dex_file == nullptr || (oat_dex_file->GetOatFile() == nullptr)) {
1558 return debug_info_off;
1559 }
1560 return oat_dex_file->GetOatFile()->GetVdexFile()->GetDebugInfoOffset(
1561 dex_file, debug_info_off);
Nicolas Geoffray58cc1cb2017-11-20 13:27:29 +00001562}
1563
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001564const OatFile::OatDexFile* OatFile::GetOatDexFile(const char* dex_location,
1565 const uint32_t* dex_location_checksum,
Richard Uhler9a37efc2016-08-05 16:32:55 -07001566 std::string* error_msg) const {
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001567 // NOTE: We assume here that the canonical location for a given dex_location never
1568 // changes. If it does (i.e. some symlink used by the filename changes) we may return
1569 // an incorrect OatDexFile. As long as we have a checksum to check, we shall return
1570 // an identical file or fail; otherwise we may see some unpredictable failures.
Calin Juravle4e1d5792014-07-15 23:56:47 +01001571
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001572 // TODO: Additional analysis of usage patterns to see if this can be simplified
1573 // without any performance loss, for example by not doing the first lock-free lookup.
1574
1575 const OatFile::OatDexFile* oat_dex_file = nullptr;
1576 StringPiece key(dex_location);
1577 // Try to find the key cheaply in the oat_dex_files_ map which holds dex locations
1578 // directly mentioned in the oat file and doesn't require locking.
1579 auto primary_it = oat_dex_files_.find(key);
1580 if (primary_it != oat_dex_files_.end()) {
1581 oat_dex_file = primary_it->second;
1582 DCHECK(oat_dex_file != nullptr);
1583 } else {
1584 // This dex_location is not one of the dex locations directly mentioned in the
1585 // oat file. The correct lookup is via the canonical location but first see in
1586 // the secondary_oat_dex_files_ whether we've looked up this location before.
1587 MutexLock mu(Thread::Current(), secondary_lookup_lock_);
1588 auto secondary_lb = secondary_oat_dex_files_.lower_bound(key);
1589 if (secondary_lb != secondary_oat_dex_files_.end() && key == secondary_lb->first) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001590 oat_dex_file = secondary_lb->second; // May be null.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001591 } else {
1592 // We haven't seen this dex_location before, we must check the canonical location.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001593 std::string dex_canonical_location = DexFileLoader::GetDexCanonicalLocation(dex_location);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001594 if (dex_canonical_location != dex_location) {
1595 StringPiece canonical_key(dex_canonical_location);
1596 auto canonical_it = oat_dex_files_.find(canonical_key);
1597 if (canonical_it != oat_dex_files_.end()) {
1598 oat_dex_file = canonical_it->second;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001599 } // else keep null.
1600 } // else keep null.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001601
1602 // Copy the key to the string_cache_ and store the result in secondary map.
1603 string_cache_.emplace_back(key.data(), key.length());
1604 StringPiece key_copy(string_cache_.back());
1605 secondary_oat_dex_files_.PutBefore(secondary_lb, key_copy, oat_dex_file);
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001606 }
1607 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001608
1609 if (oat_dex_file == nullptr) {
1610 if (error_msg != nullptr) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001611 std::string dex_canonical_location = DexFileLoader::GetDexCanonicalLocation(dex_location);
Richard Uhler9a37efc2016-08-05 16:32:55 -07001612 *error_msg = "Failed to find OatDexFile for DexFile " + std::string(dex_location)
1613 + " (canonical path " + dex_canonical_location + ") in OatFile " + GetLocation();
1614 }
1615 return nullptr;
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001616 }
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001617
Richard Uhler9a37efc2016-08-05 16:32:55 -07001618 if (dex_location_checksum != nullptr &&
1619 oat_dex_file->GetDexFileLocationChecksum() != *dex_location_checksum) {
1620 if (error_msg != nullptr) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001621 std::string dex_canonical_location = DexFileLoader::GetDexCanonicalLocation(dex_location);
Richard Uhler9a37efc2016-08-05 16:32:55 -07001622 std::string checksum = StringPrintf("0x%08x", oat_dex_file->GetDexFileLocationChecksum());
1623 std::string required_checksum = StringPrintf("0x%08x", *dex_location_checksum);
1624 *error_msg = "OatDexFile for DexFile " + std::string(dex_location)
1625 + " (canonical path " + dex_canonical_location + ") in OatFile " + GetLocation()
1626 + " has checksum " + checksum + " but " + required_checksum + " was required";
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001627 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001628 return nullptr;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001629 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001630 return oat_dex_file;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001631}
1632
Brian Carlstrome24fa612011-09-29 00:53:55 -07001633OatFile::OatDexFile::OatDexFile(const OatFile* oat_file,
Elliott Hughesaa6a5882012-01-13 19:39:16 -08001634 const std::string& dex_file_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001635 const std::string& canonical_dex_file_location,
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001636 uint32_t dex_file_location_checksum,
Ian Rogers13735952014-10-08 12:43:28 -07001637 const uint8_t* dex_file_pointer,
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001638 const uint8_t* lookup_table_data,
Vladimir Markof3c52b42017-11-17 17:32:12 +00001639 const IndexBssMapping* method_bss_mapping_data,
1640 const IndexBssMapping* type_bss_mapping_data,
1641 const IndexBssMapping* string_bss_mapping_data,
Vladimir Marko09d09432015-09-08 13:47:48 +01001642 const uint32_t* oat_class_offsets_pointer,
Mathieu Chartier120aa282017-08-05 16:03:03 -07001643 const DexLayoutSections* dex_layout_sections)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001644 : oat_file_(oat_file),
1645 dex_file_location_(dex_file_location),
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001646 canonical_dex_file_location_(canonical_dex_file_location),
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001647 dex_file_location_checksum_(dex_file_location_checksum),
Brian Carlstrom89521892011-12-07 22:05:07 -08001648 dex_file_pointer_(dex_file_pointer),
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001649 lookup_table_data_(lookup_table_data),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001650 method_bss_mapping_(method_bss_mapping_data),
Vladimir Markof3c52b42017-11-17 17:32:12 +00001651 type_bss_mapping_(type_bss_mapping_data),
1652 string_bss_mapping_(string_bss_mapping_data),
Vladimir Marko09d09432015-09-08 13:47:48 +01001653 oat_class_offsets_pointer_(oat_class_offsets_pointer),
Mathieu Chartier120aa282017-08-05 16:03:03 -07001654 dex_layout_sections_(dex_layout_sections) {
David Sehr9aa352e2016-09-15 18:13:52 -07001655 // Initialize TypeLookupTable.
1656 if (lookup_table_data_ != nullptr) {
1657 // Peek the number of classes from the DexFile.
1658 const DexFile::Header* dex_header = reinterpret_cast<const DexFile::Header*>(dex_file_pointer_);
1659 const uint32_t num_class_defs = dex_header->class_defs_size_;
1660 if (lookup_table_data_ + TypeLookupTable::RawDataLength(num_class_defs) > GetOatFile()->End()) {
1661 LOG(WARNING) << "found truncated lookup table in " << dex_file_location_;
1662 } else {
Mathieu Chartier1b868492016-11-16 16:22:37 -08001663 lookup_table_ = TypeLookupTable::Open(dex_file_pointer_, lookup_table_data_, num_class_defs);
David Sehr9aa352e2016-09-15 18:13:52 -07001664 }
1665 }
1666}
Brian Carlstrome24fa612011-09-29 00:53:55 -07001667
Mathieu Chartier1b868492016-11-16 16:22:37 -08001668OatFile::OatDexFile::OatDexFile(std::unique_ptr<TypeLookupTable>&& lookup_table)
1669 : lookup_table_(std::move(lookup_table)) {}
1670
Brian Carlstrome24fa612011-09-29 00:53:55 -07001671OatFile::OatDexFile::~OatDexFile() {}
1672
Ian Rogers05f28c62012-10-23 18:12:13 -07001673size_t OatFile::OatDexFile::FileSize() const {
1674 return reinterpret_cast<const DexFile::Header*>(dex_file_pointer_)->file_size_;
1675}
1676
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001677std::unique_ptr<const DexFile> OatFile::OatDexFile::OpenDexFile(std::string* error_msg) const {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001678 ScopedTrace trace(__PRETTY_FUNCTION__);
Aart Bik37d6a3b2016-06-21 18:30:10 -07001679 static constexpr bool kVerify = false;
1680 static constexpr bool kVerifyChecksum = false;
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001681 return DexFileLoader::Open(dex_file_pointer_,
1682 FileSize(),
1683 dex_file_location_,
1684 dex_file_location_checksum_,
1685 this,
1686 kVerify,
1687 kVerifyChecksum,
1688 error_msg);
Brian Carlstrom89521892011-12-07 22:05:07 -08001689}
1690
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001691uint32_t OatFile::OatDexFile::GetOatClassOffset(uint16_t class_def_index) const {
1692 return oat_class_offsets_pointer_[class_def_index];
1693}
1694
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001695OatFile::OatClass OatFile::OatDexFile::GetOatClass(uint16_t class_def_index) const {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001696 uint32_t oat_class_offset = GetOatClassOffset(class_def_index);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001697
Ian Rogers13735952014-10-08 12:43:28 -07001698 const uint8_t* oat_class_pointer = oat_file_->Begin() + oat_class_offset;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001699 CHECK_LT(oat_class_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001700
Ian Rogers13735952014-10-08 12:43:28 -07001701 const uint8_t* status_pointer = oat_class_pointer;
Brian Carlstromba150c32013-08-27 17:31:03 -07001702 CHECK_LT(status_pointer, oat_file_->End()) << oat_file_->GetLocation();
1703 mirror::Class::Status status =
1704 static_cast<mirror::Class::Status>(*reinterpret_cast<const int16_t*>(status_pointer));
1705 CHECK_LT(status, mirror::Class::kStatusMax);
1706
Ian Rogers13735952014-10-08 12:43:28 -07001707 const uint8_t* type_pointer = status_pointer + sizeof(uint16_t);
Brian Carlstromba150c32013-08-27 17:31:03 -07001708 CHECK_LT(type_pointer, oat_file_->End()) << oat_file_->GetLocation();
1709 OatClassType type = static_cast<OatClassType>(*reinterpret_cast<const uint16_t*>(type_pointer));
1710 CHECK_LT(type, kOatClassMax);
1711
Ian Rogers13735952014-10-08 12:43:28 -07001712 const uint8_t* after_type_pointer = type_pointer + sizeof(int16_t);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001713 CHECK_LE(after_type_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07001714
Brian Carlstromcd937a92014-03-04 22:53:23 -08001715 uint32_t bitmap_size = 0;
Ian Rogers13735952014-10-08 12:43:28 -07001716 const uint8_t* bitmap_pointer = nullptr;
1717 const uint8_t* methods_pointer = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07001718 if (type != kOatClassNoneCompiled) {
1719 if (type == kOatClassSomeCompiled) {
1720 bitmap_size = static_cast<uint32_t>(*reinterpret_cast<const uint32_t*>(after_type_pointer));
1721 bitmap_pointer = after_type_pointer + sizeof(bitmap_size);
1722 CHECK_LE(bitmap_pointer, oat_file_->End()) << oat_file_->GetLocation();
1723 methods_pointer = bitmap_pointer + bitmap_size;
1724 } else {
1725 methods_pointer = after_type_pointer;
1726 }
1727 CHECK_LE(methods_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstromcd937a92014-03-04 22:53:23 -08001728 }
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001729
Richard Uhler07b3c232015-03-31 15:57:54 -07001730 return OatFile::OatClass(oat_file_,
1731 status,
1732 type,
1733 bitmap_size,
1734 reinterpret_cast<const uint32_t*>(bitmap_pointer),
1735 reinterpret_cast<const OatMethodOffsets*>(methods_pointer));
Brian Carlstrome24fa612011-09-29 00:53:55 -07001736}
1737
David Sehr9aa352e2016-09-15 18:13:52 -07001738const DexFile::ClassDef* OatFile::OatDexFile::FindClassDef(const DexFile& dex_file,
1739 const char* descriptor,
1740 size_t hash) {
1741 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1742 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
1743 if (LIKELY((oat_dex_file != nullptr) && (oat_dex_file->GetTypeLookupTable() != nullptr))) {
1744 const uint32_t class_def_idx = oat_dex_file->GetTypeLookupTable()->Lookup(descriptor, hash);
Andreas Gampee2abbc62017-09-15 11:59:26 -07001745 return (class_def_idx != dex::kDexNoIndex) ? &dex_file.GetClassDef(class_def_idx) : nullptr;
David Sehr9aa352e2016-09-15 18:13:52 -07001746 }
1747 // Fast path for rare no class defs case.
1748 const uint32_t num_class_defs = dex_file.NumClassDefs();
1749 if (num_class_defs == 0) {
1750 return nullptr;
1751 }
1752 const DexFile::TypeId* type_id = dex_file.FindTypeId(descriptor);
1753 if (type_id != nullptr) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001754 dex::TypeIndex type_idx = dex_file.GetIndexForTypeId(*type_id);
David Sehr9aa352e2016-09-15 18:13:52 -07001755 return dex_file.FindClassDef(type_idx);
1756 }
1757 return nullptr;
1758}
1759
Mathieu Chartier120aa282017-08-05 16:03:03 -07001760// Madvise the dex file based on the state we are moving to.
1761void OatDexFile::MadviseDexFile(const DexFile& dex_file, MadviseState state) {
Mathieu Chartierc42cb0e2017-10-13 11:35:00 -07001762 Runtime* const runtime = Runtime::Current();
1763 const bool low_ram = runtime->GetHeap()->IsLowMemoryMode();
Mathieu Chartier150d25d2017-08-28 09:52:55 -07001764 // TODO: Also do madvise hints for non low ram devices.
Mathieu Chartierc42cb0e2017-10-13 11:35:00 -07001765 if (!low_ram) {
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001766 return;
1767 }
Mathieu Chartierc42cb0e2017-10-13 11:35:00 -07001768 if (state == MadviseState::kMadviseStateAtLoad && runtime->MAdviseRandomAccess()) {
1769 // Default every dex file to MADV_RANDOM when its loaded by default for low ram devices.
1770 // Other devices have enough page cache to get performance benefits from loading more pages
1771 // into the page cache.
1772 MadviseLargestPageAlignedRegion(dex_file.Begin(),
1773 dex_file.Begin() + dex_file.Size(),
1774 MADV_RANDOM);
Mathieu Chartier120aa282017-08-05 16:03:03 -07001775 }
1776 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1777 if (oat_dex_file != nullptr) {
1778 // Should always be there.
1779 const DexLayoutSections* const sections = oat_dex_file->GetDexLayoutSections();
1780 CHECK(sections != nullptr);
1781 sections->Madvise(&dex_file, state);
1782 }
1783}
1784
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001785OatFile::OatClass::OatClass(const OatFile* oat_file,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001786 mirror::Class::Status status,
Brian Carlstromba150c32013-08-27 17:31:03 -07001787 OatClassType type,
1788 uint32_t bitmap_size,
1789 const uint32_t* bitmap_pointer,
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001790 const OatMethodOffsets* methods_pointer)
Brian Carlstromba150c32013-08-27 17:31:03 -07001791 : oat_file_(oat_file), status_(status), type_(type),
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001792 bitmap_(bitmap_pointer), methods_pointer_(methods_pointer) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001793 switch (type_) {
1794 case kOatClassAllCompiled: {
1795 CHECK_EQ(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001796 CHECK(bitmap_pointer == nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001797 CHECK(methods_pointer != nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001798 break;
1799 }
1800 case kOatClassSomeCompiled: {
1801 CHECK_NE(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001802 CHECK(bitmap_pointer != nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001803 CHECK(methods_pointer != nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001804 break;
1805 }
1806 case kOatClassNoneCompiled: {
1807 CHECK_EQ(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001808 CHECK(bitmap_pointer == nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001809 CHECK(methods_pointer_ == nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001810 break;
1811 }
1812 case kOatClassMax: {
1813 LOG(FATAL) << "Invalid OatClassType " << type_;
1814 break;
1815 }
1816 }
1817}
Brian Carlstrome24fa612011-09-29 00:53:55 -07001818
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001819uint32_t OatFile::OatClass::GetOatMethodOffsetsOffset(uint32_t method_index) const {
1820 const OatMethodOffsets* oat_method_offsets = GetOatMethodOffsets(method_index);
1821 if (oat_method_offsets == nullptr) {
1822 return 0u;
1823 }
1824 return reinterpret_cast<const uint8_t*>(oat_method_offsets) - oat_file_->Begin();
1825}
1826
1827const OatMethodOffsets* OatFile::OatClass::GetOatMethodOffsets(uint32_t method_index) const {
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001828 // 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 -07001829 if (methods_pointer_ == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001830 CHECK_EQ(kOatClassNoneCompiled, type_);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001831 return nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07001832 }
1833 size_t methods_pointer_index;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001834 if (bitmap_ == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001835 CHECK_EQ(kOatClassAllCompiled, type_);
1836 methods_pointer_index = method_index;
1837 } else {
1838 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001839 if (!BitVector::IsBitSet(bitmap_, method_index)) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001840 return nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07001841 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001842 size_t num_set_bits = BitVector::NumSetBits(bitmap_, method_index);
1843 methods_pointer_index = num_set_bits;
Brian Carlstromba150c32013-08-27 17:31:03 -07001844 }
1845 const OatMethodOffsets& oat_method_offsets = methods_pointer_[methods_pointer_index];
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001846 return &oat_method_offsets;
1847}
1848
1849const OatFile::OatMethod OatFile::OatClass::GetOatMethod(uint32_t method_index) const {
1850 const OatMethodOffsets* oat_method_offsets = GetOatMethodOffsets(method_index);
1851 if (oat_method_offsets == nullptr) {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001852 return OatMethod(nullptr, 0);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001853 }
1854 if (oat_file_->IsExecutable() ||
1855 Runtime::Current() == nullptr || // This case applies for oatdump.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001856 Runtime::Current()->IsAotCompiler()) {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001857 return OatMethod(oat_file_->Begin(), oat_method_offsets->code_offset_);
Alex Light9dcc4572014-08-14 14:16:26 -07001858 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001859 // We aren't allowed to use the compiled code. We just force it down the interpreted / jit
1860 // version.
1861 return OatMethod(oat_file_->Begin(), 0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001862}
1863
Mathieu Chartiere401d142015-04-22 13:56:20 -07001864void OatFile::OatMethod::LinkMethod(ArtMethod* method) const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001865 CHECK(method != nullptr);
Ian Rogersef7d42f2014-01-06 12:55:46 -08001866 method->SetEntryPointFromQuickCompiledCode(GetQuickCode());
Brian Carlstromae826982011-11-09 01:33:42 -08001867}
1868
Andreas Gampe7ba64962014-10-23 11:37:40 -07001869bool OatFile::IsPic() const {
Igor Murashkin46774762014-10-22 11:37:02 -07001870 return GetOatHeader().IsPic();
Andreas Gampe7ba64962014-10-23 11:37:40 -07001871 // TODO: Check against oat_patches. b/18144996
1872}
1873
Sebastien Hertz0de11332015-05-13 12:14:05 +02001874bool OatFile::IsDebuggable() const {
1875 return GetOatHeader().IsDebuggable();
1876}
1877
Andreas Gampe29d38e72016-03-23 15:31:51 +00001878CompilerFilter::Filter OatFile::GetCompilerFilter() const {
1879 return GetOatHeader().GetCompilerFilter();
Calin Juravleb077e152016-02-18 18:47:37 +00001880}
1881
Calin Juravle44e5efa2017-09-12 00:54:26 -07001882std::string OatFile::GetClassLoaderContext() const {
1883 return GetOatHeader().GetStoreValueByKey(OatHeader::kClassPathKey);
Igor Murashkin2ffb7032017-11-08 13:35:21 -08001884}
Calin Juravle44e5efa2017-09-12 00:54:26 -07001885
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001886OatFile::OatClass OatFile::FindOatClass(const DexFile& dex_file,
1887 uint16_t class_def_idx,
1888 bool* found) {
1889 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
1890 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Mathieu Chartier1b868492016-11-16 16:22:37 -08001891 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001892 *found = false;
1893 return OatFile::OatClass::Invalid();
1894 }
1895 *found = true;
1896 return oat_dex_file->GetOatClass(class_def_idx);
1897}
1898
Mathieu Chartier1b868492016-11-16 16:22:37 -08001899void OatFile::OatDexFile::AssertAotCompiler() {
1900 CHECK(Runtime::Current()->IsAotCompiler());
1901}
1902
Brian Carlstrome24fa612011-09-29 00:53:55 -07001903} // namespace art