blob: d47f1b5611fecbf77c2dd9a58a62ddc314d9ddce [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>
Calin Juravle4e1d5792014-07-15 23:56:47 +010020#include <string.h>
Vladimir Marko06d7aaa2015-10-16 11:23:41 +010021#include <type_traits>
Andreas Gampedaab38c2014-09-12 18:38:24 -070022#include <unistd.h>
Brian Carlstrom700c8d32012-11-05 10:42:02 -080023
Andreas Gampe7848da42015-04-09 11:15:04 -070024#include <cstdlib>
David Srbecky1baabf02015-06-16 17:12:34 +000025#ifndef __APPLE__
26#include <link.h> // for dl_iterate_phdr.
27#endif
Richard Uhlere5fed032015-03-18 08:21:11 -070028#include <sstream>
29
Andreas Gampefa8429b2015-04-07 18:34:42 -070030// dlopen_ext support from bionic.
Bilyan Borisovbb661c02016-04-04 16:27:32 +010031#ifdef ART_TARGET_ANDROID
Andreas Gampefa8429b2015-04-07 18:34:42 -070032#include "android/dlext.h"
33#endif
34
Andreas Gampe46ee31b2016-12-14 10:11:49 -080035#include "android-base/stringprintf.h"
36
Mathieu Chartiere401d142015-04-22 13:56:20 -070037#include "art_method-inl.h"
Brian Carlstromba150c32013-08-27 17:31:03 -070038#include "base/bit_vector.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070039#include "base/enums.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080040#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080041#include "base/systrace.h"
Elliott Hughes76160052012-12-12 16:31:20 -080042#include "base/unix_file/fd_file.h"
Andreas Gampea5b09a62016-11-17 15:21:22 -080043#include "dex_file_types.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080044#include "elf_file.h"
Alex Light84d76052014-08-22 17:49:35 -070045#include "elf_utils.h"
Vladimir Markoaad75c62016-10-03 08:46:48 +000046#include "gc_root.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080047#include "oat.h"
David Srbecky1baabf02015-06-16 17:12:34 +000048#include "mem_map.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080049#include "mirror/class.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070050#include "mirror/object-inl.h"
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +010051#include "oat_file-inl.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070052#include "oat_file_manager.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070053#include "os.h"
Andreas Gampe22f8e5c2014-07-09 11:38:21 -070054#include "runtime.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000055#include "type_lookup_table.h"
David Sehr9aa352e2016-09-15 18:13:52 -070056#include "utf-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080057#include "utils.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010058#include "utils/dex_cache_arrays_layout-inl.h"
Vladimir Marko97d7e1c2016-10-04 14:44:28 +010059#include "vdex_file.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070060
61namespace art {
62
Andreas Gampe46ee31b2016-12-14 10:11:49 -080063using android::base::StringPrintf;
64
Andreas Gampe049cff02015-12-01 23:27:12 -080065// Whether OatFile::Open will try dlopen. Fallback is our own ELF loader.
David Srbecky1baabf02015-06-16 17:12:34 +000066static constexpr bool kUseDlopen = true;
Andreas Gampefa8429b2015-04-07 18:34:42 -070067
Andreas Gampe049cff02015-12-01 23:27:12 -080068// Whether OatFile::Open will try dlopen on the host. On the host we're not linking against
Andreas Gampefa8429b2015-04-07 18:34:42 -070069// bionic, so cannot take advantage of the support for changed semantics (loading the same soname
70// multiple times). However, if/when we switch the above, we likely want to switch this, too,
71// to get test coverage of the code paths.
David Srbecky1baabf02015-06-16 17:12:34 +000072static constexpr bool kUseDlopenOnHost = true;
Andreas Gampefa8429b2015-04-07 18:34:42 -070073
74// For debugging, Open will print DlOpen error message if set to true.
75static constexpr bool kPrintDlOpenErrorMessage = false;
76
Andreas Gampe049cff02015-12-01 23:27:12 -080077// Note for OatFileBase and descendents:
78//
79// These are used in OatFile::Open to try all our loaders.
80//
81// The process is simple:
82//
83// 1) Allocate an instance through the standard constructor (location, executable)
84// 2) Load() to try to open the file.
85// 3) ComputeFields() to populate the OatFile fields like begin_, using FindDynamicSymbolAddress.
86// 4) PreSetup() for any steps that should be done before the final setup.
87// 5) Setup() to complete the procedure.
Richard Uhlere5fed032015-03-18 08:21:11 -070088
Andreas Gampe049cff02015-12-01 23:27:12 -080089class OatFileBase : public OatFile {
90 public:
91 virtual ~OatFileBase() {}
Richard Uhlere5fed032015-03-18 08:21:11 -070092
Andreas Gampe049cff02015-12-01 23:27:12 -080093 template <typename kOatFileBaseSubType>
David Brazdil7b49e6c2016-09-01 11:06:18 +010094 static OatFileBase* OpenOatFile(const std::string& vdex_filename,
95 const std::string& elf_filename,
Alex Light84d76052014-08-22 17:49:35 -070096 const std::string& location,
Andreas Gampe049cff02015-12-01 23:27:12 -080097 uint8_t* requested_base,
98 uint8_t* oat_file_begin,
99 bool writable,
100 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800101 bool low_4gb,
Richard Uhlere5fed032015-03-18 08:21:11 -0700102 const char* abs_dex_location,
Andreas Gampe049cff02015-12-01 23:27:12 -0800103 std::string* error_msg);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800104
Andreas Gampe049cff02015-12-01 23:27:12 -0800105 protected:
106 OatFileBase(const std::string& filename, bool executable) : OatFile(filename, executable) {}
Andreas Gampefa8429b2015-04-07 18:34:42 -0700107
Andreas Gampe049cff02015-12-01 23:27:12 -0800108 virtual const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
109 std::string* error_msg) const = 0;
110
Andreas Gampe4075f832016-05-18 13:09:54 -0700111 virtual void PreLoad() = 0;
112
David Brazdil7b49e6c2016-09-01 11:06:18 +0100113 bool LoadVdex(const std::string& vdex_filename,
114 bool writable,
115 bool low_4gb,
116 std::string* error_msg);
117
Andreas Gampe049cff02015-12-01 23:27:12 -0800118 virtual bool Load(const std::string& elf_filename,
119 uint8_t* oat_file_begin,
120 bool writable,
121 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800122 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800123 std::string* error_msg) = 0;
124
125 bool ComputeFields(uint8_t* requested_base,
126 const std::string& file_path,
127 std::string* error_msg);
128
129 virtual void PreSetup(const std::string& elf_filename) = 0;
130
131 bool Setup(const char* abs_dex_location, std::string* error_msg);
132
133 // Setters exposed for ElfOatFile.
134
135 void SetBegin(const uint8_t* begin) {
136 begin_ = begin;
Andreas Gampefa8429b2015-04-07 18:34:42 -0700137 }
138
Andreas Gampe049cff02015-12-01 23:27:12 -0800139 void SetEnd(const uint8_t* end) {
140 end_ = end;
141 }
142
David Brazdilc93b3be2016-09-12 18:49:58 +0100143 void SetVdex(VdexFile* vdex) {
144 vdex_.reset(vdex);
145 }
146
Andreas Gampe049cff02015-12-01 23:27:12 -0800147 private:
148 DISALLOW_COPY_AND_ASSIGN(OatFileBase);
149};
150
151template <typename kOatFileBaseSubType>
David Brazdil7b49e6c2016-09-01 11:06:18 +0100152OatFileBase* OatFileBase::OpenOatFile(const std::string& vdex_filename,
153 const std::string& elf_filename,
Andreas Gampe049cff02015-12-01 23:27:12 -0800154 const std::string& location,
155 uint8_t* requested_base,
156 uint8_t* oat_file_begin,
157 bool writable,
158 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800159 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800160 const char* abs_dex_location,
161 std::string* error_msg) {
162 std::unique_ptr<OatFileBase> ret(new kOatFileBaseSubType(location, executable));
Andreas Gampe4075f832016-05-18 13:09:54 -0700163
164 ret->PreLoad();
165
David Brazdil7b49e6c2016-09-01 11:06:18 +0100166 if (kIsVdexEnabled && !ret->LoadVdex(vdex_filename, writable, low_4gb, error_msg)) {
167 return nullptr;
168 }
169
Andreas Gampe049cff02015-12-01 23:27:12 -0800170 if (!ret->Load(elf_filename,
171 oat_file_begin,
172 writable,
173 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800174 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800175 error_msg)) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800176 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800177 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800178
Andreas Gampe049cff02015-12-01 23:27:12 -0800179 if (!ret->ComputeFields(requested_base, elf_filename, error_msg)) {
180 return nullptr;
181 }
Andreas Gampe4075f832016-05-18 13:09:54 -0700182
Andreas Gampe049cff02015-12-01 23:27:12 -0800183 ret->PreSetup(elf_filename);
184
185 if (!ret->Setup(abs_dex_location, error_msg)) {
186 return nullptr;
187 }
188
Dave Allison69dfe512014-07-11 17:11:58 +0000189 return ret.release();
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800190}
191
David Brazdil7b49e6c2016-09-01 11:06:18 +0100192bool OatFileBase::LoadVdex(const std::string& vdex_filename,
193 bool writable,
194 bool low_4gb,
195 std::string* error_msg) {
196 vdex_.reset(VdexFile::Open(vdex_filename, writable, low_4gb, error_msg));
197 if (vdex_.get() == nullptr) {
198 *error_msg = StringPrintf("Failed to load vdex file '%s' %s",
199 vdex_filename.c_str(),
200 error_msg->c_str());
201 return false;
202 }
203 return true;
204}
205
Andreas Gampe049cff02015-12-01 23:27:12 -0800206bool OatFileBase::ComputeFields(uint8_t* requested_base,
207 const std::string& file_path,
208 std::string* error_msg) {
209 std::string symbol_error_msg;
210 begin_ = FindDynamicSymbolAddress("oatdata", &symbol_error_msg);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700211 if (begin_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800212 *error_msg = StringPrintf("Failed to find oatdata symbol in '%s' %s",
213 file_path.c_str(),
214 symbol_error_msg.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700215 return false;
216 }
217 if (requested_base != nullptr && begin_ != requested_base) {
Nicolas Geoffrayf97cf2a2016-03-09 15:36:23 +0000218 // Host can fail this check. Do not dump there to avoid polluting the output.
Andreas Gampe7ec09042016-04-01 17:20:49 -0700219 if (kIsTargetBuild && (kIsDebugBuild || VLOG_IS_ON(oat))) {
Nicolas Geoffrayf97cf2a2016-03-09 15:36:23 +0000220 PrintFileToLog("/proc/self/maps", LogSeverity::WARNING);
221 }
Andreas Gampefa8429b2015-04-07 18:34:42 -0700222 *error_msg = StringPrintf("Failed to find oatdata symbol at expected address: "
Andreas Gampe049cff02015-12-01 23:27:12 -0800223 "oatdata=%p != expected=%p. See process maps in the log.",
224 begin_, requested_base);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700225 return false;
226 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800227 end_ = FindDynamicSymbolAddress("oatlastword", &symbol_error_msg);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700228 if (end_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800229 *error_msg = StringPrintf("Failed to find oatlastword symbol in '%s' %s",
230 file_path.c_str(),
231 symbol_error_msg.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700232 return false;
233 }
234 // Readjust to be non-inclusive upper bound.
235 end_ += sizeof(uint32_t);
236
Andreas Gampe049cff02015-12-01 23:27:12 -0800237 bss_begin_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbss", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700238 if (bss_begin_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800239 // No .bss section.
Andreas Gampefa8429b2015-04-07 18:34:42 -0700240 bss_end_ = nullptr;
Andreas Gampefa8429b2015-04-07 18:34:42 -0700241 } else {
Andreas Gampe049cff02015-12-01 23:27:12 -0800242 bss_end_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbsslastword", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700243 if (bss_end_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800244 *error_msg = StringPrintf("Failed to find oatbasslastword symbol in '%s'", file_path.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700245 return false;
246 }
247 // Readjust to be non-inclusive upper bound.
248 bss_end_ += sizeof(uint32_t);
Vladimir Markoaad75c62016-10-03 08:46:48 +0000249 // Find bss roots if present.
250 bss_roots_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbssroots", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700251 }
252
Andreas Gampe049cff02015-12-01 23:27:12 -0800253 return true;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800254}
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800255
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100256// Read an unaligned entry from the OatDexFile data in OatFile and advance the read
257// position by the number of bytes read, i.e. sizeof(T).
258// Return true on success, false if the read would go beyond the end of the OatFile.
259template <typename T>
Vladimir Marko722fa982015-10-19 18:18:27 +0100260inline static bool ReadOatDexFileData(const OatFile& oat_file,
261 /*inout*/const uint8_t** oat,
262 /*out*/T* value) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100263 DCHECK(oat != nullptr);
264 DCHECK(value != nullptr);
265 DCHECK_LE(*oat, oat_file.End());
266 if (UNLIKELY(static_cast<size_t>(oat_file.End() - *oat) < sizeof(T))) {
267 return false;
268 }
269 static_assert(std::is_trivial<T>::value, "T must be a trivial type");
270 typedef __attribute__((__aligned__(1))) T unaligned_type;
271 *value = *reinterpret_cast<const unaligned_type*>(*oat);
272 *oat += sizeof(T);
273 return true;
274}
275
Andreas Gampe049cff02015-12-01 23:27:12 -0800276bool OatFileBase::Setup(const char* abs_dex_location, std::string* error_msg) {
Brian Carlstromf1b30302013-03-28 10:35:32 -0700277 if (!GetOatHeader().IsValid()) {
Andreas Gampe2bcb3b22014-12-12 15:25:14 -0800278 std::string cause = GetOatHeader().GetValidationErrorMessage();
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100279 *error_msg = StringPrintf("Invalid oat header for '%s': %s",
280 GetLocation().c_str(),
Andreas Gampe2bcb3b22014-12-12 15:25:14 -0800281 cause.c_str());
Brian Carlstromf1b30302013-03-28 10:35:32 -0700282 return false;
283 }
Ian Rogers13735952014-10-08 12:43:28 -0700284 const uint8_t* oat = Begin();
Brian Carlstrome24fa612011-09-29 00:53:55 -0700285 oat += sizeof(OatHeader);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700286 if (oat > End()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700287 *error_msg = StringPrintf("In oat file '%s' found truncated OatHeader", GetLocation().c_str());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700288 return false;
289 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700290
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700291 oat += GetOatHeader().GetKeyValueStoreSize();
Brian Carlstromfb331d72013-07-25 22:00:16 -0700292 if (oat > End()) {
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700293 *error_msg = StringPrintf("In oat file '%s' found truncated variable-size data: "
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100294 "%p + %zu + %u <= %p",
295 GetLocation().c_str(),
296 Begin(),
297 sizeof(OatHeader),
298 GetOatHeader().GetKeyValueStoreSize(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700299 End());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700300 return false;
301 }
302
Vladimir Markoaad75c62016-10-03 08:46:48 +0000303 if (!IsAligned<alignof(GcRoot<mirror::Object>)>(bss_begin_) ||
304 !IsAligned<alignof(GcRoot<mirror::Object>)>(bss_roots_) ||
305 !IsAligned<alignof(GcRoot<mirror::Object>)>(bss_end_)) {
306 *error_msg = StringPrintf("In oat file '%s' found unaligned bss symbol(s): "
307 "begin = %p, roots = %p, end = %p",
308 GetLocation().c_str(),
309 bss_begin_,
310 bss_roots_,
311 bss_end_);
312 return false;
313 }
314
315 if (bss_roots_ != nullptr && (bss_roots_ < bss_begin_ || bss_roots_ > bss_end_)) {
316 *error_msg = StringPrintf("In oat file '%s' found bss roots outside .bss: "
317 "%p is outside range [%p, %p]",
318 GetLocation().c_str(),
319 bss_roots_,
320 bss_begin_,
321 bss_end_);
322 return false;
323 }
324
Andreas Gampe542451c2016-07-26 09:02:02 -0700325 PointerSize pointer_size = GetInstructionSetPointerSize(GetOatHeader().GetInstructionSet());
Vladimir Marko1998cd02017-01-13 13:02:58 +0000326 uint8_t* dex_cache_arrays = (bss_begin_ == bss_roots_) ? nullptr : bss_begin_;
327 uint8_t* dex_cache_arrays_end =
328 (bss_begin_ == bss_roots_) ? nullptr : (bss_roots_ != nullptr) ? bss_roots_ : bss_end_;
329 DCHECK_EQ(dex_cache_arrays != nullptr, dex_cache_arrays_end != nullptr);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100330 uint32_t dex_file_count = GetOatHeader().GetDexFileCount();
331 oat_dex_files_storage_.reserve(dex_file_count);
332 for (size_t i = 0; i < dex_file_count; i++) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100333 uint32_t dex_file_location_size;
334 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_location_size))) {
335 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu truncated after dex file "
336 "location size",
337 GetLocation().c_str(),
338 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700339 return false;
340 }
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100341 if (UNLIKELY(dex_file_location_size == 0U)) {
342 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu with empty location name",
343 GetLocation().c_str(),
344 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700345 return false;
346 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000347 if (UNLIKELY(static_cast<size_t>(End() - oat) < dex_file_location_size)) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100348 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu with truncated dex file "
349 "location",
350 GetLocation().c_str(),
351 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700352 return false;
353 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000354 const char* dex_file_location_data = reinterpret_cast<const char*>(oat);
355 oat += dex_file_location_size;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700356
Richard Uhlere5fed032015-03-18 08:21:11 -0700357 std::string dex_file_location = ResolveRelativeEncodedDexLocation(
358 abs_dex_location,
359 std::string(dex_file_location_data, dex_file_location_size));
Brian Carlstrome24fa612011-09-29 00:53:55 -0700360
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100361 uint32_t dex_file_checksum;
362 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_checksum))) {
363 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated after "
364 "dex file checksum",
365 GetLocation().c_str(),
366 i,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700367 dex_file_location.c_str());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700368 return false;
369 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700370
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100371 uint32_t dex_file_offset;
372 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_offset))) {
373 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated "
374 "after dex file offsets",
375 GetLocation().c_str(),
376 i,
377 dex_file_location.c_str());
378 return false;
379 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700380 if (UNLIKELY(dex_file_offset == 0U)) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100381 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with zero dex "
382 "file offset",
383 GetLocation().c_str(),
384 i,
385 dex_file_location.c_str());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700386 return false;
387 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100388 if (UNLIKELY(dex_file_offset > DexSize())) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100389 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
390 "offset %u > %zu",
391 GetLocation().c_str(),
392 i,
393 dex_file_location.c_str(),
394 dex_file_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100395 DexSize());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700396 return false;
397 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100398 if (UNLIKELY(DexSize() - dex_file_offset < sizeof(DexFile::Header))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000399 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
400 "offset %u of %zu but the size of dex file header is %zu",
401 GetLocation().c_str(),
402 i,
403 dex_file_location.c_str(),
404 dex_file_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100405 DexSize(),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000406 sizeof(DexFile::Header));
407 return false;
408 }
Brian Carlstrom89521892011-12-07 22:05:07 -0800409
David Brazdil7b49e6c2016-09-01 11:06:18 +0100410 const uint8_t* dex_file_pointer = DexBegin() + dex_file_offset;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700411 if (UNLIKELY(!DexFile::IsMagicValid(dex_file_pointer))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100412 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with invalid "
413 "dex file magic '%s'",
414 GetLocation().c_str(),
415 i,
416 dex_file_location.c_str(),
417 dex_file_pointer);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700418 return false;
419 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700420 if (UNLIKELY(!DexFile::IsVersionValid(dex_file_pointer))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100421 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with invalid "
422 "dex file version '%s'",
423 GetLocation().c_str(),
424 i,
425 dex_file_location.c_str(),
426 dex_file_pointer);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700427 return false;
428 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800429 const DexFile::Header* header = reinterpret_cast<const DexFile::Header*>(dex_file_pointer);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100430 if (DexSize() - dex_file_offset < header->file_size_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000431 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
432 "offset %u and size %u truncated at %zu",
433 GetLocation().c_str(),
434 i,
435 dex_file_location.c_str(),
436 dex_file_offset,
437 header->file_size_,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100438 DexSize());
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000439 return false;
440 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300441
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000442 uint32_t class_offsets_offset;
443 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &class_offsets_offset))) {
444 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated "
445 "after class offsets offset",
446 GetLocation().c_str(),
447 i,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300448 dex_file_location.c_str());
449 return false;
450 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000451 if (UNLIKELY(class_offsets_offset > Size()) ||
452 UNLIKELY((Size() - class_offsets_offset) / sizeof(uint32_t) < header->class_defs_size_)) {
453 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with truncated "
454 "class offsets, offset %u of %zu, class defs %u",
455 GetLocation().c_str(),
456 i,
457 dex_file_location.c_str(),
458 class_offsets_offset,
459 Size(),
460 header->class_defs_size_);
461 return false;
462 }
463 if (UNLIKELY(!IsAligned<alignof(uint32_t)>(class_offsets_offset))) {
464 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with unaligned "
465 "class offsets, offset %u",
466 GetLocation().c_str(),
467 i,
468 dex_file_location.c_str(),
469 class_offsets_offset);
470 return false;
471 }
472 const uint32_t* class_offsets_pointer =
473 reinterpret_cast<const uint32_t*>(Begin() + class_offsets_offset);
474
475 uint32_t lookup_table_offset;
476 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &lookup_table_offset))) {
477 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zd for '%s' truncated "
478 "after lookup table offset",
479 GetLocation().c_str(),
480 i,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300481 dex_file_location.c_str());
482 return false;
483 }
484 const uint8_t* lookup_table_data = lookup_table_offset != 0u
485 ? Begin() + lookup_table_offset
486 : nullptr;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000487 if (lookup_table_offset != 0u &&
488 (UNLIKELY(lookup_table_offset > Size()) ||
489 UNLIKELY(Size() - lookup_table_offset <
490 TypeLookupTable::RawDataLength(header->class_defs_size_)))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100491 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with truncated "
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000492 "type lookup table, offset %u of %zu, class defs %u",
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100493 GetLocation().c_str(),
494 i,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000495 dex_file_location.c_str(),
496 lookup_table_offset,
497 Size(),
498 header->class_defs_size_);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700499 return false;
500 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700501
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100502 uint8_t* current_dex_cache_arrays = nullptr;
Vladimir Marko09d09432015-09-08 13:47:48 +0100503 if (dex_cache_arrays != nullptr) {
504 DexCacheArraysLayout layout(pointer_size, *header);
505 if (layout.Size() != 0u) {
Vladimir Markoaad75c62016-10-03 08:46:48 +0000506 if (static_cast<size_t>(dex_cache_arrays_end - dex_cache_arrays) < layout.Size()) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100507 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with "
508 "truncated dex cache arrays, %zu < %zu.",
509 GetLocation().c_str(),
510 i,
511 dex_file_location.c_str(),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000512 static_cast<size_t>(dex_cache_arrays_end - dex_cache_arrays),
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100513 layout.Size());
Vladimir Marko09d09432015-09-08 13:47:48 +0100514 return false;
515 }
516 current_dex_cache_arrays = dex_cache_arrays;
517 dex_cache_arrays += layout.Size();
518 }
519 }
520
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100521 std::string canonical_location = DexFile::GetDexCanonicalLocation(dex_file_location.c_str());
522
523 // Create the OatDexFile and add it to the owning container.
Vladimir Marko539690a2014-06-05 18:36:42 +0100524 OatDexFile* oat_dex_file = new OatDexFile(this,
525 dex_file_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100526 canonical_location,
Vladimir Marko539690a2014-06-05 18:36:42 +0100527 dex_file_checksum,
528 dex_file_pointer,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300529 lookup_table_data,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000530 class_offsets_pointer,
Vladimir Marko09d09432015-09-08 13:47:48 +0100531 current_dex_cache_arrays);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100532 oat_dex_files_storage_.push_back(oat_dex_file);
533
534 // Add the location and canonical location (if different) to the oat_dex_files_ table.
Vladimir Marko3f5838d2014-08-07 18:07:18 +0100535 StringPiece key(oat_dex_file->GetDexFileLocation());
Vladimir Marko539690a2014-06-05 18:36:42 +0100536 oat_dex_files_.Put(key, oat_dex_file);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100537 if (canonical_location != dex_file_location) {
538 StringPiece canonical_key(oat_dex_file->GetCanonicalDexFileLocation());
539 oat_dex_files_.Put(canonical_key, oat_dex_file);
540 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700541 }
Vladimir Marko09d09432015-09-08 13:47:48 +0100542
Vladimir Markoaad75c62016-10-03 08:46:48 +0000543 if (dex_cache_arrays != dex_cache_arrays_end) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100544 // We expect the bss section to be either empty (dex_cache_arrays and bss_end_
Vladimir Markoaad75c62016-10-03 08:46:48 +0000545 // both null) or contain just the dex cache arrays and optionally some GC roots.
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100546 *error_msg = StringPrintf("In oat file '%s' found unexpected bss size bigger by %zu bytes.",
Vladimir Marko09d09432015-09-08 13:47:48 +0100547 GetLocation().c_str(),
548 static_cast<size_t>(bss_end_ - dex_cache_arrays));
549 return false;
550 }
Brian Carlstromf1b30302013-03-28 10:35:32 -0700551 return true;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700552}
553
Andreas Gampe049cff02015-12-01 23:27:12 -0800554////////////////////////
555// OatFile via dlopen //
556////////////////////////
557
Andreas Gampe049cff02015-12-01 23:27:12 -0800558class DlOpenOatFile FINAL : public OatFileBase {
559 public:
560 DlOpenOatFile(const std::string& filename, bool executable)
561 : OatFileBase(filename, executable),
562 dlopen_handle_(nullptr),
Richard Uhlera206c742016-05-24 15:04:22 -0700563 shared_objects_before_(0) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800564 }
565
566 ~DlOpenOatFile() {
567 if (dlopen_handle_ != nullptr) {
Richard Uhlera206c742016-05-24 15:04:22 -0700568 if (!kIsTargetBuild) {
569 MutexLock mu(Thread::Current(), *Locks::host_dlopen_handles_lock_);
570 host_dlopen_handles_.erase(dlopen_handle_);
Mathieu Chartierc7d3f4b2016-06-01 10:48:19 -0700571 dlclose(dlopen_handle_);
572 } else {
573 dlclose(dlopen_handle_);
Richard Uhlera206c742016-05-24 15:04:22 -0700574 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800575 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800576 }
577
578 protected:
579 const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
580 std::string* error_msg) const OVERRIDE {
581 const uint8_t* ptr =
582 reinterpret_cast<const uint8_t*>(dlsym(dlopen_handle_, symbol_name.c_str()));
583 if (ptr == nullptr) {
584 *error_msg = dlerror();
585 }
586 return ptr;
587 }
588
Andreas Gampe4075f832016-05-18 13:09:54 -0700589 void PreLoad() OVERRIDE;
590
Andreas Gampe049cff02015-12-01 23:27:12 -0800591 bool Load(const std::string& elf_filename,
592 uint8_t* oat_file_begin,
593 bool writable,
594 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800595 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800596 std::string* error_msg) OVERRIDE;
597
598 // Ask the linker where it mmaped the file and notify our mmap wrapper of the regions.
599 void PreSetup(const std::string& elf_filename) OVERRIDE;
600
601 private:
602 bool Dlopen(const std::string& elf_filename,
603 uint8_t* oat_file_begin,
604 std::string* error_msg);
605
Richard Uhlera206c742016-05-24 15:04:22 -0700606 // On the host, if the same library is loaded again with dlopen the same
607 // file handle is returned. This differs from the behavior of dlopen on the
608 // target, where dlopen reloads the library at a different address every
609 // time you load it. The runtime relies on the target behavior to ensure
610 // each instance of the loaded library has a unique dex cache. To avoid
611 // problems, we fall back to our own linker in the case when the same
612 // library is opened multiple times on host. dlopen_handles_ is used to
613 // detect that case.
614 // Guarded by host_dlopen_handles_lock_;
615 static std::unordered_set<void*> host_dlopen_handles_;
616
Andreas Gampe049cff02015-12-01 23:27:12 -0800617 // dlopen handle during runtime.
618 void* dlopen_handle_; // TODO: Unique_ptr with custom deleter.
619
620 // Dummy memory map objects corresponding to the regions mapped by dlopen.
621 std::vector<std::unique_ptr<MemMap>> dlopen_mmaps_;
622
Andreas Gampe4075f832016-05-18 13:09:54 -0700623 // The number of shared objects the linker told us about before loading. Used to
624 // (optimistically) optimize the PreSetup stage (see comment there).
625 size_t shared_objects_before_;
626
Andreas Gampe049cff02015-12-01 23:27:12 -0800627 DISALLOW_COPY_AND_ASSIGN(DlOpenOatFile);
628};
629
Richard Uhlera206c742016-05-24 15:04:22 -0700630std::unordered_set<void*> DlOpenOatFile::host_dlopen_handles_;
631
Andreas Gampe4075f832016-05-18 13:09:54 -0700632void DlOpenOatFile::PreLoad() {
633#ifdef __APPLE__
Andreas Gampe39004a62016-05-18 21:27:00 -0700634 UNUSED(shared_objects_before_);
Andreas Gampe4075f832016-05-18 13:09:54 -0700635 LOG(FATAL) << "Should not reach here.";
636 UNREACHABLE();
637#else
638 // Count the entries in dl_iterate_phdr we get at this point in time.
639 struct dl_iterate_context {
640 static int callback(struct dl_phdr_info *info ATTRIBUTE_UNUSED,
641 size_t size ATTRIBUTE_UNUSED,
642 void *data) {
643 reinterpret_cast<dl_iterate_context*>(data)->count++;
644 return 0; // Continue iteration.
645 }
646 size_t count = 0;
647 } context;
648
649 dl_iterate_phdr(dl_iterate_context::callback, &context);
650 shared_objects_before_ = context.count;
651#endif
652}
653
Andreas Gampe049cff02015-12-01 23:27:12 -0800654bool DlOpenOatFile::Load(const std::string& elf_filename,
655 uint8_t* oat_file_begin,
656 bool writable,
657 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800658 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800659 std::string* error_msg) {
660 // Use dlopen only when flagged to do so, and when it's OK to load things executable.
661 // TODO: Also try when not executable? The issue here could be re-mapping as writable (as
662 // !executable is a sign that we may want to patch), which may not be allowed for
663 // various reasons.
664 if (!kUseDlopen) {
665 *error_msg = "DlOpen is disabled.";
666 return false;
667 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800668 if (low_4gb) {
669 *error_msg = "DlOpen does not support low 4gb loading.";
670 return false;
671 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800672 if (writable) {
673 *error_msg = "DlOpen does not support writable loading.";
674 return false;
675 }
676 if (!executable) {
677 *error_msg = "DlOpen does not support non-executable loading.";
678 return false;
679 }
680
681 // dlopen always returns the same library if it is already opened on the host. For this reason
682 // we only use dlopen if we are the target or we do not already have the dex file opened. Having
683 // the same library loaded multiple times at different addresses is required for class unloading
684 // and for having dex caches arrays in the .bss section.
685 if (!kIsTargetBuild) {
686 if (!kUseDlopenOnHost) {
687 *error_msg = "DlOpen disabled for host.";
688 return false;
689 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800690 }
691
692 bool success = Dlopen(elf_filename, oat_file_begin, error_msg);
693 DCHECK(dlopen_handle_ != nullptr || !success);
694
695 return success;
696}
697
698bool DlOpenOatFile::Dlopen(const std::string& elf_filename,
699 uint8_t* oat_file_begin,
700 std::string* error_msg) {
701#ifdef __APPLE__
702 // The dl_iterate_phdr syscall is missing. There is similar API on OSX,
703 // but let's fallback to the custom loading code for the time being.
704 UNUSED(elf_filename, oat_file_begin);
705 *error_msg = "Dlopen unsupported on Mac.";
706 return false;
707#else
708 {
709 UniqueCPtr<char> absolute_path(realpath(elf_filename.c_str(), nullptr));
710 if (absolute_path == nullptr) {
711 *error_msg = StringPrintf("Failed to find absolute path for '%s'", elf_filename.c_str());
712 return false;
713 }
Bilyan Borisovbb661c02016-04-04 16:27:32 +0100714#ifdef ART_TARGET_ANDROID
Anton Kirilov3a2e78e2017-01-06 13:33:42 +0000715 android_dlextinfo extinfo = {};
Andreas Gampe049cff02015-12-01 23:27:12 -0800716 extinfo.flags = ANDROID_DLEXT_FORCE_LOAD | // Force-load, don't reuse handle
717 // (open oat files multiple
718 // times).
719 ANDROID_DLEXT_FORCE_FIXED_VADDR; // Take a non-zero vaddr as absolute
720 // (non-pic boot image).
Andreas Gampe226b91e2015-12-02 10:29:33 -0800721 if (oat_file_begin != nullptr) { //
722 extinfo.flags |= ANDROID_DLEXT_LOAD_AT_FIXED_ADDRESS; // Use the requested addr if
723 extinfo.reserved_addr = oat_file_begin; // vaddr = 0.
724 } // (pic boot image).
Andreas Gampe049cff02015-12-01 23:27:12 -0800725 dlopen_handle_ = android_dlopen_ext(absolute_path.get(), RTLD_NOW, &extinfo);
726#else
Andreas Gampe049cff02015-12-01 23:27:12 -0800727 UNUSED(oat_file_begin);
Julien Duraj1af0c4f2016-11-16 14:05:48 +0000728 static_assert(!kIsTargetBuild || kIsTargetLinux, "host_dlopen_handles_ will leak handles");
Mathieu Chartierc7d3f4b2016-06-01 10:48:19 -0700729 MutexLock mu(Thread::Current(), *Locks::host_dlopen_handles_lock_);
Richard Uhlera206c742016-05-24 15:04:22 -0700730 dlopen_handle_ = dlopen(absolute_path.get(), RTLD_NOW);
731 if (dlopen_handle_ != nullptr) {
Richard Uhlera206c742016-05-24 15:04:22 -0700732 if (!host_dlopen_handles_.insert(dlopen_handle_).second) {
733 dlclose(dlopen_handle_);
734 dlopen_handle_ = nullptr;
735 *error_msg = StringPrintf("host dlopen re-opened '%s'", elf_filename.c_str());
736 return false;
737 }
738 }
Bilyan Borisovbb661c02016-04-04 16:27:32 +0100739#endif // ART_TARGET_ANDROID
Andreas Gampe049cff02015-12-01 23:27:12 -0800740 }
741 if (dlopen_handle_ == nullptr) {
742 *error_msg = StringPrintf("Failed to dlopen '%s': %s", elf_filename.c_str(), dlerror());
743 return false;
744 }
745 return true;
746#endif
747}
748
749void DlOpenOatFile::PreSetup(const std::string& elf_filename) {
Andreas Gampe74f07b52015-12-02 11:53:26 -0800750#ifdef __APPLE__
751 UNUSED(elf_filename);
752 LOG(FATAL) << "Should not reach here.";
753 UNREACHABLE();
754#else
Andreas Gampe049cff02015-12-01 23:27:12 -0800755 struct dl_iterate_context {
756 static int callback(struct dl_phdr_info *info, size_t /* size */, void *data) {
757 auto* context = reinterpret_cast<dl_iterate_context*>(data);
Andreas Gampe4075f832016-05-18 13:09:54 -0700758 context->shared_objects_seen++;
759 if (context->shared_objects_seen < context->shared_objects_before) {
760 // We haven't been called yet for anything we haven't seen before. Just continue.
761 // Note: this is aggressively optimistic. If another thread was unloading a library,
762 // we may miss out here. However, this does not happen often in practice.
763 return 0;
764 }
765
Andreas Gampe049cff02015-12-01 23:27:12 -0800766 // See whether this callback corresponds to the file which we have just loaded.
767 bool contains_begin = false;
768 for (int i = 0; i < info->dlpi_phnum; i++) {
769 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
770 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
771 info->dlpi_phdr[i].p_vaddr);
772 size_t memsz = info->dlpi_phdr[i].p_memsz;
773 if (vaddr <= context->begin_ && context->begin_ < vaddr + memsz) {
774 contains_begin = true;
775 break;
776 }
777 }
778 }
779 // Add dummy mmaps for this file.
780 if (contains_begin) {
781 for (int i = 0; i < info->dlpi_phnum; i++) {
782 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
783 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
784 info->dlpi_phdr[i].p_vaddr);
785 size_t memsz = info->dlpi_phdr[i].p_memsz;
786 MemMap* mmap = MemMap::MapDummy(info->dlpi_name, vaddr, memsz);
787 context->dlopen_mmaps_->push_back(std::unique_ptr<MemMap>(mmap));
788 }
789 }
790 return 1; // Stop iteration and return 1 from dl_iterate_phdr.
791 }
792 return 0; // Continue iteration and return 0 from dl_iterate_phdr when finished.
793 }
794 const uint8_t* const begin_;
795 std::vector<std::unique_ptr<MemMap>>* const dlopen_mmaps_;
Andreas Gampe4075f832016-05-18 13:09:54 -0700796 const size_t shared_objects_before;
797 size_t shared_objects_seen;
798 };
799 dl_iterate_context context = { Begin(), &dlopen_mmaps_, shared_objects_before_, 0};
Andreas Gampe049cff02015-12-01 23:27:12 -0800800
801 if (dl_iterate_phdr(dl_iterate_context::callback, &context) == 0) {
Andreas Gampe4075f832016-05-18 13:09:54 -0700802 // Hm. Maybe our optimization went wrong. Try another time with shared_objects_before == 0
803 // before giving up. This should be unusual.
804 VLOG(oat) << "Need a second run in PreSetup, didn't find with shared_objects_before="
805 << shared_objects_before_;
806 dl_iterate_context context0 = { Begin(), &dlopen_mmaps_, 0, 0};
807 if (dl_iterate_phdr(dl_iterate_context::callback, &context0) == 0) {
808 // OK, give up and print an error.
809 PrintFileToLog("/proc/self/maps", LogSeverity::WARNING);
810 LOG(ERROR) << "File " << elf_filename << " loaded with dlopen but cannot find its mmaps.";
811 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800812 }
Andreas Gampe74f07b52015-12-02 11:53:26 -0800813#endif
Andreas Gampe049cff02015-12-01 23:27:12 -0800814}
815
816////////////////////////////////////////////////
817// OatFile via our own ElfFile implementation //
818////////////////////////////////////////////////
819
820class ElfOatFile FINAL : public OatFileBase {
821 public:
822 ElfOatFile(const std::string& filename, bool executable) : OatFileBase(filename, executable) {}
823
824 static ElfOatFile* OpenElfFile(File* file,
825 const std::string& location,
826 uint8_t* requested_base,
827 uint8_t* oat_file_begin, // Override base if not null
828 bool writable,
829 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800830 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800831 const char* abs_dex_location,
832 std::string* error_msg);
833
834 bool InitializeFromElfFile(ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +0100835 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -0800836 const char* abs_dex_location,
837 std::string* error_msg);
838
839 protected:
840 const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
841 std::string* error_msg) const OVERRIDE {
842 const uint8_t* ptr = elf_file_->FindDynamicSymbolAddress(symbol_name);
843 if (ptr == nullptr) {
844 *error_msg = "(Internal implementation could not find symbol)";
845 }
846 return ptr;
847 }
848
Andreas Gampe4075f832016-05-18 13:09:54 -0700849 void PreLoad() OVERRIDE {
850 }
851
Andreas Gampe049cff02015-12-01 23:27:12 -0800852 bool Load(const std::string& elf_filename,
853 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
854 bool writable,
855 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800856 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800857 std::string* error_msg) OVERRIDE;
858
859 void PreSetup(const std::string& elf_filename ATTRIBUTE_UNUSED) OVERRIDE {
860 }
861
862 private:
863 bool ElfFileOpen(File* file,
864 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
865 bool writable,
866 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800867 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800868 std::string* error_msg);
869
870 private:
871 // Backing memory map for oat file during cross compilation.
872 std::unique_ptr<ElfFile> elf_file_;
873
874 DISALLOW_COPY_AND_ASSIGN(ElfOatFile);
875};
876
877ElfOatFile* ElfOatFile::OpenElfFile(File* file,
878 const std::string& location,
879 uint8_t* requested_base,
880 uint8_t* oat_file_begin, // Override base if not null
881 bool writable,
882 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800883 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800884 const char* abs_dex_location,
885 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800886 ScopedTrace trace("Open elf file " + location);
Andreas Gampe049cff02015-12-01 23:27:12 -0800887 std::unique_ptr<ElfOatFile> oat_file(new ElfOatFile(location, executable));
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800888 bool success = oat_file->ElfFileOpen(file,
889 oat_file_begin,
890 writable,
891 low_4gb,
892 executable,
893 error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -0800894 if (!success) {
895 CHECK(!error_msg->empty());
896 return nullptr;
897 }
898
899 // Complete the setup.
900 if (!oat_file->ComputeFields(requested_base, file->GetPath(), error_msg)) {
901 return nullptr;
902 }
903
904 if (!oat_file->Setup(abs_dex_location, error_msg)) {
905 return nullptr;
906 }
907
908 return oat_file.release();
909}
910
911bool ElfOatFile::InitializeFromElfFile(ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +0100912 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -0800913 const char* abs_dex_location,
914 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800915 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -0800916 if (IsExecutable()) {
917 *error_msg = "Cannot initialize from elf file in executable mode.";
918 return false;
919 }
920 elf_file_.reset(elf_file);
David Brazdilc93b3be2016-09-12 18:49:58 +0100921 SetVdex(vdex_file);
Andreas Gampe049cff02015-12-01 23:27:12 -0800922 uint64_t offset, size;
923 bool has_section = elf_file->GetSectionOffsetAndSize(".rodata", &offset, &size);
924 CHECK(has_section);
925 SetBegin(elf_file->Begin() + offset);
926 SetEnd(elf_file->Begin() + size + offset);
927 // Ignore the optional .bss section when opening non-executable.
928 return Setup(abs_dex_location, error_msg);
929}
930
931bool ElfOatFile::Load(const std::string& elf_filename,
932 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
933 bool writable,
934 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800935 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800936 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800937 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -0800938 std::unique_ptr<File> file(OS::OpenFileForReading(elf_filename.c_str()));
939 if (file == nullptr) {
940 *error_msg = StringPrintf("Failed to open oat filename for reading: %s", strerror(errno));
941 return false;
942 }
943 return ElfOatFile::ElfFileOpen(file.get(),
944 oat_file_begin,
945 writable,
946 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800947 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800948 error_msg);
949}
950
951bool ElfOatFile::ElfFileOpen(File* file,
952 uint8_t* oat_file_begin,
953 bool writable,
954 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800955 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800956 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800957 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -0800958 // TODO: rename requested_base to oat_data_begin
959 elf_file_.reset(ElfFile::Open(file,
960 writable,
961 /*program_header_only*/true,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800962 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800963 error_msg,
964 oat_file_begin));
965 if (elf_file_ == nullptr) {
966 DCHECK(!error_msg->empty());
967 return false;
968 }
Brian Carlstromf5b0f2c2016-10-14 01:04:26 -0700969 bool loaded = elf_file_->Load(file, executable, low_4gb, error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -0800970 DCHECK(loaded || !error_msg->empty());
971 return loaded;
972}
973
974//////////////////////////
975// General OatFile code //
976//////////////////////////
977
978std::string OatFile::ResolveRelativeEncodedDexLocation(
979 const char* abs_dex_location, const std::string& rel_dex_location) {
980 if (abs_dex_location != nullptr && rel_dex_location[0] != '/') {
981 // Strip :classes<N>.dex used for secondary multidex files.
982 std::string base = DexFile::GetBaseLocation(rel_dex_location);
983 std::string multidex_suffix = DexFile::GetMultiDexSuffix(rel_dex_location);
984
985 // Check if the base is a suffix of the provided abs_dex_location.
986 std::string target_suffix = "/" + base;
987 std::string abs_location(abs_dex_location);
988 if (abs_location.size() > target_suffix.size()) {
989 size_t pos = abs_location.size() - target_suffix.size();
990 if (abs_location.compare(pos, std::string::npos, target_suffix) == 0) {
991 return abs_location + multidex_suffix;
992 }
993 }
994 }
995 return rel_dex_location;
996}
997
998static void CheckLocation(const std::string& location) {
999 CHECK(!location.empty());
1000}
1001
1002OatFile* OatFile::OpenWithElfFile(ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +01001003 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001004 const std::string& location,
1005 const char* abs_dex_location,
1006 std::string* error_msg) {
1007 std::unique_ptr<ElfOatFile> oat_file(new ElfOatFile(location, false /* executable */));
David Brazdilc93b3be2016-09-12 18:49:58 +01001008 return oat_file->InitializeFromElfFile(elf_file, vdex_file, abs_dex_location, error_msg)
Andreas Gampe049cff02015-12-01 23:27:12 -08001009 ? oat_file.release()
1010 : nullptr;
1011}
1012
David Brazdil7b49e6c2016-09-01 11:06:18 +01001013OatFile* OatFile::Open(const std::string& oat_filename,
1014 const std::string& oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001015 uint8_t* requested_base,
1016 uint8_t* oat_file_begin,
1017 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001018 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001019 const char* abs_dex_location,
1020 std::string* error_msg) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001021 ScopedTrace trace("Open oat file " + oat_location);
1022 CHECK(!oat_filename.empty()) << oat_location;
1023 CheckLocation(oat_location);
Andreas Gampe54315c72016-05-18 21:10:42 -07001024
David Brazdil7b49e6c2016-09-01 11:06:18 +01001025 std::string vdex_filename = ReplaceFileExtension(oat_filename, "vdex");
1026
1027 // Check that the files even exist, fast-fail.
1028 if (kIsVdexEnabled && !OS::FileExists(vdex_filename.c_str())) {
1029 *error_msg = StringPrintf("File %s does not exist.", vdex_filename.c_str());
1030 return nullptr;
1031 } else if (!OS::FileExists(oat_filename.c_str())) {
1032 *error_msg = StringPrintf("File %s does not exist.", oat_filename.c_str());
Andreas Gampe54315c72016-05-18 21:10:42 -07001033 return nullptr;
1034 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001035
1036 // Try dlopen first, as it is required for native debuggability. This will fail fast if dlopen is
1037 // disabled.
David Brazdil7b49e6c2016-09-01 11:06:18 +01001038 OatFile* with_dlopen = OatFileBase::OpenOatFile<DlOpenOatFile>(vdex_filename,
1039 oat_filename,
1040 oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001041 requested_base,
1042 oat_file_begin,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001043 false /* writable */,
Andreas Gampe049cff02015-12-01 23:27:12 -08001044 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001045 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001046 abs_dex_location,
1047 error_msg);
1048 if (with_dlopen != nullptr) {
1049 return with_dlopen;
1050 }
1051 if (kPrintDlOpenErrorMessage) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001052 LOG(ERROR) << "Failed to dlopen: " << oat_filename << " with error " << *error_msg;
Andreas Gampe049cff02015-12-01 23:27:12 -08001053 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001054 // If we aren't trying to execute, we just use our own ElfFile loader for a couple reasons:
1055 //
1056 // On target, dlopen may fail when compiling due to selinux restrictions on installd.
1057 //
1058 // We use our own ELF loader for Quick to deal with legacy apps that
1059 // open a generated dex file by name, remove the file, then open
1060 // another generated dex file with the same name. http://b/10614658
1061 //
1062 // On host, dlopen is expected to fail when cross compiling, so fall back to OpenElfFile.
1063 //
1064 //
1065 // Another independent reason is the absolute placement of boot.oat. dlopen on the host usually
1066 // 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 +01001067 OatFile* with_internal = OatFileBase::OpenOatFile<ElfOatFile>(vdex_filename,
1068 oat_filename,
1069 oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001070 requested_base,
1071 oat_file_begin,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001072 false /* writable */,
Andreas Gampe049cff02015-12-01 23:27:12 -08001073 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001074 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001075 abs_dex_location,
1076 error_msg);
1077 return with_internal;
1078}
1079
1080OatFile* OatFile::OpenWritable(File* file,
1081 const std::string& location,
1082 const char* abs_dex_location,
1083 std::string* error_msg) {
1084 CheckLocation(location);
1085 return ElfOatFile::OpenElfFile(file,
1086 location,
1087 nullptr,
1088 nullptr,
1089 true,
1090 false,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001091 /*low_4gb*/false,
Andreas Gampe049cff02015-12-01 23:27:12 -08001092 abs_dex_location,
1093 error_msg);
1094}
1095
1096OatFile* OatFile::OpenReadable(File* file,
1097 const std::string& location,
1098 const char* abs_dex_location,
1099 std::string* error_msg) {
1100 CheckLocation(location);
1101 return ElfOatFile::OpenElfFile(file,
1102 location,
1103 nullptr,
1104 nullptr,
1105 false,
1106 false,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001107 /*low_4gb*/false,
Andreas Gampe049cff02015-12-01 23:27:12 -08001108 abs_dex_location,
1109 error_msg);
1110}
1111
1112OatFile::OatFile(const std::string& location, bool is_executable)
1113 : location_(location),
David Brazdil7b49e6c2016-09-01 11:06:18 +01001114 vdex_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001115 begin_(nullptr),
1116 end_(nullptr),
1117 bss_begin_(nullptr),
1118 bss_end_(nullptr),
Vladimir Markoaad75c62016-10-03 08:46:48 +00001119 bss_roots_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001120 is_executable_(is_executable),
1121 secondary_lookup_lock_("OatFile secondary lookup lock", kOatFileSecondaryLookupLock) {
1122 CHECK(!location_.empty());
1123}
1124
1125OatFile::~OatFile() {
1126 STLDeleteElements(&oat_dex_files_storage_);
1127}
1128
Brian Carlstrome24fa612011-09-29 00:53:55 -07001129const OatHeader& OatFile::GetOatHeader() const {
Ian Rogers30fab402012-01-23 15:43:46 -08001130 return *reinterpret_cast<const OatHeader*>(Begin());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001131}
1132
Ian Rogers13735952014-10-08 12:43:28 -07001133const uint8_t* OatFile::Begin() const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001134 CHECK(begin_ != nullptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001135 return begin_;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001136}
1137
Ian Rogers13735952014-10-08 12:43:28 -07001138const uint8_t* OatFile::End() const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001139 CHECK(end_ != nullptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001140 return end_;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001141}
1142
Vladimir Marko5c42c292015-02-25 12:02:49 +00001143const uint8_t* OatFile::BssBegin() const {
1144 return bss_begin_;
1145}
1146
1147const uint8_t* OatFile::BssEnd() const {
1148 return bss_end_;
1149}
1150
David Brazdil7b49e6c2016-09-01 11:06:18 +01001151const uint8_t* OatFile::DexBegin() const {
1152 return kIsVdexEnabled ? vdex_->Begin() : Begin();
1153}
1154
1155const uint8_t* OatFile::DexEnd() const {
1156 return kIsVdexEnabled ? vdex_->End() : End();
1157}
1158
Vladimir Markoaad75c62016-10-03 08:46:48 +00001159ArrayRef<GcRoot<mirror::Object>> OatFile::GetBssGcRoots() const {
1160 if (bss_roots_ != nullptr) {
1161 auto* roots = reinterpret_cast<GcRoot<mirror::Object>*>(bss_roots_);
1162 auto* roots_end = reinterpret_cast<GcRoot<mirror::Object>*>(bss_end_);
1163 return ArrayRef<GcRoot<mirror::Object>>(roots, roots_end - roots);
1164 } else {
1165 return ArrayRef<GcRoot<mirror::Object>>();
1166 }
1167}
1168
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001169const OatFile::OatDexFile* OatFile::GetOatDexFile(const char* dex_location,
1170 const uint32_t* dex_location_checksum,
Richard Uhler9a37efc2016-08-05 16:32:55 -07001171 std::string* error_msg) const {
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001172 // NOTE: We assume here that the canonical location for a given dex_location never
1173 // changes. If it does (i.e. some symlink used by the filename changes) we may return
1174 // an incorrect OatDexFile. As long as we have a checksum to check, we shall return
1175 // an identical file or fail; otherwise we may see some unpredictable failures.
Calin Juravle4e1d5792014-07-15 23:56:47 +01001176
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001177 // TODO: Additional analysis of usage patterns to see if this can be simplified
1178 // without any performance loss, for example by not doing the first lock-free lookup.
1179
1180 const OatFile::OatDexFile* oat_dex_file = nullptr;
1181 StringPiece key(dex_location);
1182 // Try to find the key cheaply in the oat_dex_files_ map which holds dex locations
1183 // directly mentioned in the oat file and doesn't require locking.
1184 auto primary_it = oat_dex_files_.find(key);
1185 if (primary_it != oat_dex_files_.end()) {
1186 oat_dex_file = primary_it->second;
1187 DCHECK(oat_dex_file != nullptr);
1188 } else {
1189 // This dex_location is not one of the dex locations directly mentioned in the
1190 // oat file. The correct lookup is via the canonical location but first see in
1191 // the secondary_oat_dex_files_ whether we've looked up this location before.
1192 MutexLock mu(Thread::Current(), secondary_lookup_lock_);
1193 auto secondary_lb = secondary_oat_dex_files_.lower_bound(key);
1194 if (secondary_lb != secondary_oat_dex_files_.end() && key == secondary_lb->first) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001195 oat_dex_file = secondary_lb->second; // May be null.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001196 } else {
1197 // We haven't seen this dex_location before, we must check the canonical location.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001198 std::string dex_canonical_location = DexFile::GetDexCanonicalLocation(dex_location);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001199 if (dex_canonical_location != dex_location) {
1200 StringPiece canonical_key(dex_canonical_location);
1201 auto canonical_it = oat_dex_files_.find(canonical_key);
1202 if (canonical_it != oat_dex_files_.end()) {
1203 oat_dex_file = canonical_it->second;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001204 } // else keep null.
1205 } // else keep null.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001206
1207 // Copy the key to the string_cache_ and store the result in secondary map.
1208 string_cache_.emplace_back(key.data(), key.length());
1209 StringPiece key_copy(string_cache_.back());
1210 secondary_oat_dex_files_.PutBefore(secondary_lb, key_copy, oat_dex_file);
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001211 }
1212 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001213
1214 if (oat_dex_file == nullptr) {
1215 if (error_msg != nullptr) {
1216 std::string dex_canonical_location = DexFile::GetDexCanonicalLocation(dex_location);
1217 *error_msg = "Failed to find OatDexFile for DexFile " + std::string(dex_location)
1218 + " (canonical path " + dex_canonical_location + ") in OatFile " + GetLocation();
1219 }
1220 return nullptr;
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001221 }
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001222
Richard Uhler9a37efc2016-08-05 16:32:55 -07001223 if (dex_location_checksum != nullptr &&
1224 oat_dex_file->GetDexFileLocationChecksum() != *dex_location_checksum) {
1225 if (error_msg != nullptr) {
1226 std::string dex_canonical_location = DexFile::GetDexCanonicalLocation(dex_location);
1227 std::string checksum = StringPrintf("0x%08x", oat_dex_file->GetDexFileLocationChecksum());
1228 std::string required_checksum = StringPrintf("0x%08x", *dex_location_checksum);
1229 *error_msg = "OatDexFile for DexFile " + std::string(dex_location)
1230 + " (canonical path " + dex_canonical_location + ") in OatFile " + GetLocation()
1231 + " has checksum " + checksum + " but " + required_checksum + " was required";
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001232 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001233 return nullptr;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001234 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001235 return oat_dex_file;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001236}
1237
Brian Carlstrome24fa612011-09-29 00:53:55 -07001238OatFile::OatDexFile::OatDexFile(const OatFile* oat_file,
Elliott Hughesaa6a5882012-01-13 19:39:16 -08001239 const std::string& dex_file_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001240 const std::string& canonical_dex_file_location,
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001241 uint32_t dex_file_location_checksum,
Ian Rogers13735952014-10-08 12:43:28 -07001242 const uint8_t* dex_file_pointer,
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001243 const uint8_t* lookup_table_data,
Vladimir Marko09d09432015-09-08 13:47:48 +01001244 const uint32_t* oat_class_offsets_pointer,
Vladimir Marko06d7aaa2015-10-16 11:23:41 +01001245 uint8_t* dex_cache_arrays)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001246 : oat_file_(oat_file),
1247 dex_file_location_(dex_file_location),
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001248 canonical_dex_file_location_(canonical_dex_file_location),
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001249 dex_file_location_checksum_(dex_file_location_checksum),
Brian Carlstrom89521892011-12-07 22:05:07 -08001250 dex_file_pointer_(dex_file_pointer),
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001251 lookup_table_data_(lookup_table_data),
Vladimir Marko09d09432015-09-08 13:47:48 +01001252 oat_class_offsets_pointer_(oat_class_offsets_pointer),
David Sehr9aa352e2016-09-15 18:13:52 -07001253 dex_cache_arrays_(dex_cache_arrays) {
1254 // Initialize TypeLookupTable.
1255 if (lookup_table_data_ != nullptr) {
1256 // Peek the number of classes from the DexFile.
1257 const DexFile::Header* dex_header = reinterpret_cast<const DexFile::Header*>(dex_file_pointer_);
1258 const uint32_t num_class_defs = dex_header->class_defs_size_;
1259 if (lookup_table_data_ + TypeLookupTable::RawDataLength(num_class_defs) > GetOatFile()->End()) {
1260 LOG(WARNING) << "found truncated lookup table in " << dex_file_location_;
1261 } else {
Mathieu Chartier1b868492016-11-16 16:22:37 -08001262 lookup_table_ = TypeLookupTable::Open(dex_file_pointer_, lookup_table_data_, num_class_defs);
David Sehr9aa352e2016-09-15 18:13:52 -07001263 }
1264 }
1265}
Brian Carlstrome24fa612011-09-29 00:53:55 -07001266
Mathieu Chartier1b868492016-11-16 16:22:37 -08001267OatFile::OatDexFile::OatDexFile(std::unique_ptr<TypeLookupTable>&& lookup_table)
1268 : lookup_table_(std::move(lookup_table)) {}
1269
Brian Carlstrome24fa612011-09-29 00:53:55 -07001270OatFile::OatDexFile::~OatDexFile() {}
1271
Ian Rogers05f28c62012-10-23 18:12:13 -07001272size_t OatFile::OatDexFile::FileSize() const {
1273 return reinterpret_cast<const DexFile::Header*>(dex_file_pointer_)->file_size_;
1274}
1275
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001276std::unique_ptr<const DexFile> OatFile::OatDexFile::OpenDexFile(std::string* error_msg) const {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001277 ScopedTrace trace(__PRETTY_FUNCTION__);
Aart Bik37d6a3b2016-06-21 18:30:10 -07001278 static constexpr bool kVerify = false;
1279 static constexpr bool kVerifyChecksum = false;
Andreas Gampe3a2bd292016-01-26 17:23:47 -08001280 return DexFile::Open(dex_file_pointer_,
1281 FileSize(),
1282 dex_file_location_,
1283 dex_file_location_checksum_,
1284 this,
Aart Bik37d6a3b2016-06-21 18:30:10 -07001285 kVerify,
1286 kVerifyChecksum,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08001287 error_msg);
Brian Carlstrom89521892011-12-07 22:05:07 -08001288}
1289
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001290uint32_t OatFile::OatDexFile::GetOatClassOffset(uint16_t class_def_index) const {
1291 return oat_class_offsets_pointer_[class_def_index];
1292}
1293
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001294OatFile::OatClass OatFile::OatDexFile::GetOatClass(uint16_t class_def_index) const {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001295 uint32_t oat_class_offset = GetOatClassOffset(class_def_index);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001296
Ian Rogers13735952014-10-08 12:43:28 -07001297 const uint8_t* oat_class_pointer = oat_file_->Begin() + oat_class_offset;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001298 CHECK_LT(oat_class_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001299
Ian Rogers13735952014-10-08 12:43:28 -07001300 const uint8_t* status_pointer = oat_class_pointer;
Brian Carlstromba150c32013-08-27 17:31:03 -07001301 CHECK_LT(status_pointer, oat_file_->End()) << oat_file_->GetLocation();
1302 mirror::Class::Status status =
1303 static_cast<mirror::Class::Status>(*reinterpret_cast<const int16_t*>(status_pointer));
1304 CHECK_LT(status, mirror::Class::kStatusMax);
1305
Ian Rogers13735952014-10-08 12:43:28 -07001306 const uint8_t* type_pointer = status_pointer + sizeof(uint16_t);
Brian Carlstromba150c32013-08-27 17:31:03 -07001307 CHECK_LT(type_pointer, oat_file_->End()) << oat_file_->GetLocation();
1308 OatClassType type = static_cast<OatClassType>(*reinterpret_cast<const uint16_t*>(type_pointer));
1309 CHECK_LT(type, kOatClassMax);
1310
Ian Rogers13735952014-10-08 12:43:28 -07001311 const uint8_t* after_type_pointer = type_pointer + sizeof(int16_t);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001312 CHECK_LE(after_type_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07001313
Brian Carlstromcd937a92014-03-04 22:53:23 -08001314 uint32_t bitmap_size = 0;
Ian Rogers13735952014-10-08 12:43:28 -07001315 const uint8_t* bitmap_pointer = nullptr;
1316 const uint8_t* methods_pointer = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07001317 if (type != kOatClassNoneCompiled) {
1318 if (type == kOatClassSomeCompiled) {
1319 bitmap_size = static_cast<uint32_t>(*reinterpret_cast<const uint32_t*>(after_type_pointer));
1320 bitmap_pointer = after_type_pointer + sizeof(bitmap_size);
1321 CHECK_LE(bitmap_pointer, oat_file_->End()) << oat_file_->GetLocation();
1322 methods_pointer = bitmap_pointer + bitmap_size;
1323 } else {
1324 methods_pointer = after_type_pointer;
1325 }
1326 CHECK_LE(methods_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstromcd937a92014-03-04 22:53:23 -08001327 }
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001328
Richard Uhler07b3c232015-03-31 15:57:54 -07001329 return OatFile::OatClass(oat_file_,
1330 status,
1331 type,
1332 bitmap_size,
1333 reinterpret_cast<const uint32_t*>(bitmap_pointer),
1334 reinterpret_cast<const OatMethodOffsets*>(methods_pointer));
Brian Carlstrome24fa612011-09-29 00:53:55 -07001335}
1336
David Sehr9aa352e2016-09-15 18:13:52 -07001337const DexFile::ClassDef* OatFile::OatDexFile::FindClassDef(const DexFile& dex_file,
1338 const char* descriptor,
1339 size_t hash) {
1340 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1341 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
1342 if (LIKELY((oat_dex_file != nullptr) && (oat_dex_file->GetTypeLookupTable() != nullptr))) {
1343 const uint32_t class_def_idx = oat_dex_file->GetTypeLookupTable()->Lookup(descriptor, hash);
1344 return (class_def_idx != DexFile::kDexNoIndex) ? &dex_file.GetClassDef(class_def_idx) : nullptr;
1345 }
1346 // Fast path for rare no class defs case.
1347 const uint32_t num_class_defs = dex_file.NumClassDefs();
1348 if (num_class_defs == 0) {
1349 return nullptr;
1350 }
1351 const DexFile::TypeId* type_id = dex_file.FindTypeId(descriptor);
1352 if (type_id != nullptr) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001353 dex::TypeIndex type_idx = dex_file.GetIndexForTypeId(*type_id);
David Sehr9aa352e2016-09-15 18:13:52 -07001354 return dex_file.FindClassDef(type_idx);
1355 }
1356 return nullptr;
1357}
1358
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001359OatFile::OatClass::OatClass(const OatFile* oat_file,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001360 mirror::Class::Status status,
Brian Carlstromba150c32013-08-27 17:31:03 -07001361 OatClassType type,
1362 uint32_t bitmap_size,
1363 const uint32_t* bitmap_pointer,
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001364 const OatMethodOffsets* methods_pointer)
Brian Carlstromba150c32013-08-27 17:31:03 -07001365 : oat_file_(oat_file), status_(status), type_(type),
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001366 bitmap_(bitmap_pointer), methods_pointer_(methods_pointer) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001367 switch (type_) {
1368 case kOatClassAllCompiled: {
1369 CHECK_EQ(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001370 CHECK(bitmap_pointer == nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001371 CHECK(methods_pointer != nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001372 break;
1373 }
1374 case kOatClassSomeCompiled: {
1375 CHECK_NE(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001376 CHECK(bitmap_pointer != nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001377 CHECK(methods_pointer != nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001378 break;
1379 }
1380 case kOatClassNoneCompiled: {
1381 CHECK_EQ(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001382 CHECK(bitmap_pointer == nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001383 CHECK(methods_pointer_ == nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001384 break;
1385 }
1386 case kOatClassMax: {
1387 LOG(FATAL) << "Invalid OatClassType " << type_;
1388 break;
1389 }
1390 }
1391}
Brian Carlstrome24fa612011-09-29 00:53:55 -07001392
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001393uint32_t OatFile::OatClass::GetOatMethodOffsetsOffset(uint32_t method_index) const {
1394 const OatMethodOffsets* oat_method_offsets = GetOatMethodOffsets(method_index);
1395 if (oat_method_offsets == nullptr) {
1396 return 0u;
1397 }
1398 return reinterpret_cast<const uint8_t*>(oat_method_offsets) - oat_file_->Begin();
1399}
1400
1401const OatMethodOffsets* OatFile::OatClass::GetOatMethodOffsets(uint32_t method_index) const {
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001402 // 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 -07001403 if (methods_pointer_ == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001404 CHECK_EQ(kOatClassNoneCompiled, type_);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001405 return nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07001406 }
1407 size_t methods_pointer_index;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001408 if (bitmap_ == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001409 CHECK_EQ(kOatClassAllCompiled, type_);
1410 methods_pointer_index = method_index;
1411 } else {
1412 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001413 if (!BitVector::IsBitSet(bitmap_, method_index)) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001414 return nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07001415 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001416 size_t num_set_bits = BitVector::NumSetBits(bitmap_, method_index);
1417 methods_pointer_index = num_set_bits;
Brian Carlstromba150c32013-08-27 17:31:03 -07001418 }
1419 const OatMethodOffsets& oat_method_offsets = methods_pointer_[methods_pointer_index];
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001420 return &oat_method_offsets;
1421}
1422
1423const OatFile::OatMethod OatFile::OatClass::GetOatMethod(uint32_t method_index) const {
1424 const OatMethodOffsets* oat_method_offsets = GetOatMethodOffsets(method_index);
1425 if (oat_method_offsets == nullptr) {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001426 return OatMethod(nullptr, 0);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001427 }
1428 if (oat_file_->IsExecutable() ||
1429 Runtime::Current() == nullptr || // This case applies for oatdump.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001430 Runtime::Current()->IsAotCompiler()) {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001431 return OatMethod(oat_file_->Begin(), oat_method_offsets->code_offset_);
Alex Light9dcc4572014-08-14 14:16:26 -07001432 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001433 // We aren't allowed to use the compiled code. We just force it down the interpreted / jit
1434 // version.
1435 return OatMethod(oat_file_->Begin(), 0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001436}
1437
Mathieu Chartiere401d142015-04-22 13:56:20 -07001438void OatFile::OatMethod::LinkMethod(ArtMethod* method) const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001439 CHECK(method != nullptr);
Ian Rogersef7d42f2014-01-06 12:55:46 -08001440 method->SetEntryPointFromQuickCompiledCode(GetQuickCode());
Brian Carlstromae826982011-11-09 01:33:42 -08001441}
1442
Andreas Gampe7ba64962014-10-23 11:37:40 -07001443bool OatFile::IsPic() const {
Igor Murashkin46774762014-10-22 11:37:02 -07001444 return GetOatHeader().IsPic();
Andreas Gampe7ba64962014-10-23 11:37:40 -07001445 // TODO: Check against oat_patches. b/18144996
1446}
1447
Sebastien Hertz0de11332015-05-13 12:14:05 +02001448bool OatFile::IsDebuggable() const {
1449 return GetOatHeader().IsDebuggable();
1450}
1451
Andreas Gampe29d38e72016-03-23 15:31:51 +00001452CompilerFilter::Filter OatFile::GetCompilerFilter() const {
1453 return GetOatHeader().GetCompilerFilter();
Calin Juravleb077e152016-02-18 18:47:37 +00001454}
1455
Andreas Gampe7848da42015-04-09 11:15:04 -07001456static constexpr char kDexClassPathEncodingSeparator = '*';
1457
1458std::string OatFile::EncodeDexFileDependencies(const std::vector<const DexFile*>& dex_files) {
1459 std::ostringstream out;
1460
1461 for (const DexFile* dex_file : dex_files) {
1462 out << dex_file->GetLocation().c_str();
1463 out << kDexClassPathEncodingSeparator;
1464 out << dex_file->GetLocationChecksum();
1465 out << kDexClassPathEncodingSeparator;
1466 }
1467
1468 return out.str();
1469}
1470
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001471bool OatFile::CheckStaticDexFileDependencies(const char* dex_dependencies, std::string* msg) {
Andreas Gampe7848da42015-04-09 11:15:04 -07001472 if (dex_dependencies == nullptr || dex_dependencies[0] == 0) {
1473 // No dependencies.
1474 return true;
1475 }
1476
1477 // Assumption: this is not performance-critical. So it's OK to do this with a std::string and
1478 // Split() instead of manual parsing of the combined char*.
1479 std::vector<std::string> split;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001480 Split(dex_dependencies, kDexClassPathEncodingSeparator, &split);
Andreas Gampe7848da42015-04-09 11:15:04 -07001481 if (split.size() % 2 != 0) {
1482 // Expected pairs of location and checksum.
1483 *msg = StringPrintf("Odd number of elements in dependency list %s", dex_dependencies);
1484 return false;
1485 }
1486
1487 for (auto it = split.begin(), end = split.end(); it != end; it += 2) {
1488 std::string& location = *it;
1489 std::string& checksum = *(it + 1);
1490 int64_t converted = strtoll(checksum.c_str(), nullptr, 10);
1491 if (converted == 0) {
1492 // Conversion error.
1493 *msg = StringPrintf("Conversion error for %s", checksum.c_str());
1494 return false;
1495 }
1496
1497 uint32_t dex_checksum;
1498 std::string error_msg;
1499 if (DexFile::GetChecksum(DexFile::GetDexCanonicalLocation(location.c_str()).c_str(),
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001500 &dex_checksum,
1501 &error_msg)) {
Andreas Gampe7848da42015-04-09 11:15:04 -07001502 if (converted != dex_checksum) {
1503 *msg = StringPrintf("Checksums don't match for %s: %" PRId64 " vs %u",
1504 location.c_str(), converted, dex_checksum);
1505 return false;
1506 }
1507 } else {
1508 // Problem retrieving checksum.
1509 // TODO: odex files?
1510 *msg = StringPrintf("Could not retrieve checksum for %s: %s", location.c_str(),
1511 error_msg.c_str());
1512 return false;
1513 }
1514 }
1515
1516 return true;
1517}
1518
1519bool OatFile::GetDexLocationsFromDependencies(const char* dex_dependencies,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001520 std::vector<std::string>* locations) {
1521 DCHECK(locations != nullptr);
Andreas Gampe7848da42015-04-09 11:15:04 -07001522 if (dex_dependencies == nullptr || dex_dependencies[0] == 0) {
1523 return true;
1524 }
1525
1526 // Assumption: this is not performance-critical. So it's OK to do this with a std::string and
1527 // Split() instead of manual parsing of the combined char*.
1528 std::vector<std::string> split;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001529 Split(dex_dependencies, kDexClassPathEncodingSeparator, &split);
Andreas Gampe7848da42015-04-09 11:15:04 -07001530 if (split.size() % 2 != 0) {
1531 // Expected pairs of location and checksum.
1532 return false;
1533 }
1534
1535 for (auto it = split.begin(), end = split.end(); it != end; it += 2) {
1536 locations->push_back(*it);
1537 }
1538
1539 return true;
1540}
1541
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001542OatFile::OatClass OatFile::FindOatClass(const DexFile& dex_file,
1543 uint16_t class_def_idx,
1544 bool* found) {
1545 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
1546 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Mathieu Chartier1b868492016-11-16 16:22:37 -08001547 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001548 *found = false;
1549 return OatFile::OatClass::Invalid();
1550 }
1551 *found = true;
1552 return oat_dex_file->GetOatClass(class_def_idx);
1553}
1554
Mathieu Chartier1b868492016-11-16 16:22:37 -08001555void OatFile::OatDexFile::AssertAotCompiler() {
1556 CHECK(Runtime::Current()->IsAotCompiler());
1557}
1558
Brian Carlstrome24fa612011-09-29 00:53:55 -07001559} // namespace art