blob: b05d7accbaf5f2e8657480bc09a0e6d465be5391 [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
Mathieu Chartiere401d142015-04-22 13:56:20 -070035#include "art_method-inl.h"
Brian Carlstromba150c32013-08-27 17:31:03 -070036#include "base/bit_vector.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070037#include "base/enums.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080038#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080039#include "base/systrace.h"
Elliott Hughes76160052012-12-12 16:31:20 -080040#include "base/unix_file/fd_file.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080041#include "elf_file.h"
Alex Light84d76052014-08-22 17:49:35 -070042#include "elf_utils.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080043#include "oat.h"
David Srbecky1baabf02015-06-16 17:12:34 +000044#include "mem_map.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080045#include "mirror/class.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070046#include "mirror/object-inl.h"
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +010047#include "oat_file-inl.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070048#include "oat_file_manager.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070049#include "os.h"
Andreas Gampe22f8e5c2014-07-09 11:38:21 -070050#include "runtime.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000051#include "type_lookup_table.h"
David Sehr9aa352e2016-09-15 18:13:52 -070052#include "utf-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080053#include "utils.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010054#include "utils/dex_cache_arrays_layout-inl.h"
Vladimir Marko97d7e1c2016-10-04 14:44:28 +010055#include "vdex_file.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070056
57namespace art {
58
Andreas Gampe049cff02015-12-01 23:27:12 -080059// Whether OatFile::Open will try dlopen. Fallback is our own ELF loader.
David Srbecky1baabf02015-06-16 17:12:34 +000060static constexpr bool kUseDlopen = true;
Andreas Gampefa8429b2015-04-07 18:34:42 -070061
Andreas Gampe049cff02015-12-01 23:27:12 -080062// Whether OatFile::Open will try dlopen on the host. On the host we're not linking against
Andreas Gampefa8429b2015-04-07 18:34:42 -070063// bionic, so cannot take advantage of the support for changed semantics (loading the same soname
64// multiple times). However, if/when we switch the above, we likely want to switch this, too,
65// to get test coverage of the code paths.
David Srbecky1baabf02015-06-16 17:12:34 +000066static constexpr bool kUseDlopenOnHost = true;
Andreas Gampefa8429b2015-04-07 18:34:42 -070067
68// For debugging, Open will print DlOpen error message if set to true.
69static constexpr bool kPrintDlOpenErrorMessage = false;
70
Andreas Gampe049cff02015-12-01 23:27:12 -080071// Note for OatFileBase and descendents:
72//
73// These are used in OatFile::Open to try all our loaders.
74//
75// The process is simple:
76//
77// 1) Allocate an instance through the standard constructor (location, executable)
78// 2) Load() to try to open the file.
79// 3) ComputeFields() to populate the OatFile fields like begin_, using FindDynamicSymbolAddress.
80// 4) PreSetup() for any steps that should be done before the final setup.
81// 5) Setup() to complete the procedure.
Richard Uhlere5fed032015-03-18 08:21:11 -070082
Andreas Gampe049cff02015-12-01 23:27:12 -080083class OatFileBase : public OatFile {
84 public:
85 virtual ~OatFileBase() {}
Richard Uhlere5fed032015-03-18 08:21:11 -070086
Andreas Gampe049cff02015-12-01 23:27:12 -080087 template <typename kOatFileBaseSubType>
David Brazdil7b49e6c2016-09-01 11:06:18 +010088 static OatFileBase* OpenOatFile(const std::string& vdex_filename,
89 const std::string& elf_filename,
Alex Light84d76052014-08-22 17:49:35 -070090 const std::string& location,
Andreas Gampe049cff02015-12-01 23:27:12 -080091 uint8_t* requested_base,
92 uint8_t* oat_file_begin,
93 bool writable,
94 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -080095 bool low_4gb,
Richard Uhlere5fed032015-03-18 08:21:11 -070096 const char* abs_dex_location,
Andreas Gampe049cff02015-12-01 23:27:12 -080097 std::string* error_msg);
Brian Carlstrom700c8d32012-11-05 10:42:02 -080098
Andreas Gampe049cff02015-12-01 23:27:12 -080099 protected:
100 OatFileBase(const std::string& filename, bool executable) : OatFile(filename, executable) {}
Andreas Gampefa8429b2015-04-07 18:34:42 -0700101
Andreas Gampe049cff02015-12-01 23:27:12 -0800102 virtual const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
103 std::string* error_msg) const = 0;
104
Andreas Gampe4075f832016-05-18 13:09:54 -0700105 virtual void PreLoad() = 0;
106
David Brazdil7b49e6c2016-09-01 11:06:18 +0100107 bool LoadVdex(const std::string& vdex_filename,
108 bool writable,
109 bool low_4gb,
110 std::string* error_msg);
111
Andreas Gampe049cff02015-12-01 23:27:12 -0800112 virtual bool Load(const std::string& elf_filename,
113 uint8_t* oat_file_begin,
114 bool writable,
115 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800116 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800117 std::string* error_msg) = 0;
118
119 bool ComputeFields(uint8_t* requested_base,
120 const std::string& file_path,
121 std::string* error_msg);
122
123 virtual void PreSetup(const std::string& elf_filename) = 0;
124
125 bool Setup(const char* abs_dex_location, std::string* error_msg);
126
127 // Setters exposed for ElfOatFile.
128
129 void SetBegin(const uint8_t* begin) {
130 begin_ = begin;
Andreas Gampefa8429b2015-04-07 18:34:42 -0700131 }
132
Andreas Gampe049cff02015-12-01 23:27:12 -0800133 void SetEnd(const uint8_t* end) {
134 end_ = end;
135 }
136
David Brazdilc93b3be2016-09-12 18:49:58 +0100137 void SetVdex(VdexFile* vdex) {
138 vdex_.reset(vdex);
139 }
140
Andreas Gampe049cff02015-12-01 23:27:12 -0800141 private:
142 DISALLOW_COPY_AND_ASSIGN(OatFileBase);
143};
144
145template <typename kOatFileBaseSubType>
David Brazdil7b49e6c2016-09-01 11:06:18 +0100146OatFileBase* OatFileBase::OpenOatFile(const std::string& vdex_filename,
147 const std::string& elf_filename,
Andreas Gampe049cff02015-12-01 23:27:12 -0800148 const std::string& location,
149 uint8_t* requested_base,
150 uint8_t* oat_file_begin,
151 bool writable,
152 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800153 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800154 const char* abs_dex_location,
155 std::string* error_msg) {
156 std::unique_ptr<OatFileBase> ret(new kOatFileBaseSubType(location, executable));
Andreas Gampe4075f832016-05-18 13:09:54 -0700157
158 ret->PreLoad();
159
David Brazdil7b49e6c2016-09-01 11:06:18 +0100160 if (kIsVdexEnabled && !ret->LoadVdex(vdex_filename, writable, low_4gb, error_msg)) {
161 return nullptr;
162 }
163
Andreas Gampe049cff02015-12-01 23:27:12 -0800164 if (!ret->Load(elf_filename,
165 oat_file_begin,
166 writable,
167 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800168 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800169 error_msg)) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800170 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800171 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800172
Andreas Gampe049cff02015-12-01 23:27:12 -0800173 if (!ret->ComputeFields(requested_base, elf_filename, error_msg)) {
174 return nullptr;
175 }
Andreas Gampe4075f832016-05-18 13:09:54 -0700176
Andreas Gampe049cff02015-12-01 23:27:12 -0800177 ret->PreSetup(elf_filename);
178
179 if (!ret->Setup(abs_dex_location, error_msg)) {
180 return nullptr;
181 }
182
Dave Allison69dfe512014-07-11 17:11:58 +0000183 return ret.release();
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800184}
185
David Brazdil7b49e6c2016-09-01 11:06:18 +0100186bool OatFileBase::LoadVdex(const std::string& vdex_filename,
187 bool writable,
188 bool low_4gb,
189 std::string* error_msg) {
190 vdex_.reset(VdexFile::Open(vdex_filename, writable, low_4gb, error_msg));
191 if (vdex_.get() == nullptr) {
192 *error_msg = StringPrintf("Failed to load vdex file '%s' %s",
193 vdex_filename.c_str(),
194 error_msg->c_str());
195 return false;
196 }
197 return true;
198}
199
Andreas Gampe049cff02015-12-01 23:27:12 -0800200bool OatFileBase::ComputeFields(uint8_t* requested_base,
201 const std::string& file_path,
202 std::string* error_msg) {
203 std::string symbol_error_msg;
204 begin_ = FindDynamicSymbolAddress("oatdata", &symbol_error_msg);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700205 if (begin_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800206 *error_msg = StringPrintf("Failed to find oatdata symbol in '%s' %s",
207 file_path.c_str(),
208 symbol_error_msg.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700209 return false;
210 }
211 if (requested_base != nullptr && begin_ != requested_base) {
Nicolas Geoffrayf97cf2a2016-03-09 15:36:23 +0000212 // Host can fail this check. Do not dump there to avoid polluting the output.
Andreas Gampe7ec09042016-04-01 17:20:49 -0700213 if (kIsTargetBuild && (kIsDebugBuild || VLOG_IS_ON(oat))) {
Nicolas Geoffrayf97cf2a2016-03-09 15:36:23 +0000214 PrintFileToLog("/proc/self/maps", LogSeverity::WARNING);
215 }
Andreas Gampefa8429b2015-04-07 18:34:42 -0700216 *error_msg = StringPrintf("Failed to find oatdata symbol at expected address: "
Andreas Gampe049cff02015-12-01 23:27:12 -0800217 "oatdata=%p != expected=%p. See process maps in the log.",
218 begin_, requested_base);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700219 return false;
220 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800221 end_ = FindDynamicSymbolAddress("oatlastword", &symbol_error_msg);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700222 if (end_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800223 *error_msg = StringPrintf("Failed to find oatlastword symbol in '%s' %s",
224 file_path.c_str(),
225 symbol_error_msg.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700226 return false;
227 }
228 // Readjust to be non-inclusive upper bound.
229 end_ += sizeof(uint32_t);
230
Andreas Gampe049cff02015-12-01 23:27:12 -0800231 bss_begin_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbss", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700232 if (bss_begin_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800233 // No .bss section.
Andreas Gampefa8429b2015-04-07 18:34:42 -0700234 bss_end_ = nullptr;
Andreas Gampefa8429b2015-04-07 18:34:42 -0700235 } else {
Andreas Gampe049cff02015-12-01 23:27:12 -0800236 bss_end_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbsslastword", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700237 if (bss_end_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800238 *error_msg = StringPrintf("Failed to find oatbasslastword symbol in '%s'", file_path.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700239 return false;
240 }
241 // Readjust to be non-inclusive upper bound.
242 bss_end_ += sizeof(uint32_t);
243 }
244
Andreas Gampe049cff02015-12-01 23:27:12 -0800245 return true;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800246}
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800247
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100248// Read an unaligned entry from the OatDexFile data in OatFile and advance the read
249// position by the number of bytes read, i.e. sizeof(T).
250// Return true on success, false if the read would go beyond the end of the OatFile.
251template <typename T>
Vladimir Marko722fa982015-10-19 18:18:27 +0100252inline static bool ReadOatDexFileData(const OatFile& oat_file,
253 /*inout*/const uint8_t** oat,
254 /*out*/T* value) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100255 DCHECK(oat != nullptr);
256 DCHECK(value != nullptr);
257 DCHECK_LE(*oat, oat_file.End());
258 if (UNLIKELY(static_cast<size_t>(oat_file.End() - *oat) < sizeof(T))) {
259 return false;
260 }
261 static_assert(std::is_trivial<T>::value, "T must be a trivial type");
262 typedef __attribute__((__aligned__(1))) T unaligned_type;
263 *value = *reinterpret_cast<const unaligned_type*>(*oat);
264 *oat += sizeof(T);
265 return true;
266}
267
Andreas Gampe049cff02015-12-01 23:27:12 -0800268bool OatFileBase::Setup(const char* abs_dex_location, std::string* error_msg) {
Brian Carlstromf1b30302013-03-28 10:35:32 -0700269 if (!GetOatHeader().IsValid()) {
Andreas Gampe2bcb3b22014-12-12 15:25:14 -0800270 std::string cause = GetOatHeader().GetValidationErrorMessage();
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100271 *error_msg = StringPrintf("Invalid oat header for '%s': %s",
272 GetLocation().c_str(),
Andreas Gampe2bcb3b22014-12-12 15:25:14 -0800273 cause.c_str());
Brian Carlstromf1b30302013-03-28 10:35:32 -0700274 return false;
275 }
Ian Rogers13735952014-10-08 12:43:28 -0700276 const uint8_t* oat = Begin();
Brian Carlstrome24fa612011-09-29 00:53:55 -0700277 oat += sizeof(OatHeader);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700278 if (oat > End()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700279 *error_msg = StringPrintf("In oat file '%s' found truncated OatHeader", GetLocation().c_str());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700280 return false;
281 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700282
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700283 oat += GetOatHeader().GetKeyValueStoreSize();
Brian Carlstromfb331d72013-07-25 22:00:16 -0700284 if (oat > End()) {
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700285 *error_msg = StringPrintf("In oat file '%s' found truncated variable-size data: "
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100286 "%p + %zu + %u <= %p",
287 GetLocation().c_str(),
288 Begin(),
289 sizeof(OatHeader),
290 GetOatHeader().GetKeyValueStoreSize(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700291 End());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700292 return false;
293 }
294
Andreas Gampe542451c2016-07-26 09:02:02 -0700295 PointerSize pointer_size = GetInstructionSetPointerSize(GetOatHeader().GetInstructionSet());
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100296 uint8_t* dex_cache_arrays = bss_begin_;
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100297 uint32_t dex_file_count = GetOatHeader().GetDexFileCount();
298 oat_dex_files_storage_.reserve(dex_file_count);
299 for (size_t i = 0; i < dex_file_count; i++) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100300 uint32_t dex_file_location_size;
301 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_location_size))) {
302 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu truncated after dex file "
303 "location size",
304 GetLocation().c_str(),
305 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700306 return false;
307 }
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100308 if (UNLIKELY(dex_file_location_size == 0U)) {
309 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu with empty location name",
310 GetLocation().c_str(),
311 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700312 return false;
313 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000314 if (UNLIKELY(static_cast<size_t>(End() - oat) < dex_file_location_size)) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100315 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu with truncated dex file "
316 "location",
317 GetLocation().c_str(),
318 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700319 return false;
320 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000321 const char* dex_file_location_data = reinterpret_cast<const char*>(oat);
322 oat += dex_file_location_size;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700323
Richard Uhlere5fed032015-03-18 08:21:11 -0700324 std::string dex_file_location = ResolveRelativeEncodedDexLocation(
325 abs_dex_location,
326 std::string(dex_file_location_data, dex_file_location_size));
Brian Carlstrome24fa612011-09-29 00:53:55 -0700327
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100328 uint32_t dex_file_checksum;
329 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_checksum))) {
330 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated after "
331 "dex file checksum",
332 GetLocation().c_str(),
333 i,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700334 dex_file_location.c_str());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700335 return false;
336 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700337
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100338 uint32_t dex_file_offset;
339 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_offset))) {
340 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated "
341 "after dex file offsets",
342 GetLocation().c_str(),
343 i,
344 dex_file_location.c_str());
345 return false;
346 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700347 if (UNLIKELY(dex_file_offset == 0U)) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100348 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with zero dex "
349 "file offset",
350 GetLocation().c_str(),
351 i,
352 dex_file_location.c_str());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700353 return false;
354 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100355 if (UNLIKELY(dex_file_offset > DexSize())) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100356 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
357 "offset %u > %zu",
358 GetLocation().c_str(),
359 i,
360 dex_file_location.c_str(),
361 dex_file_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100362 DexSize());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700363 return false;
364 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100365 if (UNLIKELY(DexSize() - dex_file_offset < sizeof(DexFile::Header))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000366 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
367 "offset %u of %zu but the size of dex file header is %zu",
368 GetLocation().c_str(),
369 i,
370 dex_file_location.c_str(),
371 dex_file_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100372 DexSize(),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000373 sizeof(DexFile::Header));
374 return false;
375 }
Brian Carlstrom89521892011-12-07 22:05:07 -0800376
David Brazdil7b49e6c2016-09-01 11:06:18 +0100377 const uint8_t* dex_file_pointer = DexBegin() + dex_file_offset;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700378 if (UNLIKELY(!DexFile::IsMagicValid(dex_file_pointer))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100379 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with invalid "
380 "dex file magic '%s'",
381 GetLocation().c_str(),
382 i,
383 dex_file_location.c_str(),
384 dex_file_pointer);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700385 return false;
386 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700387 if (UNLIKELY(!DexFile::IsVersionValid(dex_file_pointer))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100388 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with invalid "
389 "dex file version '%s'",
390 GetLocation().c_str(),
391 i,
392 dex_file_location.c_str(),
393 dex_file_pointer);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700394 return false;
395 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800396 const DexFile::Header* header = reinterpret_cast<const DexFile::Header*>(dex_file_pointer);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100397 if (DexSize() - dex_file_offset < header->file_size_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000398 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
399 "offset %u and size %u truncated at %zu",
400 GetLocation().c_str(),
401 i,
402 dex_file_location.c_str(),
403 dex_file_offset,
404 header->file_size_,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100405 DexSize());
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000406 return false;
407 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300408
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000409 uint32_t class_offsets_offset;
410 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &class_offsets_offset))) {
411 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated "
412 "after class offsets offset",
413 GetLocation().c_str(),
414 i,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300415 dex_file_location.c_str());
416 return false;
417 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000418 if (UNLIKELY(class_offsets_offset > Size()) ||
419 UNLIKELY((Size() - class_offsets_offset) / sizeof(uint32_t) < header->class_defs_size_)) {
420 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with truncated "
421 "class offsets, offset %u of %zu, class defs %u",
422 GetLocation().c_str(),
423 i,
424 dex_file_location.c_str(),
425 class_offsets_offset,
426 Size(),
427 header->class_defs_size_);
428 return false;
429 }
430 if (UNLIKELY(!IsAligned<alignof(uint32_t)>(class_offsets_offset))) {
431 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with unaligned "
432 "class offsets, offset %u",
433 GetLocation().c_str(),
434 i,
435 dex_file_location.c_str(),
436 class_offsets_offset);
437 return false;
438 }
439 const uint32_t* class_offsets_pointer =
440 reinterpret_cast<const uint32_t*>(Begin() + class_offsets_offset);
441
442 uint32_t lookup_table_offset;
443 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &lookup_table_offset))) {
444 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zd for '%s' truncated "
445 "after lookup table offset",
446 GetLocation().c_str(),
447 i,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300448 dex_file_location.c_str());
449 return false;
450 }
451 const uint8_t* lookup_table_data = lookup_table_offset != 0u
452 ? Begin() + lookup_table_offset
453 : nullptr;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000454 if (lookup_table_offset != 0u &&
455 (UNLIKELY(lookup_table_offset > Size()) ||
456 UNLIKELY(Size() - lookup_table_offset <
457 TypeLookupTable::RawDataLength(header->class_defs_size_)))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100458 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with truncated "
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000459 "type lookup table, offset %u of %zu, class defs %u",
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100460 GetLocation().c_str(),
461 i,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000462 dex_file_location.c_str(),
463 lookup_table_offset,
464 Size(),
465 header->class_defs_size_);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700466 return false;
467 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700468
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100469 uint8_t* current_dex_cache_arrays = nullptr;
Vladimir Marko09d09432015-09-08 13:47:48 +0100470 if (dex_cache_arrays != nullptr) {
471 DexCacheArraysLayout layout(pointer_size, *header);
472 if (layout.Size() != 0u) {
Vladimir Marko5f926052016-09-30 17:04:49 +0000473 if (static_cast<size_t>(bss_end_ - dex_cache_arrays) < layout.Size()) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100474 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with "
475 "truncated dex cache arrays, %zu < %zu.",
476 GetLocation().c_str(),
477 i,
478 dex_file_location.c_str(),
Vladimir Marko5f926052016-09-30 17:04:49 +0000479 static_cast<size_t>(bss_end_ - dex_cache_arrays),
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100480 layout.Size());
Vladimir Marko09d09432015-09-08 13:47:48 +0100481 return false;
482 }
483 current_dex_cache_arrays = dex_cache_arrays;
484 dex_cache_arrays += layout.Size();
485 }
486 }
487
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100488 std::string canonical_location = DexFile::GetDexCanonicalLocation(dex_file_location.c_str());
489
490 // Create the OatDexFile and add it to the owning container.
Vladimir Marko539690a2014-06-05 18:36:42 +0100491 OatDexFile* oat_dex_file = new OatDexFile(this,
492 dex_file_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100493 canonical_location,
Vladimir Marko539690a2014-06-05 18:36:42 +0100494 dex_file_checksum,
495 dex_file_pointer,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300496 lookup_table_data,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000497 class_offsets_pointer,
Vladimir Marko09d09432015-09-08 13:47:48 +0100498 current_dex_cache_arrays);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100499 oat_dex_files_storage_.push_back(oat_dex_file);
500
501 // Add the location and canonical location (if different) to the oat_dex_files_ table.
Vladimir Marko3f5838d2014-08-07 18:07:18 +0100502 StringPiece key(oat_dex_file->GetDexFileLocation());
Vladimir Marko539690a2014-06-05 18:36:42 +0100503 oat_dex_files_.Put(key, oat_dex_file);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100504 if (canonical_location != dex_file_location) {
505 StringPiece canonical_key(oat_dex_file->GetCanonicalDexFileLocation());
506 oat_dex_files_.Put(canonical_key, oat_dex_file);
507 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700508 }
Vladimir Marko09d09432015-09-08 13:47:48 +0100509
Vladimir Marko5f926052016-09-30 17:04:49 +0000510 if (dex_cache_arrays != bss_end_) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100511 // We expect the bss section to be either empty (dex_cache_arrays and bss_end_
Vladimir Marko5f926052016-09-30 17:04:49 +0000512 // both null) or contain just the dex cache arrays and nothing else.
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100513 *error_msg = StringPrintf("In oat file '%s' found unexpected bss size bigger by %zu bytes.",
Vladimir Marko09d09432015-09-08 13:47:48 +0100514 GetLocation().c_str(),
515 static_cast<size_t>(bss_end_ - dex_cache_arrays));
516 return false;
517 }
Brian Carlstromf1b30302013-03-28 10:35:32 -0700518 return true;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700519}
520
Andreas Gampe049cff02015-12-01 23:27:12 -0800521////////////////////////
522// OatFile via dlopen //
523////////////////////////
524
Andreas Gampe049cff02015-12-01 23:27:12 -0800525class DlOpenOatFile FINAL : public OatFileBase {
526 public:
527 DlOpenOatFile(const std::string& filename, bool executable)
528 : OatFileBase(filename, executable),
529 dlopen_handle_(nullptr),
Richard Uhlera206c742016-05-24 15:04:22 -0700530 shared_objects_before_(0) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800531 }
532
533 ~DlOpenOatFile() {
534 if (dlopen_handle_ != nullptr) {
Richard Uhlera206c742016-05-24 15:04:22 -0700535 if (!kIsTargetBuild) {
536 MutexLock mu(Thread::Current(), *Locks::host_dlopen_handles_lock_);
537 host_dlopen_handles_.erase(dlopen_handle_);
Mathieu Chartierc7d3f4b2016-06-01 10:48:19 -0700538 dlclose(dlopen_handle_);
539 } else {
540 dlclose(dlopen_handle_);
Richard Uhlera206c742016-05-24 15:04:22 -0700541 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800542 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800543 }
544
545 protected:
546 const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
547 std::string* error_msg) const OVERRIDE {
548 const uint8_t* ptr =
549 reinterpret_cast<const uint8_t*>(dlsym(dlopen_handle_, symbol_name.c_str()));
550 if (ptr == nullptr) {
551 *error_msg = dlerror();
552 }
553 return ptr;
554 }
555
Andreas Gampe4075f832016-05-18 13:09:54 -0700556 void PreLoad() OVERRIDE;
557
Andreas Gampe049cff02015-12-01 23:27:12 -0800558 bool Load(const std::string& elf_filename,
559 uint8_t* oat_file_begin,
560 bool writable,
561 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800562 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800563 std::string* error_msg) OVERRIDE;
564
565 // Ask the linker where it mmaped the file and notify our mmap wrapper of the regions.
566 void PreSetup(const std::string& elf_filename) OVERRIDE;
567
568 private:
569 bool Dlopen(const std::string& elf_filename,
570 uint8_t* oat_file_begin,
571 std::string* error_msg);
572
Richard Uhlera206c742016-05-24 15:04:22 -0700573 // On the host, if the same library is loaded again with dlopen the same
574 // file handle is returned. This differs from the behavior of dlopen on the
575 // target, where dlopen reloads the library at a different address every
576 // time you load it. The runtime relies on the target behavior to ensure
577 // each instance of the loaded library has a unique dex cache. To avoid
578 // problems, we fall back to our own linker in the case when the same
579 // library is opened multiple times on host. dlopen_handles_ is used to
580 // detect that case.
581 // Guarded by host_dlopen_handles_lock_;
582 static std::unordered_set<void*> host_dlopen_handles_;
583
Andreas Gampe049cff02015-12-01 23:27:12 -0800584 // dlopen handle during runtime.
585 void* dlopen_handle_; // TODO: Unique_ptr with custom deleter.
586
587 // Dummy memory map objects corresponding to the regions mapped by dlopen.
588 std::vector<std::unique_ptr<MemMap>> dlopen_mmaps_;
589
Andreas Gampe4075f832016-05-18 13:09:54 -0700590 // The number of shared objects the linker told us about before loading. Used to
591 // (optimistically) optimize the PreSetup stage (see comment there).
592 size_t shared_objects_before_;
593
Andreas Gampe049cff02015-12-01 23:27:12 -0800594 DISALLOW_COPY_AND_ASSIGN(DlOpenOatFile);
595};
596
Richard Uhlera206c742016-05-24 15:04:22 -0700597std::unordered_set<void*> DlOpenOatFile::host_dlopen_handles_;
598
Andreas Gampe4075f832016-05-18 13:09:54 -0700599void DlOpenOatFile::PreLoad() {
600#ifdef __APPLE__
Andreas Gampe39004a62016-05-18 21:27:00 -0700601 UNUSED(shared_objects_before_);
Andreas Gampe4075f832016-05-18 13:09:54 -0700602 LOG(FATAL) << "Should not reach here.";
603 UNREACHABLE();
604#else
605 // Count the entries in dl_iterate_phdr we get at this point in time.
606 struct dl_iterate_context {
607 static int callback(struct dl_phdr_info *info ATTRIBUTE_UNUSED,
608 size_t size ATTRIBUTE_UNUSED,
609 void *data) {
610 reinterpret_cast<dl_iterate_context*>(data)->count++;
611 return 0; // Continue iteration.
612 }
613 size_t count = 0;
614 } context;
615
616 dl_iterate_phdr(dl_iterate_context::callback, &context);
617 shared_objects_before_ = context.count;
618#endif
619}
620
Andreas Gampe049cff02015-12-01 23:27:12 -0800621bool DlOpenOatFile::Load(const std::string& elf_filename,
622 uint8_t* oat_file_begin,
623 bool writable,
624 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800625 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800626 std::string* error_msg) {
627 // Use dlopen only when flagged to do so, and when it's OK to load things executable.
628 // TODO: Also try when not executable? The issue here could be re-mapping as writable (as
629 // !executable is a sign that we may want to patch), which may not be allowed for
630 // various reasons.
631 if (!kUseDlopen) {
632 *error_msg = "DlOpen is disabled.";
633 return false;
634 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800635 if (low_4gb) {
636 *error_msg = "DlOpen does not support low 4gb loading.";
637 return false;
638 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800639 if (writable) {
640 *error_msg = "DlOpen does not support writable loading.";
641 return false;
642 }
643 if (!executable) {
644 *error_msg = "DlOpen does not support non-executable loading.";
645 return false;
646 }
647
648 // dlopen always returns the same library if it is already opened on the host. For this reason
649 // we only use dlopen if we are the target or we do not already have the dex file opened. Having
650 // the same library loaded multiple times at different addresses is required for class unloading
651 // and for having dex caches arrays in the .bss section.
652 if (!kIsTargetBuild) {
653 if (!kUseDlopenOnHost) {
654 *error_msg = "DlOpen disabled for host.";
655 return false;
656 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800657 }
658
659 bool success = Dlopen(elf_filename, oat_file_begin, error_msg);
660 DCHECK(dlopen_handle_ != nullptr || !success);
661
662 return success;
663}
664
665bool DlOpenOatFile::Dlopen(const std::string& elf_filename,
666 uint8_t* oat_file_begin,
667 std::string* error_msg) {
668#ifdef __APPLE__
669 // The dl_iterate_phdr syscall is missing. There is similar API on OSX,
670 // but let's fallback to the custom loading code for the time being.
671 UNUSED(elf_filename, oat_file_begin);
672 *error_msg = "Dlopen unsupported on Mac.";
673 return false;
674#else
675 {
676 UniqueCPtr<char> absolute_path(realpath(elf_filename.c_str(), nullptr));
677 if (absolute_path == nullptr) {
678 *error_msg = StringPrintf("Failed to find absolute path for '%s'", elf_filename.c_str());
679 return false;
680 }
Bilyan Borisovbb661c02016-04-04 16:27:32 +0100681#ifdef ART_TARGET_ANDROID
Andreas Gampe049cff02015-12-01 23:27:12 -0800682 android_dlextinfo extinfo;
683 extinfo.flags = ANDROID_DLEXT_FORCE_LOAD | // Force-load, don't reuse handle
684 // (open oat files multiple
685 // times).
686 ANDROID_DLEXT_FORCE_FIXED_VADDR; // Take a non-zero vaddr as absolute
687 // (non-pic boot image).
Andreas Gampe226b91e2015-12-02 10:29:33 -0800688 if (oat_file_begin != nullptr) { //
689 extinfo.flags |= ANDROID_DLEXT_LOAD_AT_FIXED_ADDRESS; // Use the requested addr if
690 extinfo.reserved_addr = oat_file_begin; // vaddr = 0.
691 } // (pic boot image).
Andreas Gampe049cff02015-12-01 23:27:12 -0800692 dlopen_handle_ = android_dlopen_ext(absolute_path.get(), RTLD_NOW, &extinfo);
693#else
Andreas Gampe049cff02015-12-01 23:27:12 -0800694 UNUSED(oat_file_begin);
Richard Uhlera206c742016-05-24 15:04:22 -0700695 static_assert(!kIsTargetBuild, "host_dlopen_handles_ will leak handles");
Mathieu Chartierc7d3f4b2016-06-01 10:48:19 -0700696 MutexLock mu(Thread::Current(), *Locks::host_dlopen_handles_lock_);
Richard Uhlera206c742016-05-24 15:04:22 -0700697 dlopen_handle_ = dlopen(absolute_path.get(), RTLD_NOW);
698 if (dlopen_handle_ != nullptr) {
Richard Uhlera206c742016-05-24 15:04:22 -0700699 if (!host_dlopen_handles_.insert(dlopen_handle_).second) {
700 dlclose(dlopen_handle_);
701 dlopen_handle_ = nullptr;
702 *error_msg = StringPrintf("host dlopen re-opened '%s'", elf_filename.c_str());
703 return false;
704 }
705 }
Bilyan Borisovbb661c02016-04-04 16:27:32 +0100706#endif // ART_TARGET_ANDROID
Andreas Gampe049cff02015-12-01 23:27:12 -0800707 }
708 if (dlopen_handle_ == nullptr) {
709 *error_msg = StringPrintf("Failed to dlopen '%s': %s", elf_filename.c_str(), dlerror());
710 return false;
711 }
712 return true;
713#endif
714}
715
716void DlOpenOatFile::PreSetup(const std::string& elf_filename) {
Andreas Gampe74f07b52015-12-02 11:53:26 -0800717#ifdef __APPLE__
718 UNUSED(elf_filename);
719 LOG(FATAL) << "Should not reach here.";
720 UNREACHABLE();
721#else
Andreas Gampe049cff02015-12-01 23:27:12 -0800722 struct dl_iterate_context {
723 static int callback(struct dl_phdr_info *info, size_t /* size */, void *data) {
724 auto* context = reinterpret_cast<dl_iterate_context*>(data);
Andreas Gampe4075f832016-05-18 13:09:54 -0700725 context->shared_objects_seen++;
726 if (context->shared_objects_seen < context->shared_objects_before) {
727 // We haven't been called yet for anything we haven't seen before. Just continue.
728 // Note: this is aggressively optimistic. If another thread was unloading a library,
729 // we may miss out here. However, this does not happen often in practice.
730 return 0;
731 }
732
Andreas Gampe049cff02015-12-01 23:27:12 -0800733 // See whether this callback corresponds to the file which we have just loaded.
734 bool contains_begin = false;
735 for (int i = 0; i < info->dlpi_phnum; i++) {
736 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
737 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
738 info->dlpi_phdr[i].p_vaddr);
739 size_t memsz = info->dlpi_phdr[i].p_memsz;
740 if (vaddr <= context->begin_ && context->begin_ < vaddr + memsz) {
741 contains_begin = true;
742 break;
743 }
744 }
745 }
746 // Add dummy mmaps for this file.
747 if (contains_begin) {
748 for (int i = 0; i < info->dlpi_phnum; i++) {
749 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
750 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
751 info->dlpi_phdr[i].p_vaddr);
752 size_t memsz = info->dlpi_phdr[i].p_memsz;
753 MemMap* mmap = MemMap::MapDummy(info->dlpi_name, vaddr, memsz);
754 context->dlopen_mmaps_->push_back(std::unique_ptr<MemMap>(mmap));
755 }
756 }
757 return 1; // Stop iteration and return 1 from dl_iterate_phdr.
758 }
759 return 0; // Continue iteration and return 0 from dl_iterate_phdr when finished.
760 }
761 const uint8_t* const begin_;
762 std::vector<std::unique_ptr<MemMap>>* const dlopen_mmaps_;
Andreas Gampe4075f832016-05-18 13:09:54 -0700763 const size_t shared_objects_before;
764 size_t shared_objects_seen;
765 };
766 dl_iterate_context context = { Begin(), &dlopen_mmaps_, shared_objects_before_, 0};
Andreas Gampe049cff02015-12-01 23:27:12 -0800767
768 if (dl_iterate_phdr(dl_iterate_context::callback, &context) == 0) {
Andreas Gampe4075f832016-05-18 13:09:54 -0700769 // Hm. Maybe our optimization went wrong. Try another time with shared_objects_before == 0
770 // before giving up. This should be unusual.
771 VLOG(oat) << "Need a second run in PreSetup, didn't find with shared_objects_before="
772 << shared_objects_before_;
773 dl_iterate_context context0 = { Begin(), &dlopen_mmaps_, 0, 0};
774 if (dl_iterate_phdr(dl_iterate_context::callback, &context0) == 0) {
775 // OK, give up and print an error.
776 PrintFileToLog("/proc/self/maps", LogSeverity::WARNING);
777 LOG(ERROR) << "File " << elf_filename << " loaded with dlopen but cannot find its mmaps.";
778 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800779 }
Andreas Gampe74f07b52015-12-02 11:53:26 -0800780#endif
Andreas Gampe049cff02015-12-01 23:27:12 -0800781}
782
783////////////////////////////////////////////////
784// OatFile via our own ElfFile implementation //
785////////////////////////////////////////////////
786
787class ElfOatFile FINAL : public OatFileBase {
788 public:
789 ElfOatFile(const std::string& filename, bool executable) : OatFileBase(filename, executable) {}
790
791 static ElfOatFile* OpenElfFile(File* file,
792 const std::string& location,
793 uint8_t* requested_base,
794 uint8_t* oat_file_begin, // Override base if not null
795 bool writable,
796 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800797 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800798 const char* abs_dex_location,
799 std::string* error_msg);
800
801 bool InitializeFromElfFile(ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +0100802 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -0800803 const char* abs_dex_location,
804 std::string* error_msg);
805
806 protected:
807 const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
808 std::string* error_msg) const OVERRIDE {
809 const uint8_t* ptr = elf_file_->FindDynamicSymbolAddress(symbol_name);
810 if (ptr == nullptr) {
811 *error_msg = "(Internal implementation could not find symbol)";
812 }
813 return ptr;
814 }
815
Andreas Gampe4075f832016-05-18 13:09:54 -0700816 void PreLoad() OVERRIDE {
817 }
818
Andreas Gampe049cff02015-12-01 23:27:12 -0800819 bool Load(const std::string& elf_filename,
820 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
821 bool writable,
822 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800823 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800824 std::string* error_msg) OVERRIDE;
825
826 void PreSetup(const std::string& elf_filename ATTRIBUTE_UNUSED) OVERRIDE {
827 }
828
829 private:
830 bool ElfFileOpen(File* file,
831 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
832 bool writable,
833 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800834 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800835 std::string* error_msg);
836
837 private:
838 // Backing memory map for oat file during cross compilation.
839 std::unique_ptr<ElfFile> elf_file_;
840
841 DISALLOW_COPY_AND_ASSIGN(ElfOatFile);
842};
843
844ElfOatFile* ElfOatFile::OpenElfFile(File* file,
845 const std::string& location,
846 uint8_t* requested_base,
847 uint8_t* oat_file_begin, // Override base if not null
848 bool writable,
849 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800850 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800851 const char* abs_dex_location,
852 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800853 ScopedTrace trace("Open elf file " + location);
Andreas Gampe049cff02015-12-01 23:27:12 -0800854 std::unique_ptr<ElfOatFile> oat_file(new ElfOatFile(location, executable));
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800855 bool success = oat_file->ElfFileOpen(file,
856 oat_file_begin,
857 writable,
858 low_4gb,
859 executable,
860 error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -0800861 if (!success) {
862 CHECK(!error_msg->empty());
863 return nullptr;
864 }
865
866 // Complete the setup.
867 if (!oat_file->ComputeFields(requested_base, file->GetPath(), error_msg)) {
868 return nullptr;
869 }
870
871 if (!oat_file->Setup(abs_dex_location, error_msg)) {
872 return nullptr;
873 }
874
875 return oat_file.release();
876}
877
878bool ElfOatFile::InitializeFromElfFile(ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +0100879 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -0800880 const char* abs_dex_location,
881 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800882 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -0800883 if (IsExecutable()) {
884 *error_msg = "Cannot initialize from elf file in executable mode.";
885 return false;
886 }
887 elf_file_.reset(elf_file);
David Brazdilc93b3be2016-09-12 18:49:58 +0100888 SetVdex(vdex_file);
Andreas Gampe049cff02015-12-01 23:27:12 -0800889 uint64_t offset, size;
890 bool has_section = elf_file->GetSectionOffsetAndSize(".rodata", &offset, &size);
891 CHECK(has_section);
892 SetBegin(elf_file->Begin() + offset);
893 SetEnd(elf_file->Begin() + size + offset);
894 // Ignore the optional .bss section when opening non-executable.
895 return Setup(abs_dex_location, error_msg);
896}
897
898bool ElfOatFile::Load(const std::string& elf_filename,
899 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
900 bool writable,
901 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800902 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800903 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800904 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -0800905 std::unique_ptr<File> file(OS::OpenFileForReading(elf_filename.c_str()));
906 if (file == nullptr) {
907 *error_msg = StringPrintf("Failed to open oat filename for reading: %s", strerror(errno));
908 return false;
909 }
910 return ElfOatFile::ElfFileOpen(file.get(),
911 oat_file_begin,
912 writable,
913 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800914 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800915 error_msg);
916}
917
918bool ElfOatFile::ElfFileOpen(File* file,
919 uint8_t* oat_file_begin,
920 bool writable,
921 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800922 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800923 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800924 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -0800925 // TODO: rename requested_base to oat_data_begin
926 elf_file_.reset(ElfFile::Open(file,
927 writable,
928 /*program_header_only*/true,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800929 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800930 error_msg,
931 oat_file_begin));
932 if (elf_file_ == nullptr) {
933 DCHECK(!error_msg->empty());
934 return false;
935 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800936 bool loaded = elf_file_->Load(executable, low_4gb, error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -0800937 DCHECK(loaded || !error_msg->empty());
938 return loaded;
939}
940
941//////////////////////////
942// General OatFile code //
943//////////////////////////
944
945std::string OatFile::ResolveRelativeEncodedDexLocation(
946 const char* abs_dex_location, const std::string& rel_dex_location) {
947 if (abs_dex_location != nullptr && rel_dex_location[0] != '/') {
948 // Strip :classes<N>.dex used for secondary multidex files.
949 std::string base = DexFile::GetBaseLocation(rel_dex_location);
950 std::string multidex_suffix = DexFile::GetMultiDexSuffix(rel_dex_location);
951
952 // Check if the base is a suffix of the provided abs_dex_location.
953 std::string target_suffix = "/" + base;
954 std::string abs_location(abs_dex_location);
955 if (abs_location.size() > target_suffix.size()) {
956 size_t pos = abs_location.size() - target_suffix.size();
957 if (abs_location.compare(pos, std::string::npos, target_suffix) == 0) {
958 return abs_location + multidex_suffix;
959 }
960 }
961 }
962 return rel_dex_location;
963}
964
965static void CheckLocation(const std::string& location) {
966 CHECK(!location.empty());
967}
968
969OatFile* OatFile::OpenWithElfFile(ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +0100970 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -0800971 const std::string& location,
972 const char* abs_dex_location,
973 std::string* error_msg) {
974 std::unique_ptr<ElfOatFile> oat_file(new ElfOatFile(location, false /* executable */));
David Brazdilc93b3be2016-09-12 18:49:58 +0100975 return oat_file->InitializeFromElfFile(elf_file, vdex_file, abs_dex_location, error_msg)
Andreas Gampe049cff02015-12-01 23:27:12 -0800976 ? oat_file.release()
977 : nullptr;
978}
979
David Brazdil7b49e6c2016-09-01 11:06:18 +0100980OatFile* OatFile::Open(const std::string& oat_filename,
981 const std::string& oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -0800982 uint8_t* requested_base,
983 uint8_t* oat_file_begin,
984 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800985 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800986 const char* abs_dex_location,
987 std::string* error_msg) {
David Brazdil7b49e6c2016-09-01 11:06:18 +0100988 ScopedTrace trace("Open oat file " + oat_location);
989 CHECK(!oat_filename.empty()) << oat_location;
990 CheckLocation(oat_location);
Andreas Gampe54315c72016-05-18 21:10:42 -0700991
David Brazdil7b49e6c2016-09-01 11:06:18 +0100992 std::string vdex_filename = ReplaceFileExtension(oat_filename, "vdex");
993
994 // Check that the files even exist, fast-fail.
995 if (kIsVdexEnabled && !OS::FileExists(vdex_filename.c_str())) {
996 *error_msg = StringPrintf("File %s does not exist.", vdex_filename.c_str());
997 return nullptr;
998 } else if (!OS::FileExists(oat_filename.c_str())) {
999 *error_msg = StringPrintf("File %s does not exist.", oat_filename.c_str());
Andreas Gampe54315c72016-05-18 21:10:42 -07001000 return nullptr;
1001 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001002
1003 // Try dlopen first, as it is required for native debuggability. This will fail fast if dlopen is
1004 // disabled.
David Brazdil7b49e6c2016-09-01 11:06:18 +01001005 OatFile* with_dlopen = OatFileBase::OpenOatFile<DlOpenOatFile>(vdex_filename,
1006 oat_filename,
1007 oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001008 requested_base,
1009 oat_file_begin,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001010 false /* writable */,
Andreas Gampe049cff02015-12-01 23:27:12 -08001011 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001012 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001013 abs_dex_location,
1014 error_msg);
1015 if (with_dlopen != nullptr) {
1016 return with_dlopen;
1017 }
1018 if (kPrintDlOpenErrorMessage) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001019 LOG(ERROR) << "Failed to dlopen: " << oat_filename << " with error " << *error_msg;
Andreas Gampe049cff02015-12-01 23:27:12 -08001020 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001021 // If we aren't trying to execute, we just use our own ElfFile loader for a couple reasons:
1022 //
1023 // On target, dlopen may fail when compiling due to selinux restrictions on installd.
1024 //
1025 // We use our own ELF loader for Quick to deal with legacy apps that
1026 // open a generated dex file by name, remove the file, then open
1027 // another generated dex file with the same name. http://b/10614658
1028 //
1029 // On host, dlopen is expected to fail when cross compiling, so fall back to OpenElfFile.
1030 //
1031 //
1032 // Another independent reason is the absolute placement of boot.oat. dlopen on the host usually
1033 // 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 +01001034 OatFile* with_internal = OatFileBase::OpenOatFile<ElfOatFile>(vdex_filename,
1035 oat_filename,
1036 oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001037 requested_base,
1038 oat_file_begin,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001039 false /* writable */,
Andreas Gampe049cff02015-12-01 23:27:12 -08001040 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001041 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001042 abs_dex_location,
1043 error_msg);
1044 return with_internal;
1045}
1046
1047OatFile* OatFile::OpenWritable(File* file,
1048 const std::string& location,
1049 const char* abs_dex_location,
1050 std::string* error_msg) {
1051 CheckLocation(location);
1052 return ElfOatFile::OpenElfFile(file,
1053 location,
1054 nullptr,
1055 nullptr,
1056 true,
1057 false,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001058 /*low_4gb*/false,
Andreas Gampe049cff02015-12-01 23:27:12 -08001059 abs_dex_location,
1060 error_msg);
1061}
1062
1063OatFile* OatFile::OpenReadable(File* file,
1064 const std::string& location,
1065 const char* abs_dex_location,
1066 std::string* error_msg) {
1067 CheckLocation(location);
1068 return ElfOatFile::OpenElfFile(file,
1069 location,
1070 nullptr,
1071 nullptr,
1072 false,
1073 false,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001074 /*low_4gb*/false,
Andreas Gampe049cff02015-12-01 23:27:12 -08001075 abs_dex_location,
1076 error_msg);
1077}
1078
1079OatFile::OatFile(const std::string& location, bool is_executable)
1080 : location_(location),
David Brazdil7b49e6c2016-09-01 11:06:18 +01001081 vdex_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001082 begin_(nullptr),
1083 end_(nullptr),
1084 bss_begin_(nullptr),
1085 bss_end_(nullptr),
1086 is_executable_(is_executable),
1087 secondary_lookup_lock_("OatFile secondary lookup lock", kOatFileSecondaryLookupLock) {
1088 CHECK(!location_.empty());
1089}
1090
1091OatFile::~OatFile() {
1092 STLDeleteElements(&oat_dex_files_storage_);
1093}
1094
Brian Carlstrome24fa612011-09-29 00:53:55 -07001095const OatHeader& OatFile::GetOatHeader() const {
Ian Rogers30fab402012-01-23 15:43:46 -08001096 return *reinterpret_cast<const OatHeader*>(Begin());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001097}
1098
Ian Rogers13735952014-10-08 12:43:28 -07001099const uint8_t* OatFile::Begin() const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001100 CHECK(begin_ != nullptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001101 return begin_;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001102}
1103
Ian Rogers13735952014-10-08 12:43:28 -07001104const uint8_t* OatFile::End() const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001105 CHECK(end_ != nullptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001106 return end_;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001107}
1108
Vladimir Marko5c42c292015-02-25 12:02:49 +00001109const uint8_t* OatFile::BssBegin() const {
1110 return bss_begin_;
1111}
1112
1113const uint8_t* OatFile::BssEnd() const {
1114 return bss_end_;
1115}
1116
David Brazdil7b49e6c2016-09-01 11:06:18 +01001117const uint8_t* OatFile::DexBegin() const {
1118 return kIsVdexEnabled ? vdex_->Begin() : Begin();
1119}
1120
1121const uint8_t* OatFile::DexEnd() const {
1122 return kIsVdexEnabled ? vdex_->End() : End();
1123}
1124
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001125const OatFile::OatDexFile* OatFile::GetOatDexFile(const char* dex_location,
1126 const uint32_t* dex_location_checksum,
Richard Uhler9a37efc2016-08-05 16:32:55 -07001127 std::string* error_msg) const {
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001128 // NOTE: We assume here that the canonical location for a given dex_location never
1129 // changes. If it does (i.e. some symlink used by the filename changes) we may return
1130 // an incorrect OatDexFile. As long as we have a checksum to check, we shall return
1131 // an identical file or fail; otherwise we may see some unpredictable failures.
Calin Juravle4e1d5792014-07-15 23:56:47 +01001132
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001133 // TODO: Additional analysis of usage patterns to see if this can be simplified
1134 // without any performance loss, for example by not doing the first lock-free lookup.
1135
1136 const OatFile::OatDexFile* oat_dex_file = nullptr;
1137 StringPiece key(dex_location);
1138 // Try to find the key cheaply in the oat_dex_files_ map which holds dex locations
1139 // directly mentioned in the oat file and doesn't require locking.
1140 auto primary_it = oat_dex_files_.find(key);
1141 if (primary_it != oat_dex_files_.end()) {
1142 oat_dex_file = primary_it->second;
1143 DCHECK(oat_dex_file != nullptr);
1144 } else {
1145 // This dex_location is not one of the dex locations directly mentioned in the
1146 // oat file. The correct lookup is via the canonical location but first see in
1147 // the secondary_oat_dex_files_ whether we've looked up this location before.
1148 MutexLock mu(Thread::Current(), secondary_lookup_lock_);
1149 auto secondary_lb = secondary_oat_dex_files_.lower_bound(key);
1150 if (secondary_lb != secondary_oat_dex_files_.end() && key == secondary_lb->first) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001151 oat_dex_file = secondary_lb->second; // May be null.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001152 } else {
1153 // We haven't seen this dex_location before, we must check the canonical location.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001154 std::string dex_canonical_location = DexFile::GetDexCanonicalLocation(dex_location);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001155 if (dex_canonical_location != dex_location) {
1156 StringPiece canonical_key(dex_canonical_location);
1157 auto canonical_it = oat_dex_files_.find(canonical_key);
1158 if (canonical_it != oat_dex_files_.end()) {
1159 oat_dex_file = canonical_it->second;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001160 } // else keep null.
1161 } // else keep null.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001162
1163 // Copy the key to the string_cache_ and store the result in secondary map.
1164 string_cache_.emplace_back(key.data(), key.length());
1165 StringPiece key_copy(string_cache_.back());
1166 secondary_oat_dex_files_.PutBefore(secondary_lb, key_copy, oat_dex_file);
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001167 }
1168 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001169
1170 if (oat_dex_file == nullptr) {
1171 if (error_msg != nullptr) {
1172 std::string dex_canonical_location = DexFile::GetDexCanonicalLocation(dex_location);
1173 *error_msg = "Failed to find OatDexFile for DexFile " + std::string(dex_location)
1174 + " (canonical path " + dex_canonical_location + ") in OatFile " + GetLocation();
1175 }
1176 return nullptr;
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001177 }
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001178
Richard Uhler9a37efc2016-08-05 16:32:55 -07001179 if (dex_location_checksum != nullptr &&
1180 oat_dex_file->GetDexFileLocationChecksum() != *dex_location_checksum) {
1181 if (error_msg != nullptr) {
1182 std::string dex_canonical_location = DexFile::GetDexCanonicalLocation(dex_location);
1183 std::string checksum = StringPrintf("0x%08x", oat_dex_file->GetDexFileLocationChecksum());
1184 std::string required_checksum = StringPrintf("0x%08x", *dex_location_checksum);
1185 *error_msg = "OatDexFile for DexFile " + std::string(dex_location)
1186 + " (canonical path " + dex_canonical_location + ") in OatFile " + GetLocation()
1187 + " has checksum " + checksum + " but " + required_checksum + " was required";
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001188 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001189 return nullptr;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001190 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001191 return oat_dex_file;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001192}
1193
Brian Carlstrome24fa612011-09-29 00:53:55 -07001194OatFile::OatDexFile::OatDexFile(const OatFile* oat_file,
Elliott Hughesaa6a5882012-01-13 19:39:16 -08001195 const std::string& dex_file_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001196 const std::string& canonical_dex_file_location,
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001197 uint32_t dex_file_location_checksum,
Ian Rogers13735952014-10-08 12:43:28 -07001198 const uint8_t* dex_file_pointer,
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001199 const uint8_t* lookup_table_data,
Vladimir Marko09d09432015-09-08 13:47:48 +01001200 const uint32_t* oat_class_offsets_pointer,
Vladimir Marko06d7aaa2015-10-16 11:23:41 +01001201 uint8_t* dex_cache_arrays)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001202 : oat_file_(oat_file),
1203 dex_file_location_(dex_file_location),
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001204 canonical_dex_file_location_(canonical_dex_file_location),
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001205 dex_file_location_checksum_(dex_file_location_checksum),
Brian Carlstrom89521892011-12-07 22:05:07 -08001206 dex_file_pointer_(dex_file_pointer),
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001207 lookup_table_data_(lookup_table_data),
Vladimir Marko09d09432015-09-08 13:47:48 +01001208 oat_class_offsets_pointer_(oat_class_offsets_pointer),
David Sehr9aa352e2016-09-15 18:13:52 -07001209 dex_cache_arrays_(dex_cache_arrays) {
1210 // Initialize TypeLookupTable.
1211 if (lookup_table_data_ != nullptr) {
1212 // Peek the number of classes from the DexFile.
1213 const DexFile::Header* dex_header = reinterpret_cast<const DexFile::Header*>(dex_file_pointer_);
1214 const uint32_t num_class_defs = dex_header->class_defs_size_;
1215 if (lookup_table_data_ + TypeLookupTable::RawDataLength(num_class_defs) > GetOatFile()->End()) {
1216 LOG(WARNING) << "found truncated lookup table in " << dex_file_location_;
1217 } else {
1218 lookup_table_.reset(TypeLookupTable::Open(dex_file_pointer_,
1219 lookup_table_data_,
1220 num_class_defs));
1221 }
1222 }
1223}
Brian Carlstrome24fa612011-09-29 00:53:55 -07001224
1225OatFile::OatDexFile::~OatDexFile() {}
1226
Ian Rogers05f28c62012-10-23 18:12:13 -07001227size_t OatFile::OatDexFile::FileSize() const {
1228 return reinterpret_cast<const DexFile::Header*>(dex_file_pointer_)->file_size_;
1229}
1230
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001231std::unique_ptr<const DexFile> OatFile::OatDexFile::OpenDexFile(std::string* error_msg) const {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001232 ScopedTrace trace(__PRETTY_FUNCTION__);
Aart Bik37d6a3b2016-06-21 18:30:10 -07001233 static constexpr bool kVerify = false;
1234 static constexpr bool kVerifyChecksum = false;
Andreas Gampe3a2bd292016-01-26 17:23:47 -08001235 return DexFile::Open(dex_file_pointer_,
1236 FileSize(),
1237 dex_file_location_,
1238 dex_file_location_checksum_,
1239 this,
Aart Bik37d6a3b2016-06-21 18:30:10 -07001240 kVerify,
1241 kVerifyChecksum,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08001242 error_msg);
Brian Carlstrom89521892011-12-07 22:05:07 -08001243}
1244
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001245uint32_t OatFile::OatDexFile::GetOatClassOffset(uint16_t class_def_index) const {
1246 return oat_class_offsets_pointer_[class_def_index];
1247}
1248
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001249OatFile::OatClass OatFile::OatDexFile::GetOatClass(uint16_t class_def_index) const {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001250 uint32_t oat_class_offset = GetOatClassOffset(class_def_index);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001251
Ian Rogers13735952014-10-08 12:43:28 -07001252 const uint8_t* oat_class_pointer = oat_file_->Begin() + oat_class_offset;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001253 CHECK_LT(oat_class_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001254
Ian Rogers13735952014-10-08 12:43:28 -07001255 const uint8_t* status_pointer = oat_class_pointer;
Brian Carlstromba150c32013-08-27 17:31:03 -07001256 CHECK_LT(status_pointer, oat_file_->End()) << oat_file_->GetLocation();
1257 mirror::Class::Status status =
1258 static_cast<mirror::Class::Status>(*reinterpret_cast<const int16_t*>(status_pointer));
1259 CHECK_LT(status, mirror::Class::kStatusMax);
1260
Ian Rogers13735952014-10-08 12:43:28 -07001261 const uint8_t* type_pointer = status_pointer + sizeof(uint16_t);
Brian Carlstromba150c32013-08-27 17:31:03 -07001262 CHECK_LT(type_pointer, oat_file_->End()) << oat_file_->GetLocation();
1263 OatClassType type = static_cast<OatClassType>(*reinterpret_cast<const uint16_t*>(type_pointer));
1264 CHECK_LT(type, kOatClassMax);
1265
Ian Rogers13735952014-10-08 12:43:28 -07001266 const uint8_t* after_type_pointer = type_pointer + sizeof(int16_t);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001267 CHECK_LE(after_type_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07001268
Brian Carlstromcd937a92014-03-04 22:53:23 -08001269 uint32_t bitmap_size = 0;
Ian Rogers13735952014-10-08 12:43:28 -07001270 const uint8_t* bitmap_pointer = nullptr;
1271 const uint8_t* methods_pointer = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07001272 if (type != kOatClassNoneCompiled) {
1273 if (type == kOatClassSomeCompiled) {
1274 bitmap_size = static_cast<uint32_t>(*reinterpret_cast<const uint32_t*>(after_type_pointer));
1275 bitmap_pointer = after_type_pointer + sizeof(bitmap_size);
1276 CHECK_LE(bitmap_pointer, oat_file_->End()) << oat_file_->GetLocation();
1277 methods_pointer = bitmap_pointer + bitmap_size;
1278 } else {
1279 methods_pointer = after_type_pointer;
1280 }
1281 CHECK_LE(methods_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstromcd937a92014-03-04 22:53:23 -08001282 }
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001283
Richard Uhler07b3c232015-03-31 15:57:54 -07001284 return OatFile::OatClass(oat_file_,
1285 status,
1286 type,
1287 bitmap_size,
1288 reinterpret_cast<const uint32_t*>(bitmap_pointer),
1289 reinterpret_cast<const OatMethodOffsets*>(methods_pointer));
Brian Carlstrome24fa612011-09-29 00:53:55 -07001290}
1291
David Sehr9aa352e2016-09-15 18:13:52 -07001292const DexFile::ClassDef* OatFile::OatDexFile::FindClassDef(const DexFile& dex_file,
1293 const char* descriptor,
1294 size_t hash) {
1295 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1296 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
1297 if (LIKELY((oat_dex_file != nullptr) && (oat_dex_file->GetTypeLookupTable() != nullptr))) {
1298 const uint32_t class_def_idx = oat_dex_file->GetTypeLookupTable()->Lookup(descriptor, hash);
1299 return (class_def_idx != DexFile::kDexNoIndex) ? &dex_file.GetClassDef(class_def_idx) : nullptr;
1300 }
1301 // Fast path for rare no class defs case.
1302 const uint32_t num_class_defs = dex_file.NumClassDefs();
1303 if (num_class_defs == 0) {
1304 return nullptr;
1305 }
1306 const DexFile::TypeId* type_id = dex_file.FindTypeId(descriptor);
1307 if (type_id != nullptr) {
1308 uint16_t type_idx = dex_file.GetIndexForTypeId(*type_id);
1309 return dex_file.FindClassDef(type_idx);
1310 }
1311 return nullptr;
1312}
1313
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001314OatFile::OatClass::OatClass(const OatFile* oat_file,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001315 mirror::Class::Status status,
Brian Carlstromba150c32013-08-27 17:31:03 -07001316 OatClassType type,
1317 uint32_t bitmap_size,
1318 const uint32_t* bitmap_pointer,
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001319 const OatMethodOffsets* methods_pointer)
Brian Carlstromba150c32013-08-27 17:31:03 -07001320 : oat_file_(oat_file), status_(status), type_(type),
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001321 bitmap_(bitmap_pointer), methods_pointer_(methods_pointer) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001322 switch (type_) {
1323 case kOatClassAllCompiled: {
1324 CHECK_EQ(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001325 CHECK(bitmap_pointer == nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001326 CHECK(methods_pointer != nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001327 break;
1328 }
1329 case kOatClassSomeCompiled: {
1330 CHECK_NE(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001331 CHECK(bitmap_pointer != nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001332 CHECK(methods_pointer != nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001333 break;
1334 }
1335 case kOatClassNoneCompiled: {
1336 CHECK_EQ(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001337 CHECK(bitmap_pointer == nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001338 CHECK(methods_pointer_ == nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001339 break;
1340 }
1341 case kOatClassMax: {
1342 LOG(FATAL) << "Invalid OatClassType " << type_;
1343 break;
1344 }
1345 }
1346}
Brian Carlstrome24fa612011-09-29 00:53:55 -07001347
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001348uint32_t OatFile::OatClass::GetOatMethodOffsetsOffset(uint32_t method_index) const {
1349 const OatMethodOffsets* oat_method_offsets = GetOatMethodOffsets(method_index);
1350 if (oat_method_offsets == nullptr) {
1351 return 0u;
1352 }
1353 return reinterpret_cast<const uint8_t*>(oat_method_offsets) - oat_file_->Begin();
1354}
1355
1356const OatMethodOffsets* OatFile::OatClass::GetOatMethodOffsets(uint32_t method_index) const {
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001357 // 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 -07001358 if (methods_pointer_ == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001359 CHECK_EQ(kOatClassNoneCompiled, type_);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001360 return nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07001361 }
1362 size_t methods_pointer_index;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001363 if (bitmap_ == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001364 CHECK_EQ(kOatClassAllCompiled, type_);
1365 methods_pointer_index = method_index;
1366 } else {
1367 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001368 if (!BitVector::IsBitSet(bitmap_, method_index)) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001369 return nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07001370 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001371 size_t num_set_bits = BitVector::NumSetBits(bitmap_, method_index);
1372 methods_pointer_index = num_set_bits;
Brian Carlstromba150c32013-08-27 17:31:03 -07001373 }
1374 const OatMethodOffsets& oat_method_offsets = methods_pointer_[methods_pointer_index];
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001375 return &oat_method_offsets;
1376}
1377
1378const OatFile::OatMethod OatFile::OatClass::GetOatMethod(uint32_t method_index) const {
1379 const OatMethodOffsets* oat_method_offsets = GetOatMethodOffsets(method_index);
1380 if (oat_method_offsets == nullptr) {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001381 return OatMethod(nullptr, 0);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001382 }
1383 if (oat_file_->IsExecutable() ||
1384 Runtime::Current() == nullptr || // This case applies for oatdump.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001385 Runtime::Current()->IsAotCompiler()) {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001386 return OatMethod(oat_file_->Begin(), oat_method_offsets->code_offset_);
Alex Light9dcc4572014-08-14 14:16:26 -07001387 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001388 // We aren't allowed to use the compiled code. We just force it down the interpreted / jit
1389 // version.
1390 return OatMethod(oat_file_->Begin(), 0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001391}
1392
Mathieu Chartiere401d142015-04-22 13:56:20 -07001393void OatFile::OatMethod::LinkMethod(ArtMethod* method) const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001394 CHECK(method != nullptr);
Ian Rogersef7d42f2014-01-06 12:55:46 -08001395 method->SetEntryPointFromQuickCompiledCode(GetQuickCode());
Brian Carlstromae826982011-11-09 01:33:42 -08001396}
1397
Richard Uhlerd1537b52016-03-29 13:27:41 -07001398bool OatFile::HasPatchInfo() const {
1399 return GetOatHeader().HasPatchInfo();
1400}
1401
Andreas Gampe7ba64962014-10-23 11:37:40 -07001402bool OatFile::IsPic() const {
Igor Murashkin46774762014-10-22 11:37:02 -07001403 return GetOatHeader().IsPic();
Andreas Gampe7ba64962014-10-23 11:37:40 -07001404 // TODO: Check against oat_patches. b/18144996
1405}
1406
Sebastien Hertz0de11332015-05-13 12:14:05 +02001407bool OatFile::IsDebuggable() const {
1408 return GetOatHeader().IsDebuggable();
1409}
1410
Andreas Gampe29d38e72016-03-23 15:31:51 +00001411CompilerFilter::Filter OatFile::GetCompilerFilter() const {
1412 return GetOatHeader().GetCompilerFilter();
Calin Juravleb077e152016-02-18 18:47:37 +00001413}
1414
Andreas Gampe7848da42015-04-09 11:15:04 -07001415static constexpr char kDexClassPathEncodingSeparator = '*';
1416
1417std::string OatFile::EncodeDexFileDependencies(const std::vector<const DexFile*>& dex_files) {
1418 std::ostringstream out;
1419
1420 for (const DexFile* dex_file : dex_files) {
1421 out << dex_file->GetLocation().c_str();
1422 out << kDexClassPathEncodingSeparator;
1423 out << dex_file->GetLocationChecksum();
1424 out << kDexClassPathEncodingSeparator;
1425 }
1426
1427 return out.str();
1428}
1429
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001430bool OatFile::CheckStaticDexFileDependencies(const char* dex_dependencies, std::string* msg) {
Andreas Gampe7848da42015-04-09 11:15:04 -07001431 if (dex_dependencies == nullptr || dex_dependencies[0] == 0) {
1432 // No dependencies.
1433 return true;
1434 }
1435
1436 // Assumption: this is not performance-critical. So it's OK to do this with a std::string and
1437 // Split() instead of manual parsing of the combined char*.
1438 std::vector<std::string> split;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001439 Split(dex_dependencies, kDexClassPathEncodingSeparator, &split);
Andreas Gampe7848da42015-04-09 11:15:04 -07001440 if (split.size() % 2 != 0) {
1441 // Expected pairs of location and checksum.
1442 *msg = StringPrintf("Odd number of elements in dependency list %s", dex_dependencies);
1443 return false;
1444 }
1445
1446 for (auto it = split.begin(), end = split.end(); it != end; it += 2) {
1447 std::string& location = *it;
1448 std::string& checksum = *(it + 1);
1449 int64_t converted = strtoll(checksum.c_str(), nullptr, 10);
1450 if (converted == 0) {
1451 // Conversion error.
1452 *msg = StringPrintf("Conversion error for %s", checksum.c_str());
1453 return false;
1454 }
1455
1456 uint32_t dex_checksum;
1457 std::string error_msg;
1458 if (DexFile::GetChecksum(DexFile::GetDexCanonicalLocation(location.c_str()).c_str(),
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001459 &dex_checksum,
1460 &error_msg)) {
Andreas Gampe7848da42015-04-09 11:15:04 -07001461 if (converted != dex_checksum) {
1462 *msg = StringPrintf("Checksums don't match for %s: %" PRId64 " vs %u",
1463 location.c_str(), converted, dex_checksum);
1464 return false;
1465 }
1466 } else {
1467 // Problem retrieving checksum.
1468 // TODO: odex files?
1469 *msg = StringPrintf("Could not retrieve checksum for %s: %s", location.c_str(),
1470 error_msg.c_str());
1471 return false;
1472 }
1473 }
1474
1475 return true;
1476}
1477
1478bool OatFile::GetDexLocationsFromDependencies(const char* dex_dependencies,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001479 std::vector<std::string>* locations) {
1480 DCHECK(locations != nullptr);
Andreas Gampe7848da42015-04-09 11:15:04 -07001481 if (dex_dependencies == nullptr || dex_dependencies[0] == 0) {
1482 return true;
1483 }
1484
1485 // Assumption: this is not performance-critical. So it's OK to do this with a std::string and
1486 // Split() instead of manual parsing of the combined char*.
1487 std::vector<std::string> split;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001488 Split(dex_dependencies, kDexClassPathEncodingSeparator, &split);
Andreas Gampe7848da42015-04-09 11:15:04 -07001489 if (split.size() % 2 != 0) {
1490 // Expected pairs of location and checksum.
1491 return false;
1492 }
1493
1494 for (auto it = split.begin(), end = split.end(); it != end; it += 2) {
1495 locations->push_back(*it);
1496 }
1497
1498 return true;
1499}
1500
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001501OatFile::OatClass OatFile::FindOatClass(const DexFile& dex_file,
1502 uint16_t class_def_idx,
1503 bool* found) {
1504 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
1505 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1506 if (oat_dex_file == nullptr) {
1507 *found = false;
1508 return OatFile::OatClass::Invalid();
1509 }
1510 *found = true;
1511 return oat_dex_file->GetOatClass(class_def_idx);
1512}
1513
Brian Carlstrome24fa612011-09-29 00:53:55 -07001514} // namespace art