blob: 61979c7666ab9a596a241d596a1ed4234f062de8 [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"
Vladimir Markoaad75c62016-10-03 08:46:48 +000043#include "gc_root.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080044#include "oat.h"
David Srbecky1baabf02015-06-16 17:12:34 +000045#include "mem_map.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080046#include "mirror/class.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070047#include "mirror/object-inl.h"
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +010048#include "oat_file-inl.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070049#include "oat_file_manager.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070050#include "os.h"
Andreas Gampe22f8e5c2014-07-09 11:38:21 -070051#include "runtime.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000052#include "type_lookup_table.h"
David Sehr9aa352e2016-09-15 18:13:52 -070053#include "utf-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080054#include "utils.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010055#include "utils/dex_cache_arrays_layout-inl.h"
Vladimir Marko97d7e1c2016-10-04 14:44:28 +010056#include "vdex_file.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070057
58namespace art {
59
Andreas Gampe049cff02015-12-01 23:27:12 -080060// Whether OatFile::Open will try dlopen. Fallback is our own ELF loader.
David Srbecky1baabf02015-06-16 17:12:34 +000061static constexpr bool kUseDlopen = true;
Andreas Gampefa8429b2015-04-07 18:34:42 -070062
Andreas Gampe049cff02015-12-01 23:27:12 -080063// Whether OatFile::Open will try dlopen on the host. On the host we're not linking against
Andreas Gampefa8429b2015-04-07 18:34:42 -070064// bionic, so cannot take advantage of the support for changed semantics (loading the same soname
65// multiple times). However, if/when we switch the above, we likely want to switch this, too,
66// to get test coverage of the code paths.
David Srbecky1baabf02015-06-16 17:12:34 +000067static constexpr bool kUseDlopenOnHost = true;
Andreas Gampefa8429b2015-04-07 18:34:42 -070068
69// For debugging, Open will print DlOpen error message if set to true.
70static constexpr bool kPrintDlOpenErrorMessage = false;
71
Andreas Gampe049cff02015-12-01 23:27:12 -080072// Note for OatFileBase and descendents:
73//
74// These are used in OatFile::Open to try all our loaders.
75//
76// The process is simple:
77//
78// 1) Allocate an instance through the standard constructor (location, executable)
79// 2) Load() to try to open the file.
80// 3) ComputeFields() to populate the OatFile fields like begin_, using FindDynamicSymbolAddress.
81// 4) PreSetup() for any steps that should be done before the final setup.
82// 5) Setup() to complete the procedure.
Richard Uhlere5fed032015-03-18 08:21:11 -070083
Andreas Gampe049cff02015-12-01 23:27:12 -080084class OatFileBase : public OatFile {
85 public:
86 virtual ~OatFileBase() {}
Richard Uhlere5fed032015-03-18 08:21:11 -070087
Andreas Gampe049cff02015-12-01 23:27:12 -080088 template <typename kOatFileBaseSubType>
David Brazdil7b49e6c2016-09-01 11:06:18 +010089 static OatFileBase* OpenOatFile(const std::string& vdex_filename,
90 const std::string& elf_filename,
Alex Light84d76052014-08-22 17:49:35 -070091 const std::string& location,
Andreas Gampe049cff02015-12-01 23:27:12 -080092 uint8_t* requested_base,
93 uint8_t* oat_file_begin,
94 bool writable,
95 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -080096 bool low_4gb,
Richard Uhlere5fed032015-03-18 08:21:11 -070097 const char* abs_dex_location,
Andreas Gampe049cff02015-12-01 23:27:12 -080098 std::string* error_msg);
Brian Carlstrom700c8d32012-11-05 10:42:02 -080099
Andreas Gampe049cff02015-12-01 23:27:12 -0800100 protected:
101 OatFileBase(const std::string& filename, bool executable) : OatFile(filename, executable) {}
Andreas Gampefa8429b2015-04-07 18:34:42 -0700102
Andreas Gampe049cff02015-12-01 23:27:12 -0800103 virtual const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
104 std::string* error_msg) const = 0;
105
Andreas Gampe4075f832016-05-18 13:09:54 -0700106 virtual void PreLoad() = 0;
107
David Brazdil7b49e6c2016-09-01 11:06:18 +0100108 bool LoadVdex(const std::string& vdex_filename,
109 bool writable,
110 bool low_4gb,
111 std::string* error_msg);
112
Andreas Gampe049cff02015-12-01 23:27:12 -0800113 virtual bool Load(const std::string& elf_filename,
114 uint8_t* oat_file_begin,
115 bool writable,
116 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800117 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800118 std::string* error_msg) = 0;
119
120 bool ComputeFields(uint8_t* requested_base,
121 const std::string& file_path,
122 std::string* error_msg);
123
124 virtual void PreSetup(const std::string& elf_filename) = 0;
125
126 bool Setup(const char* abs_dex_location, std::string* error_msg);
127
128 // Setters exposed for ElfOatFile.
129
130 void SetBegin(const uint8_t* begin) {
131 begin_ = begin;
Andreas Gampefa8429b2015-04-07 18:34:42 -0700132 }
133
Andreas Gampe049cff02015-12-01 23:27:12 -0800134 void SetEnd(const uint8_t* end) {
135 end_ = end;
136 }
137
David Brazdilc93b3be2016-09-12 18:49:58 +0100138 void SetVdex(VdexFile* vdex) {
139 vdex_.reset(vdex);
140 }
141
Andreas Gampe049cff02015-12-01 23:27:12 -0800142 private:
143 DISALLOW_COPY_AND_ASSIGN(OatFileBase);
144};
145
146template <typename kOatFileBaseSubType>
David Brazdil7b49e6c2016-09-01 11:06:18 +0100147OatFileBase* OatFileBase::OpenOatFile(const std::string& vdex_filename,
148 const std::string& elf_filename,
Andreas Gampe049cff02015-12-01 23:27:12 -0800149 const std::string& location,
150 uint8_t* requested_base,
151 uint8_t* oat_file_begin,
152 bool writable,
153 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800154 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800155 const char* abs_dex_location,
156 std::string* error_msg) {
157 std::unique_ptr<OatFileBase> ret(new kOatFileBaseSubType(location, executable));
Andreas Gampe4075f832016-05-18 13:09:54 -0700158
159 ret->PreLoad();
160
David Brazdil7b49e6c2016-09-01 11:06:18 +0100161 if (kIsVdexEnabled && !ret->LoadVdex(vdex_filename, writable, low_4gb, error_msg)) {
162 return nullptr;
163 }
164
Andreas Gampe049cff02015-12-01 23:27:12 -0800165 if (!ret->Load(elf_filename,
166 oat_file_begin,
167 writable,
168 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800169 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800170 error_msg)) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800171 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800172 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800173
Andreas Gampe049cff02015-12-01 23:27:12 -0800174 if (!ret->ComputeFields(requested_base, elf_filename, error_msg)) {
175 return nullptr;
176 }
Andreas Gampe4075f832016-05-18 13:09:54 -0700177
Andreas Gampe049cff02015-12-01 23:27:12 -0800178 ret->PreSetup(elf_filename);
179
180 if (!ret->Setup(abs_dex_location, error_msg)) {
181 return nullptr;
182 }
183
Dave Allison69dfe512014-07-11 17:11:58 +0000184 return ret.release();
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800185}
186
David Brazdil7b49e6c2016-09-01 11:06:18 +0100187bool OatFileBase::LoadVdex(const std::string& vdex_filename,
188 bool writable,
189 bool low_4gb,
190 std::string* error_msg) {
191 vdex_.reset(VdexFile::Open(vdex_filename, writable, low_4gb, error_msg));
192 if (vdex_.get() == nullptr) {
193 *error_msg = StringPrintf("Failed to load vdex file '%s' %s",
194 vdex_filename.c_str(),
195 error_msg->c_str());
196 return false;
197 }
198 return true;
199}
200
Andreas Gampe049cff02015-12-01 23:27:12 -0800201bool OatFileBase::ComputeFields(uint8_t* requested_base,
202 const std::string& file_path,
203 std::string* error_msg) {
204 std::string symbol_error_msg;
205 begin_ = FindDynamicSymbolAddress("oatdata", &symbol_error_msg);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700206 if (begin_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800207 *error_msg = StringPrintf("Failed to find oatdata symbol in '%s' %s",
208 file_path.c_str(),
209 symbol_error_msg.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700210 return false;
211 }
212 if (requested_base != nullptr && begin_ != requested_base) {
Nicolas Geoffrayf97cf2a2016-03-09 15:36:23 +0000213 // Host can fail this check. Do not dump there to avoid polluting the output.
Andreas Gampe7ec09042016-04-01 17:20:49 -0700214 if (kIsTargetBuild && (kIsDebugBuild || VLOG_IS_ON(oat))) {
Nicolas Geoffrayf97cf2a2016-03-09 15:36:23 +0000215 PrintFileToLog("/proc/self/maps", LogSeverity::WARNING);
216 }
Andreas Gampefa8429b2015-04-07 18:34:42 -0700217 *error_msg = StringPrintf("Failed to find oatdata symbol at expected address: "
Andreas Gampe049cff02015-12-01 23:27:12 -0800218 "oatdata=%p != expected=%p. See process maps in the log.",
219 begin_, requested_base);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700220 return false;
221 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800222 end_ = FindDynamicSymbolAddress("oatlastword", &symbol_error_msg);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700223 if (end_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800224 *error_msg = StringPrintf("Failed to find oatlastword symbol in '%s' %s",
225 file_path.c_str(),
226 symbol_error_msg.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700227 return false;
228 }
229 // Readjust to be non-inclusive upper bound.
230 end_ += sizeof(uint32_t);
231
Andreas Gampe049cff02015-12-01 23:27:12 -0800232 bss_begin_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbss", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700233 if (bss_begin_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800234 // No .bss section.
Andreas Gampefa8429b2015-04-07 18:34:42 -0700235 bss_end_ = nullptr;
Andreas Gampefa8429b2015-04-07 18:34:42 -0700236 } else {
Andreas Gampe049cff02015-12-01 23:27:12 -0800237 bss_end_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbsslastword", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700238 if (bss_end_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800239 *error_msg = StringPrintf("Failed to find oatbasslastword symbol in '%s'", file_path.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700240 return false;
241 }
242 // Readjust to be non-inclusive upper bound.
243 bss_end_ += sizeof(uint32_t);
Vladimir Markoaad75c62016-10-03 08:46:48 +0000244 // Find bss roots if present.
245 bss_roots_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbssroots", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700246 }
247
Andreas Gampe049cff02015-12-01 23:27:12 -0800248 return true;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800249}
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800250
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100251// Read an unaligned entry from the OatDexFile data in OatFile and advance the read
252// position by the number of bytes read, i.e. sizeof(T).
253// Return true on success, false if the read would go beyond the end of the OatFile.
254template <typename T>
Vladimir Marko722fa982015-10-19 18:18:27 +0100255inline static bool ReadOatDexFileData(const OatFile& oat_file,
256 /*inout*/const uint8_t** oat,
257 /*out*/T* value) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100258 DCHECK(oat != nullptr);
259 DCHECK(value != nullptr);
260 DCHECK_LE(*oat, oat_file.End());
261 if (UNLIKELY(static_cast<size_t>(oat_file.End() - *oat) < sizeof(T))) {
262 return false;
263 }
264 static_assert(std::is_trivial<T>::value, "T must be a trivial type");
265 typedef __attribute__((__aligned__(1))) T unaligned_type;
266 *value = *reinterpret_cast<const unaligned_type*>(*oat);
267 *oat += sizeof(T);
268 return true;
269}
270
Andreas Gampe049cff02015-12-01 23:27:12 -0800271bool OatFileBase::Setup(const char* abs_dex_location, std::string* error_msg) {
Brian Carlstromf1b30302013-03-28 10:35:32 -0700272 if (!GetOatHeader().IsValid()) {
Andreas Gampe2bcb3b22014-12-12 15:25:14 -0800273 std::string cause = GetOatHeader().GetValidationErrorMessage();
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100274 *error_msg = StringPrintf("Invalid oat header for '%s': %s",
275 GetLocation().c_str(),
Andreas Gampe2bcb3b22014-12-12 15:25:14 -0800276 cause.c_str());
Brian Carlstromf1b30302013-03-28 10:35:32 -0700277 return false;
278 }
Ian Rogers13735952014-10-08 12:43:28 -0700279 const uint8_t* oat = Begin();
Brian Carlstrome24fa612011-09-29 00:53:55 -0700280 oat += sizeof(OatHeader);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700281 if (oat > End()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700282 *error_msg = StringPrintf("In oat file '%s' found truncated OatHeader", GetLocation().c_str());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700283 return false;
284 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700285
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700286 oat += GetOatHeader().GetKeyValueStoreSize();
Brian Carlstromfb331d72013-07-25 22:00:16 -0700287 if (oat > End()) {
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700288 *error_msg = StringPrintf("In oat file '%s' found truncated variable-size data: "
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100289 "%p + %zu + %u <= %p",
290 GetLocation().c_str(),
291 Begin(),
292 sizeof(OatHeader),
293 GetOatHeader().GetKeyValueStoreSize(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700294 End());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700295 return false;
296 }
297
Vladimir Markoaad75c62016-10-03 08:46:48 +0000298 if (!IsAligned<alignof(GcRoot<mirror::Object>)>(bss_begin_) ||
299 !IsAligned<alignof(GcRoot<mirror::Object>)>(bss_roots_) ||
300 !IsAligned<alignof(GcRoot<mirror::Object>)>(bss_end_)) {
301 *error_msg = StringPrintf("In oat file '%s' found unaligned bss symbol(s): "
302 "begin = %p, roots = %p, end = %p",
303 GetLocation().c_str(),
304 bss_begin_,
305 bss_roots_,
306 bss_end_);
307 return false;
308 }
309
310 if (bss_roots_ != nullptr && (bss_roots_ < bss_begin_ || bss_roots_ > bss_end_)) {
311 *error_msg = StringPrintf("In oat file '%s' found bss roots outside .bss: "
312 "%p is outside range [%p, %p]",
313 GetLocation().c_str(),
314 bss_roots_,
315 bss_begin_,
316 bss_end_);
317 return false;
318 }
319
Andreas Gampe542451c2016-07-26 09:02:02 -0700320 PointerSize pointer_size = GetInstructionSetPointerSize(GetOatHeader().GetInstructionSet());
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100321 uint8_t* dex_cache_arrays = bss_begin_;
Vladimir Markoaad75c62016-10-03 08:46:48 +0000322 uint8_t* dex_cache_arrays_end = (bss_roots_ != nullptr) ? bss_roots_ : bss_end_;
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100323 uint32_t dex_file_count = GetOatHeader().GetDexFileCount();
324 oat_dex_files_storage_.reserve(dex_file_count);
325 for (size_t i = 0; i < dex_file_count; i++) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100326 uint32_t dex_file_location_size;
327 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_location_size))) {
328 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu truncated after dex file "
329 "location size",
330 GetLocation().c_str(),
331 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700332 return false;
333 }
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100334 if (UNLIKELY(dex_file_location_size == 0U)) {
335 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu with empty location name",
336 GetLocation().c_str(),
337 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700338 return false;
339 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000340 if (UNLIKELY(static_cast<size_t>(End() - oat) < dex_file_location_size)) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100341 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu with truncated dex file "
342 "location",
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 const char* dex_file_location_data = reinterpret_cast<const char*>(oat);
348 oat += dex_file_location_size;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700349
Richard Uhlere5fed032015-03-18 08:21:11 -0700350 std::string dex_file_location = ResolveRelativeEncodedDexLocation(
351 abs_dex_location,
352 std::string(dex_file_location_data, dex_file_location_size));
Brian Carlstrome24fa612011-09-29 00:53:55 -0700353
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100354 uint32_t dex_file_checksum;
355 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_checksum))) {
356 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated after "
357 "dex file checksum",
358 GetLocation().c_str(),
359 i,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700360 dex_file_location.c_str());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700361 return false;
362 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700363
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100364 uint32_t dex_file_offset;
365 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_offset))) {
366 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated "
367 "after dex file offsets",
368 GetLocation().c_str(),
369 i,
370 dex_file_location.c_str());
371 return false;
372 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700373 if (UNLIKELY(dex_file_offset == 0U)) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100374 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with zero dex "
375 "file offset",
376 GetLocation().c_str(),
377 i,
378 dex_file_location.c_str());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700379 return false;
380 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100381 if (UNLIKELY(dex_file_offset > DexSize())) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100382 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
383 "offset %u > %zu",
384 GetLocation().c_str(),
385 i,
386 dex_file_location.c_str(),
387 dex_file_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100388 DexSize());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700389 return false;
390 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100391 if (UNLIKELY(DexSize() - dex_file_offset < sizeof(DexFile::Header))) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000392 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
393 "offset %u of %zu but the size of dex file header is %zu",
394 GetLocation().c_str(),
395 i,
396 dex_file_location.c_str(),
397 dex_file_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100398 DexSize(),
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000399 sizeof(DexFile::Header));
400 return false;
401 }
Brian Carlstrom89521892011-12-07 22:05:07 -0800402
David Brazdil7b49e6c2016-09-01 11:06:18 +0100403 const uint8_t* dex_file_pointer = DexBegin() + dex_file_offset;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700404 if (UNLIKELY(!DexFile::IsMagicValid(dex_file_pointer))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100405 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with invalid "
406 "dex file magic '%s'",
407 GetLocation().c_str(),
408 i,
409 dex_file_location.c_str(),
410 dex_file_pointer);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700411 return false;
412 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700413 if (UNLIKELY(!DexFile::IsVersionValid(dex_file_pointer))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100414 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with invalid "
415 "dex file version '%s'",
416 GetLocation().c_str(),
417 i,
418 dex_file_location.c_str(),
419 dex_file_pointer);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700420 return false;
421 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800422 const DexFile::Header* header = reinterpret_cast<const DexFile::Header*>(dex_file_pointer);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100423 if (DexSize() - dex_file_offset < header->file_size_) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000424 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
425 "offset %u and size %u truncated at %zu",
426 GetLocation().c_str(),
427 i,
428 dex_file_location.c_str(),
429 dex_file_offset,
430 header->file_size_,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100431 DexSize());
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000432 return false;
433 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300434
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000435 uint32_t class_offsets_offset;
436 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &class_offsets_offset))) {
437 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated "
438 "after class offsets offset",
439 GetLocation().c_str(),
440 i,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300441 dex_file_location.c_str());
442 return false;
443 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000444 if (UNLIKELY(class_offsets_offset > Size()) ||
445 UNLIKELY((Size() - class_offsets_offset) / sizeof(uint32_t) < header->class_defs_size_)) {
446 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with truncated "
447 "class offsets, offset %u of %zu, class defs %u",
448 GetLocation().c_str(),
449 i,
450 dex_file_location.c_str(),
451 class_offsets_offset,
452 Size(),
453 header->class_defs_size_);
454 return false;
455 }
456 if (UNLIKELY(!IsAligned<alignof(uint32_t)>(class_offsets_offset))) {
457 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with unaligned "
458 "class offsets, offset %u",
459 GetLocation().c_str(),
460 i,
461 dex_file_location.c_str(),
462 class_offsets_offset);
463 return false;
464 }
465 const uint32_t* class_offsets_pointer =
466 reinterpret_cast<const uint32_t*>(Begin() + class_offsets_offset);
467
468 uint32_t lookup_table_offset;
469 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &lookup_table_offset))) {
470 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zd for '%s' truncated "
471 "after lookup table offset",
472 GetLocation().c_str(),
473 i,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300474 dex_file_location.c_str());
475 return false;
476 }
477 const uint8_t* lookup_table_data = lookup_table_offset != 0u
478 ? Begin() + lookup_table_offset
479 : nullptr;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000480 if (lookup_table_offset != 0u &&
481 (UNLIKELY(lookup_table_offset > Size()) ||
482 UNLIKELY(Size() - lookup_table_offset <
483 TypeLookupTable::RawDataLength(header->class_defs_size_)))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100484 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with truncated "
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000485 "type lookup table, offset %u of %zu, class defs %u",
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100486 GetLocation().c_str(),
487 i,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000488 dex_file_location.c_str(),
489 lookup_table_offset,
490 Size(),
491 header->class_defs_size_);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700492 return false;
493 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700494
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100495 uint8_t* current_dex_cache_arrays = nullptr;
Vladimir Marko09d09432015-09-08 13:47:48 +0100496 if (dex_cache_arrays != nullptr) {
497 DexCacheArraysLayout layout(pointer_size, *header);
498 if (layout.Size() != 0u) {
Vladimir Markoaad75c62016-10-03 08:46:48 +0000499 if (static_cast<size_t>(dex_cache_arrays_end - dex_cache_arrays) < layout.Size()) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100500 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with "
501 "truncated dex cache arrays, %zu < %zu.",
502 GetLocation().c_str(),
503 i,
504 dex_file_location.c_str(),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000505 static_cast<size_t>(dex_cache_arrays_end - dex_cache_arrays),
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100506 layout.Size());
Vladimir Marko09d09432015-09-08 13:47:48 +0100507 return false;
508 }
509 current_dex_cache_arrays = dex_cache_arrays;
510 dex_cache_arrays += layout.Size();
511 }
512 }
513
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100514 std::string canonical_location = DexFile::GetDexCanonicalLocation(dex_file_location.c_str());
515
516 // Create the OatDexFile and add it to the owning container.
Vladimir Marko539690a2014-06-05 18:36:42 +0100517 OatDexFile* oat_dex_file = new OatDexFile(this,
518 dex_file_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100519 canonical_location,
Vladimir Marko539690a2014-06-05 18:36:42 +0100520 dex_file_checksum,
521 dex_file_pointer,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300522 lookup_table_data,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000523 class_offsets_pointer,
Vladimir Marko09d09432015-09-08 13:47:48 +0100524 current_dex_cache_arrays);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100525 oat_dex_files_storage_.push_back(oat_dex_file);
526
527 // Add the location and canonical location (if different) to the oat_dex_files_ table.
Vladimir Marko3f5838d2014-08-07 18:07:18 +0100528 StringPiece key(oat_dex_file->GetDexFileLocation());
Vladimir Marko539690a2014-06-05 18:36:42 +0100529 oat_dex_files_.Put(key, oat_dex_file);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100530 if (canonical_location != dex_file_location) {
531 StringPiece canonical_key(oat_dex_file->GetCanonicalDexFileLocation());
532 oat_dex_files_.Put(canonical_key, oat_dex_file);
533 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700534 }
Vladimir Marko09d09432015-09-08 13:47:48 +0100535
Vladimir Markoaad75c62016-10-03 08:46:48 +0000536 if (dex_cache_arrays != dex_cache_arrays_end) {
Vladimir Marko09d09432015-09-08 13:47:48 +0100537 // We expect the bss section to be either empty (dex_cache_arrays and bss_end_
Vladimir Markoaad75c62016-10-03 08:46:48 +0000538 // both null) or contain just the dex cache arrays and optionally some GC roots.
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100539 *error_msg = StringPrintf("In oat file '%s' found unexpected bss size bigger by %zu bytes.",
Vladimir Marko09d09432015-09-08 13:47:48 +0100540 GetLocation().c_str(),
541 static_cast<size_t>(bss_end_ - dex_cache_arrays));
542 return false;
543 }
Brian Carlstromf1b30302013-03-28 10:35:32 -0700544 return true;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700545}
546
Andreas Gampe049cff02015-12-01 23:27:12 -0800547////////////////////////
548// OatFile via dlopen //
549////////////////////////
550
Andreas Gampe049cff02015-12-01 23:27:12 -0800551class DlOpenOatFile FINAL : public OatFileBase {
552 public:
553 DlOpenOatFile(const std::string& filename, bool executable)
554 : OatFileBase(filename, executable),
555 dlopen_handle_(nullptr),
Richard Uhlera206c742016-05-24 15:04:22 -0700556 shared_objects_before_(0) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800557 }
558
559 ~DlOpenOatFile() {
560 if (dlopen_handle_ != nullptr) {
Richard Uhlera206c742016-05-24 15:04:22 -0700561 if (!kIsTargetBuild) {
562 MutexLock mu(Thread::Current(), *Locks::host_dlopen_handles_lock_);
563 host_dlopen_handles_.erase(dlopen_handle_);
Mathieu Chartierc7d3f4b2016-06-01 10:48:19 -0700564 dlclose(dlopen_handle_);
565 } else {
566 dlclose(dlopen_handle_);
Richard Uhlera206c742016-05-24 15:04:22 -0700567 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800568 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800569 }
570
571 protected:
572 const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
573 std::string* error_msg) const OVERRIDE {
574 const uint8_t* ptr =
575 reinterpret_cast<const uint8_t*>(dlsym(dlopen_handle_, symbol_name.c_str()));
576 if (ptr == nullptr) {
577 *error_msg = dlerror();
578 }
579 return ptr;
580 }
581
Andreas Gampe4075f832016-05-18 13:09:54 -0700582 void PreLoad() OVERRIDE;
583
Andreas Gampe049cff02015-12-01 23:27:12 -0800584 bool Load(const std::string& elf_filename,
585 uint8_t* oat_file_begin,
586 bool writable,
587 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800588 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800589 std::string* error_msg) OVERRIDE;
590
591 // Ask the linker where it mmaped the file and notify our mmap wrapper of the regions.
592 void PreSetup(const std::string& elf_filename) OVERRIDE;
593
594 private:
595 bool Dlopen(const std::string& elf_filename,
596 uint8_t* oat_file_begin,
597 std::string* error_msg);
598
Richard Uhlera206c742016-05-24 15:04:22 -0700599 // On the host, if the same library is loaded again with dlopen the same
600 // file handle is returned. This differs from the behavior of dlopen on the
601 // target, where dlopen reloads the library at a different address every
602 // time you load it. The runtime relies on the target behavior to ensure
603 // each instance of the loaded library has a unique dex cache. To avoid
604 // problems, we fall back to our own linker in the case when the same
605 // library is opened multiple times on host. dlopen_handles_ is used to
606 // detect that case.
607 // Guarded by host_dlopen_handles_lock_;
608 static std::unordered_set<void*> host_dlopen_handles_;
609
Andreas Gampe049cff02015-12-01 23:27:12 -0800610 // dlopen handle during runtime.
611 void* dlopen_handle_; // TODO: Unique_ptr with custom deleter.
612
613 // Dummy memory map objects corresponding to the regions mapped by dlopen.
614 std::vector<std::unique_ptr<MemMap>> dlopen_mmaps_;
615
Andreas Gampe4075f832016-05-18 13:09:54 -0700616 // The number of shared objects the linker told us about before loading. Used to
617 // (optimistically) optimize the PreSetup stage (see comment there).
618 size_t shared_objects_before_;
619
Andreas Gampe049cff02015-12-01 23:27:12 -0800620 DISALLOW_COPY_AND_ASSIGN(DlOpenOatFile);
621};
622
Richard Uhlera206c742016-05-24 15:04:22 -0700623std::unordered_set<void*> DlOpenOatFile::host_dlopen_handles_;
624
Andreas Gampe4075f832016-05-18 13:09:54 -0700625void DlOpenOatFile::PreLoad() {
626#ifdef __APPLE__
Andreas Gampe39004a62016-05-18 21:27:00 -0700627 UNUSED(shared_objects_before_);
Andreas Gampe4075f832016-05-18 13:09:54 -0700628 LOG(FATAL) << "Should not reach here.";
629 UNREACHABLE();
630#else
631 // Count the entries in dl_iterate_phdr we get at this point in time.
632 struct dl_iterate_context {
633 static int callback(struct dl_phdr_info *info ATTRIBUTE_UNUSED,
634 size_t size ATTRIBUTE_UNUSED,
635 void *data) {
636 reinterpret_cast<dl_iterate_context*>(data)->count++;
637 return 0; // Continue iteration.
638 }
639 size_t count = 0;
640 } context;
641
642 dl_iterate_phdr(dl_iterate_context::callback, &context);
643 shared_objects_before_ = context.count;
644#endif
645}
646
Andreas Gampe049cff02015-12-01 23:27:12 -0800647bool DlOpenOatFile::Load(const std::string& elf_filename,
648 uint8_t* oat_file_begin,
649 bool writable,
650 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800651 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800652 std::string* error_msg) {
653 // Use dlopen only when flagged to do so, and when it's OK to load things executable.
654 // TODO: Also try when not executable? The issue here could be re-mapping as writable (as
655 // !executable is a sign that we may want to patch), which may not be allowed for
656 // various reasons.
657 if (!kUseDlopen) {
658 *error_msg = "DlOpen is disabled.";
659 return false;
660 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800661 if (low_4gb) {
662 *error_msg = "DlOpen does not support low 4gb loading.";
663 return false;
664 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800665 if (writable) {
666 *error_msg = "DlOpen does not support writable loading.";
667 return false;
668 }
669 if (!executable) {
670 *error_msg = "DlOpen does not support non-executable loading.";
671 return false;
672 }
673
674 // dlopen always returns the same library if it is already opened on the host. For this reason
675 // we only use dlopen if we are the target or we do not already have the dex file opened. Having
676 // the same library loaded multiple times at different addresses is required for class unloading
677 // and for having dex caches arrays in the .bss section.
678 if (!kIsTargetBuild) {
679 if (!kUseDlopenOnHost) {
680 *error_msg = "DlOpen disabled for host.";
681 return false;
682 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800683 }
684
685 bool success = Dlopen(elf_filename, oat_file_begin, error_msg);
686 DCHECK(dlopen_handle_ != nullptr || !success);
687
688 return success;
689}
690
691bool DlOpenOatFile::Dlopen(const std::string& elf_filename,
692 uint8_t* oat_file_begin,
693 std::string* error_msg) {
694#ifdef __APPLE__
695 // The dl_iterate_phdr syscall is missing. There is similar API on OSX,
696 // but let's fallback to the custom loading code for the time being.
697 UNUSED(elf_filename, oat_file_begin);
698 *error_msg = "Dlopen unsupported on Mac.";
699 return false;
700#else
701 {
702 UniqueCPtr<char> absolute_path(realpath(elf_filename.c_str(), nullptr));
703 if (absolute_path == nullptr) {
704 *error_msg = StringPrintf("Failed to find absolute path for '%s'", elf_filename.c_str());
705 return false;
706 }
Bilyan Borisovbb661c02016-04-04 16:27:32 +0100707#ifdef ART_TARGET_ANDROID
Andreas Gampe049cff02015-12-01 23:27:12 -0800708 android_dlextinfo extinfo;
709 extinfo.flags = ANDROID_DLEXT_FORCE_LOAD | // Force-load, don't reuse handle
710 // (open oat files multiple
711 // times).
712 ANDROID_DLEXT_FORCE_FIXED_VADDR; // Take a non-zero vaddr as absolute
713 // (non-pic boot image).
Andreas Gampe226b91e2015-12-02 10:29:33 -0800714 if (oat_file_begin != nullptr) { //
715 extinfo.flags |= ANDROID_DLEXT_LOAD_AT_FIXED_ADDRESS; // Use the requested addr if
716 extinfo.reserved_addr = oat_file_begin; // vaddr = 0.
717 } // (pic boot image).
Andreas Gampe049cff02015-12-01 23:27:12 -0800718 dlopen_handle_ = android_dlopen_ext(absolute_path.get(), RTLD_NOW, &extinfo);
719#else
Andreas Gampe049cff02015-12-01 23:27:12 -0800720 UNUSED(oat_file_begin);
Richard Uhlera206c742016-05-24 15:04:22 -0700721 static_assert(!kIsTargetBuild, "host_dlopen_handles_ will leak handles");
Mathieu Chartierc7d3f4b2016-06-01 10:48:19 -0700722 MutexLock mu(Thread::Current(), *Locks::host_dlopen_handles_lock_);
Richard Uhlera206c742016-05-24 15:04:22 -0700723 dlopen_handle_ = dlopen(absolute_path.get(), RTLD_NOW);
724 if (dlopen_handle_ != nullptr) {
Richard Uhlera206c742016-05-24 15:04:22 -0700725 if (!host_dlopen_handles_.insert(dlopen_handle_).second) {
726 dlclose(dlopen_handle_);
727 dlopen_handle_ = nullptr;
728 *error_msg = StringPrintf("host dlopen re-opened '%s'", elf_filename.c_str());
729 return false;
730 }
731 }
Bilyan Borisovbb661c02016-04-04 16:27:32 +0100732#endif // ART_TARGET_ANDROID
Andreas Gampe049cff02015-12-01 23:27:12 -0800733 }
734 if (dlopen_handle_ == nullptr) {
735 *error_msg = StringPrintf("Failed to dlopen '%s': %s", elf_filename.c_str(), dlerror());
736 return false;
737 }
738 return true;
739#endif
740}
741
742void DlOpenOatFile::PreSetup(const std::string& elf_filename) {
Andreas Gampe74f07b52015-12-02 11:53:26 -0800743#ifdef __APPLE__
744 UNUSED(elf_filename);
745 LOG(FATAL) << "Should not reach here.";
746 UNREACHABLE();
747#else
Andreas Gampe049cff02015-12-01 23:27:12 -0800748 struct dl_iterate_context {
749 static int callback(struct dl_phdr_info *info, size_t /* size */, void *data) {
750 auto* context = reinterpret_cast<dl_iterate_context*>(data);
Andreas Gampe4075f832016-05-18 13:09:54 -0700751 context->shared_objects_seen++;
752 if (context->shared_objects_seen < context->shared_objects_before) {
753 // We haven't been called yet for anything we haven't seen before. Just continue.
754 // Note: this is aggressively optimistic. If another thread was unloading a library,
755 // we may miss out here. However, this does not happen often in practice.
756 return 0;
757 }
758
Andreas Gampe049cff02015-12-01 23:27:12 -0800759 // See whether this callback corresponds to the file which we have just loaded.
760 bool contains_begin = false;
761 for (int i = 0; i < info->dlpi_phnum; i++) {
762 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
763 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
764 info->dlpi_phdr[i].p_vaddr);
765 size_t memsz = info->dlpi_phdr[i].p_memsz;
766 if (vaddr <= context->begin_ && context->begin_ < vaddr + memsz) {
767 contains_begin = true;
768 break;
769 }
770 }
771 }
772 // Add dummy mmaps for this file.
773 if (contains_begin) {
774 for (int i = 0; i < info->dlpi_phnum; i++) {
775 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
776 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
777 info->dlpi_phdr[i].p_vaddr);
778 size_t memsz = info->dlpi_phdr[i].p_memsz;
779 MemMap* mmap = MemMap::MapDummy(info->dlpi_name, vaddr, memsz);
780 context->dlopen_mmaps_->push_back(std::unique_ptr<MemMap>(mmap));
781 }
782 }
783 return 1; // Stop iteration and return 1 from dl_iterate_phdr.
784 }
785 return 0; // Continue iteration and return 0 from dl_iterate_phdr when finished.
786 }
787 const uint8_t* const begin_;
788 std::vector<std::unique_ptr<MemMap>>* const dlopen_mmaps_;
Andreas Gampe4075f832016-05-18 13:09:54 -0700789 const size_t shared_objects_before;
790 size_t shared_objects_seen;
791 };
792 dl_iterate_context context = { Begin(), &dlopen_mmaps_, shared_objects_before_, 0};
Andreas Gampe049cff02015-12-01 23:27:12 -0800793
794 if (dl_iterate_phdr(dl_iterate_context::callback, &context) == 0) {
Andreas Gampe4075f832016-05-18 13:09:54 -0700795 // Hm. Maybe our optimization went wrong. Try another time with shared_objects_before == 0
796 // before giving up. This should be unusual.
797 VLOG(oat) << "Need a second run in PreSetup, didn't find with shared_objects_before="
798 << shared_objects_before_;
799 dl_iterate_context context0 = { Begin(), &dlopen_mmaps_, 0, 0};
800 if (dl_iterate_phdr(dl_iterate_context::callback, &context0) == 0) {
801 // OK, give up and print an error.
802 PrintFileToLog("/proc/self/maps", LogSeverity::WARNING);
803 LOG(ERROR) << "File " << elf_filename << " loaded with dlopen but cannot find its mmaps.";
804 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800805 }
Andreas Gampe74f07b52015-12-02 11:53:26 -0800806#endif
Andreas Gampe049cff02015-12-01 23:27:12 -0800807}
808
809////////////////////////////////////////////////
810// OatFile via our own ElfFile implementation //
811////////////////////////////////////////////////
812
813class ElfOatFile FINAL : public OatFileBase {
814 public:
815 ElfOatFile(const std::string& filename, bool executable) : OatFileBase(filename, executable) {}
816
817 static ElfOatFile* OpenElfFile(File* file,
818 const std::string& location,
819 uint8_t* requested_base,
820 uint8_t* oat_file_begin, // Override base 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 const char* abs_dex_location,
825 std::string* error_msg);
826
827 bool InitializeFromElfFile(ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +0100828 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -0800829 const char* abs_dex_location,
830 std::string* error_msg);
831
832 protected:
833 const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
834 std::string* error_msg) const OVERRIDE {
835 const uint8_t* ptr = elf_file_->FindDynamicSymbolAddress(symbol_name);
836 if (ptr == nullptr) {
837 *error_msg = "(Internal implementation could not find symbol)";
838 }
839 return ptr;
840 }
841
Andreas Gampe4075f832016-05-18 13:09:54 -0700842 void PreLoad() OVERRIDE {
843 }
844
Andreas Gampe049cff02015-12-01 23:27:12 -0800845 bool Load(const std::string& elf_filename,
846 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
847 bool writable,
848 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800849 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800850 std::string* error_msg) OVERRIDE;
851
852 void PreSetup(const std::string& elf_filename ATTRIBUTE_UNUSED) OVERRIDE {
853 }
854
855 private:
856 bool ElfFileOpen(File* file,
857 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
858 bool writable,
859 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800860 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800861 std::string* error_msg);
862
863 private:
864 // Backing memory map for oat file during cross compilation.
865 std::unique_ptr<ElfFile> elf_file_;
866
867 DISALLOW_COPY_AND_ASSIGN(ElfOatFile);
868};
869
870ElfOatFile* ElfOatFile::OpenElfFile(File* file,
871 const std::string& location,
872 uint8_t* requested_base,
873 uint8_t* oat_file_begin, // Override base if not null
874 bool writable,
875 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800876 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800877 const char* abs_dex_location,
878 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800879 ScopedTrace trace("Open elf file " + location);
Andreas Gampe049cff02015-12-01 23:27:12 -0800880 std::unique_ptr<ElfOatFile> oat_file(new ElfOatFile(location, executable));
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800881 bool success = oat_file->ElfFileOpen(file,
882 oat_file_begin,
883 writable,
884 low_4gb,
885 executable,
886 error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -0800887 if (!success) {
888 CHECK(!error_msg->empty());
889 return nullptr;
890 }
891
892 // Complete the setup.
893 if (!oat_file->ComputeFields(requested_base, file->GetPath(), error_msg)) {
894 return nullptr;
895 }
896
897 if (!oat_file->Setup(abs_dex_location, error_msg)) {
898 return nullptr;
899 }
900
901 return oat_file.release();
902}
903
904bool ElfOatFile::InitializeFromElfFile(ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +0100905 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -0800906 const char* abs_dex_location,
907 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800908 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -0800909 if (IsExecutable()) {
910 *error_msg = "Cannot initialize from elf file in executable mode.";
911 return false;
912 }
913 elf_file_.reset(elf_file);
David Brazdilc93b3be2016-09-12 18:49:58 +0100914 SetVdex(vdex_file);
Andreas Gampe049cff02015-12-01 23:27:12 -0800915 uint64_t offset, size;
916 bool has_section = elf_file->GetSectionOffsetAndSize(".rodata", &offset, &size);
917 CHECK(has_section);
918 SetBegin(elf_file->Begin() + offset);
919 SetEnd(elf_file->Begin() + size + offset);
920 // Ignore the optional .bss section when opening non-executable.
921 return Setup(abs_dex_location, error_msg);
922}
923
924bool ElfOatFile::Load(const std::string& elf_filename,
925 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
926 bool writable,
927 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800928 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800929 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800930 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -0800931 std::unique_ptr<File> file(OS::OpenFileForReading(elf_filename.c_str()));
932 if (file == nullptr) {
933 *error_msg = StringPrintf("Failed to open oat filename for reading: %s", strerror(errno));
934 return false;
935 }
936 return ElfOatFile::ElfFileOpen(file.get(),
937 oat_file_begin,
938 writable,
939 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800940 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800941 error_msg);
942}
943
944bool ElfOatFile::ElfFileOpen(File* file,
945 uint8_t* oat_file_begin,
946 bool writable,
947 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800948 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800949 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800950 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -0800951 // TODO: rename requested_base to oat_data_begin
952 elf_file_.reset(ElfFile::Open(file,
953 writable,
954 /*program_header_only*/true,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800955 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800956 error_msg,
957 oat_file_begin));
958 if (elf_file_ == nullptr) {
959 DCHECK(!error_msg->empty());
960 return false;
961 }
Brian Carlstromf5b0f2c2016-10-14 01:04:26 -0700962 bool loaded = elf_file_->Load(file, executable, low_4gb, error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -0800963 DCHECK(loaded || !error_msg->empty());
964 return loaded;
965}
966
967//////////////////////////
968// General OatFile code //
969//////////////////////////
970
971std::string OatFile::ResolveRelativeEncodedDexLocation(
972 const char* abs_dex_location, const std::string& rel_dex_location) {
973 if (abs_dex_location != nullptr && rel_dex_location[0] != '/') {
974 // Strip :classes<N>.dex used for secondary multidex files.
975 std::string base = DexFile::GetBaseLocation(rel_dex_location);
976 std::string multidex_suffix = DexFile::GetMultiDexSuffix(rel_dex_location);
977
978 // Check if the base is a suffix of the provided abs_dex_location.
979 std::string target_suffix = "/" + base;
980 std::string abs_location(abs_dex_location);
981 if (abs_location.size() > target_suffix.size()) {
982 size_t pos = abs_location.size() - target_suffix.size();
983 if (abs_location.compare(pos, std::string::npos, target_suffix) == 0) {
984 return abs_location + multidex_suffix;
985 }
986 }
987 }
988 return rel_dex_location;
989}
990
991static void CheckLocation(const std::string& location) {
992 CHECK(!location.empty());
993}
994
995OatFile* OatFile::OpenWithElfFile(ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +0100996 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -0800997 const std::string& location,
998 const char* abs_dex_location,
999 std::string* error_msg) {
1000 std::unique_ptr<ElfOatFile> oat_file(new ElfOatFile(location, false /* executable */));
David Brazdilc93b3be2016-09-12 18:49:58 +01001001 return oat_file->InitializeFromElfFile(elf_file, vdex_file, abs_dex_location, error_msg)
Andreas Gampe049cff02015-12-01 23:27:12 -08001002 ? oat_file.release()
1003 : nullptr;
1004}
1005
David Brazdil7b49e6c2016-09-01 11:06:18 +01001006OatFile* OatFile::Open(const std::string& oat_filename,
1007 const std::string& oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001008 uint8_t* requested_base,
1009 uint8_t* oat_file_begin,
1010 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001011 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001012 const char* abs_dex_location,
1013 std::string* error_msg) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001014 ScopedTrace trace("Open oat file " + oat_location);
1015 CHECK(!oat_filename.empty()) << oat_location;
1016 CheckLocation(oat_location);
Andreas Gampe54315c72016-05-18 21:10:42 -07001017
David Brazdil7b49e6c2016-09-01 11:06:18 +01001018 std::string vdex_filename = ReplaceFileExtension(oat_filename, "vdex");
1019
1020 // Check that the files even exist, fast-fail.
1021 if (kIsVdexEnabled && !OS::FileExists(vdex_filename.c_str())) {
1022 *error_msg = StringPrintf("File %s does not exist.", vdex_filename.c_str());
1023 return nullptr;
1024 } else if (!OS::FileExists(oat_filename.c_str())) {
1025 *error_msg = StringPrintf("File %s does not exist.", oat_filename.c_str());
Andreas Gampe54315c72016-05-18 21:10:42 -07001026 return nullptr;
1027 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001028
1029 // Try dlopen first, as it is required for native debuggability. This will fail fast if dlopen is
1030 // disabled.
David Brazdil7b49e6c2016-09-01 11:06:18 +01001031 OatFile* with_dlopen = OatFileBase::OpenOatFile<DlOpenOatFile>(vdex_filename,
1032 oat_filename,
1033 oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001034 requested_base,
1035 oat_file_begin,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001036 false /* writable */,
Andreas Gampe049cff02015-12-01 23:27:12 -08001037 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001038 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001039 abs_dex_location,
1040 error_msg);
1041 if (with_dlopen != nullptr) {
1042 return with_dlopen;
1043 }
1044 if (kPrintDlOpenErrorMessage) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001045 LOG(ERROR) << "Failed to dlopen: " << oat_filename << " with error " << *error_msg;
Andreas Gampe049cff02015-12-01 23:27:12 -08001046 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001047 // If we aren't trying to execute, we just use our own ElfFile loader for a couple reasons:
1048 //
1049 // On target, dlopen may fail when compiling due to selinux restrictions on installd.
1050 //
1051 // We use our own ELF loader for Quick to deal with legacy apps that
1052 // open a generated dex file by name, remove the file, then open
1053 // another generated dex file with the same name. http://b/10614658
1054 //
1055 // On host, dlopen is expected to fail when cross compiling, so fall back to OpenElfFile.
1056 //
1057 //
1058 // Another independent reason is the absolute placement of boot.oat. dlopen on the host usually
1059 // 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 +01001060 OatFile* with_internal = OatFileBase::OpenOatFile<ElfOatFile>(vdex_filename,
1061 oat_filename,
1062 oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001063 requested_base,
1064 oat_file_begin,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001065 false /* writable */,
Andreas Gampe049cff02015-12-01 23:27:12 -08001066 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001067 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001068 abs_dex_location,
1069 error_msg);
1070 return with_internal;
1071}
1072
1073OatFile* OatFile::OpenWritable(File* file,
1074 const std::string& location,
1075 const char* abs_dex_location,
1076 std::string* error_msg) {
1077 CheckLocation(location);
1078 return ElfOatFile::OpenElfFile(file,
1079 location,
1080 nullptr,
1081 nullptr,
1082 true,
1083 false,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001084 /*low_4gb*/false,
Andreas Gampe049cff02015-12-01 23:27:12 -08001085 abs_dex_location,
1086 error_msg);
1087}
1088
1089OatFile* OatFile::OpenReadable(File* file,
1090 const std::string& location,
1091 const char* abs_dex_location,
1092 std::string* error_msg) {
1093 CheckLocation(location);
1094 return ElfOatFile::OpenElfFile(file,
1095 location,
1096 nullptr,
1097 nullptr,
1098 false,
1099 false,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001100 /*low_4gb*/false,
Andreas Gampe049cff02015-12-01 23:27:12 -08001101 abs_dex_location,
1102 error_msg);
1103}
1104
1105OatFile::OatFile(const std::string& location, bool is_executable)
1106 : location_(location),
David Brazdil7b49e6c2016-09-01 11:06:18 +01001107 vdex_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001108 begin_(nullptr),
1109 end_(nullptr),
1110 bss_begin_(nullptr),
1111 bss_end_(nullptr),
Vladimir Markoaad75c62016-10-03 08:46:48 +00001112 bss_roots_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001113 is_executable_(is_executable),
1114 secondary_lookup_lock_("OatFile secondary lookup lock", kOatFileSecondaryLookupLock) {
1115 CHECK(!location_.empty());
1116}
1117
1118OatFile::~OatFile() {
1119 STLDeleteElements(&oat_dex_files_storage_);
1120}
1121
Brian Carlstrome24fa612011-09-29 00:53:55 -07001122const OatHeader& OatFile::GetOatHeader() const {
Ian Rogers30fab402012-01-23 15:43:46 -08001123 return *reinterpret_cast<const OatHeader*>(Begin());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001124}
1125
Ian Rogers13735952014-10-08 12:43:28 -07001126const uint8_t* OatFile::Begin() const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001127 CHECK(begin_ != nullptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001128 return begin_;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001129}
1130
Ian Rogers13735952014-10-08 12:43:28 -07001131const uint8_t* OatFile::End() const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001132 CHECK(end_ != nullptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001133 return end_;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001134}
1135
Vladimir Marko5c42c292015-02-25 12:02:49 +00001136const uint8_t* OatFile::BssBegin() const {
1137 return bss_begin_;
1138}
1139
1140const uint8_t* OatFile::BssEnd() const {
1141 return bss_end_;
1142}
1143
David Brazdil7b49e6c2016-09-01 11:06:18 +01001144const uint8_t* OatFile::DexBegin() const {
1145 return kIsVdexEnabled ? vdex_->Begin() : Begin();
1146}
1147
1148const uint8_t* OatFile::DexEnd() const {
1149 return kIsVdexEnabled ? vdex_->End() : End();
1150}
1151
Vladimir Markoaad75c62016-10-03 08:46:48 +00001152ArrayRef<GcRoot<mirror::Object>> OatFile::GetBssGcRoots() const {
1153 if (bss_roots_ != nullptr) {
1154 auto* roots = reinterpret_cast<GcRoot<mirror::Object>*>(bss_roots_);
1155 auto* roots_end = reinterpret_cast<GcRoot<mirror::Object>*>(bss_end_);
1156 return ArrayRef<GcRoot<mirror::Object>>(roots, roots_end - roots);
1157 } else {
1158 return ArrayRef<GcRoot<mirror::Object>>();
1159 }
1160}
1161
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001162const OatFile::OatDexFile* OatFile::GetOatDexFile(const char* dex_location,
1163 const uint32_t* dex_location_checksum,
Richard Uhler9a37efc2016-08-05 16:32:55 -07001164 std::string* error_msg) const {
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001165 // NOTE: We assume here that the canonical location for a given dex_location never
1166 // changes. If it does (i.e. some symlink used by the filename changes) we may return
1167 // an incorrect OatDexFile. As long as we have a checksum to check, we shall return
1168 // an identical file or fail; otherwise we may see some unpredictable failures.
Calin Juravle4e1d5792014-07-15 23:56:47 +01001169
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001170 // TODO: Additional analysis of usage patterns to see if this can be simplified
1171 // without any performance loss, for example by not doing the first lock-free lookup.
1172
1173 const OatFile::OatDexFile* oat_dex_file = nullptr;
1174 StringPiece key(dex_location);
1175 // Try to find the key cheaply in the oat_dex_files_ map which holds dex locations
1176 // directly mentioned in the oat file and doesn't require locking.
1177 auto primary_it = oat_dex_files_.find(key);
1178 if (primary_it != oat_dex_files_.end()) {
1179 oat_dex_file = primary_it->second;
1180 DCHECK(oat_dex_file != nullptr);
1181 } else {
1182 // This dex_location is not one of the dex locations directly mentioned in the
1183 // oat file. The correct lookup is via the canonical location but first see in
1184 // the secondary_oat_dex_files_ whether we've looked up this location before.
1185 MutexLock mu(Thread::Current(), secondary_lookup_lock_);
1186 auto secondary_lb = secondary_oat_dex_files_.lower_bound(key);
1187 if (secondary_lb != secondary_oat_dex_files_.end() && key == secondary_lb->first) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001188 oat_dex_file = secondary_lb->second; // May be null.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001189 } else {
1190 // We haven't seen this dex_location before, we must check the canonical location.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001191 std::string dex_canonical_location = DexFile::GetDexCanonicalLocation(dex_location);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001192 if (dex_canonical_location != dex_location) {
1193 StringPiece canonical_key(dex_canonical_location);
1194 auto canonical_it = oat_dex_files_.find(canonical_key);
1195 if (canonical_it != oat_dex_files_.end()) {
1196 oat_dex_file = canonical_it->second;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001197 } // else keep null.
1198 } // else keep null.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001199
1200 // Copy the key to the string_cache_ and store the result in secondary map.
1201 string_cache_.emplace_back(key.data(), key.length());
1202 StringPiece key_copy(string_cache_.back());
1203 secondary_oat_dex_files_.PutBefore(secondary_lb, key_copy, oat_dex_file);
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001204 }
1205 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001206
1207 if (oat_dex_file == nullptr) {
1208 if (error_msg != nullptr) {
1209 std::string dex_canonical_location = DexFile::GetDexCanonicalLocation(dex_location);
1210 *error_msg = "Failed to find OatDexFile for DexFile " + std::string(dex_location)
1211 + " (canonical path " + dex_canonical_location + ") in OatFile " + GetLocation();
1212 }
1213 return nullptr;
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001214 }
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001215
Richard Uhler9a37efc2016-08-05 16:32:55 -07001216 if (dex_location_checksum != nullptr &&
1217 oat_dex_file->GetDexFileLocationChecksum() != *dex_location_checksum) {
1218 if (error_msg != nullptr) {
1219 std::string dex_canonical_location = DexFile::GetDexCanonicalLocation(dex_location);
1220 std::string checksum = StringPrintf("0x%08x", oat_dex_file->GetDexFileLocationChecksum());
1221 std::string required_checksum = StringPrintf("0x%08x", *dex_location_checksum);
1222 *error_msg = "OatDexFile for DexFile " + std::string(dex_location)
1223 + " (canonical path " + dex_canonical_location + ") in OatFile " + GetLocation()
1224 + " has checksum " + checksum + " but " + required_checksum + " was required";
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001225 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001226 return nullptr;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001227 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001228 return oat_dex_file;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001229}
1230
Brian Carlstrome24fa612011-09-29 00:53:55 -07001231OatFile::OatDexFile::OatDexFile(const OatFile* oat_file,
Elliott Hughesaa6a5882012-01-13 19:39:16 -08001232 const std::string& dex_file_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001233 const std::string& canonical_dex_file_location,
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001234 uint32_t dex_file_location_checksum,
Ian Rogers13735952014-10-08 12:43:28 -07001235 const uint8_t* dex_file_pointer,
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001236 const uint8_t* lookup_table_data,
Vladimir Marko09d09432015-09-08 13:47:48 +01001237 const uint32_t* oat_class_offsets_pointer,
Vladimir Marko06d7aaa2015-10-16 11:23:41 +01001238 uint8_t* dex_cache_arrays)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001239 : oat_file_(oat_file),
1240 dex_file_location_(dex_file_location),
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001241 canonical_dex_file_location_(canonical_dex_file_location),
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001242 dex_file_location_checksum_(dex_file_location_checksum),
Brian Carlstrom89521892011-12-07 22:05:07 -08001243 dex_file_pointer_(dex_file_pointer),
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001244 lookup_table_data_(lookup_table_data),
Vladimir Marko09d09432015-09-08 13:47:48 +01001245 oat_class_offsets_pointer_(oat_class_offsets_pointer),
David Sehr9aa352e2016-09-15 18:13:52 -07001246 dex_cache_arrays_(dex_cache_arrays) {
1247 // Initialize TypeLookupTable.
1248 if (lookup_table_data_ != nullptr) {
1249 // Peek the number of classes from the DexFile.
1250 const DexFile::Header* dex_header = reinterpret_cast<const DexFile::Header*>(dex_file_pointer_);
1251 const uint32_t num_class_defs = dex_header->class_defs_size_;
1252 if (lookup_table_data_ + TypeLookupTable::RawDataLength(num_class_defs) > GetOatFile()->End()) {
1253 LOG(WARNING) << "found truncated lookup table in " << dex_file_location_;
1254 } else {
Mathieu Chartier1b868492016-11-16 16:22:37 -08001255 lookup_table_ = TypeLookupTable::Open(dex_file_pointer_, lookup_table_data_, num_class_defs);
David Sehr9aa352e2016-09-15 18:13:52 -07001256 }
1257 }
1258}
Brian Carlstrome24fa612011-09-29 00:53:55 -07001259
Mathieu Chartier1b868492016-11-16 16:22:37 -08001260OatFile::OatDexFile::OatDexFile(std::unique_ptr<TypeLookupTable>&& lookup_table)
1261 : lookup_table_(std::move(lookup_table)) {}
1262
Brian Carlstrome24fa612011-09-29 00:53:55 -07001263OatFile::OatDexFile::~OatDexFile() {}
1264
Ian Rogers05f28c62012-10-23 18:12:13 -07001265size_t OatFile::OatDexFile::FileSize() const {
1266 return reinterpret_cast<const DexFile::Header*>(dex_file_pointer_)->file_size_;
1267}
1268
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001269std::unique_ptr<const DexFile> OatFile::OatDexFile::OpenDexFile(std::string* error_msg) const {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001270 ScopedTrace trace(__PRETTY_FUNCTION__);
Aart Bik37d6a3b2016-06-21 18:30:10 -07001271 static constexpr bool kVerify = false;
1272 static constexpr bool kVerifyChecksum = false;
Andreas Gampe3a2bd292016-01-26 17:23:47 -08001273 return DexFile::Open(dex_file_pointer_,
1274 FileSize(),
1275 dex_file_location_,
1276 dex_file_location_checksum_,
1277 this,
Aart Bik37d6a3b2016-06-21 18:30:10 -07001278 kVerify,
1279 kVerifyChecksum,
Andreas Gampe3a2bd292016-01-26 17:23:47 -08001280 error_msg);
Brian Carlstrom89521892011-12-07 22:05:07 -08001281}
1282
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001283uint32_t OatFile::OatDexFile::GetOatClassOffset(uint16_t class_def_index) const {
1284 return oat_class_offsets_pointer_[class_def_index];
1285}
1286
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001287OatFile::OatClass OatFile::OatDexFile::GetOatClass(uint16_t class_def_index) const {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001288 uint32_t oat_class_offset = GetOatClassOffset(class_def_index);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001289
Ian Rogers13735952014-10-08 12:43:28 -07001290 const uint8_t* oat_class_pointer = oat_file_->Begin() + oat_class_offset;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001291 CHECK_LT(oat_class_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001292
Ian Rogers13735952014-10-08 12:43:28 -07001293 const uint8_t* status_pointer = oat_class_pointer;
Brian Carlstromba150c32013-08-27 17:31:03 -07001294 CHECK_LT(status_pointer, oat_file_->End()) << oat_file_->GetLocation();
1295 mirror::Class::Status status =
1296 static_cast<mirror::Class::Status>(*reinterpret_cast<const int16_t*>(status_pointer));
1297 CHECK_LT(status, mirror::Class::kStatusMax);
1298
Ian Rogers13735952014-10-08 12:43:28 -07001299 const uint8_t* type_pointer = status_pointer + sizeof(uint16_t);
Brian Carlstromba150c32013-08-27 17:31:03 -07001300 CHECK_LT(type_pointer, oat_file_->End()) << oat_file_->GetLocation();
1301 OatClassType type = static_cast<OatClassType>(*reinterpret_cast<const uint16_t*>(type_pointer));
1302 CHECK_LT(type, kOatClassMax);
1303
Ian Rogers13735952014-10-08 12:43:28 -07001304 const uint8_t* after_type_pointer = type_pointer + sizeof(int16_t);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001305 CHECK_LE(after_type_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07001306
Brian Carlstromcd937a92014-03-04 22:53:23 -08001307 uint32_t bitmap_size = 0;
Ian Rogers13735952014-10-08 12:43:28 -07001308 const uint8_t* bitmap_pointer = nullptr;
1309 const uint8_t* methods_pointer = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07001310 if (type != kOatClassNoneCompiled) {
1311 if (type == kOatClassSomeCompiled) {
1312 bitmap_size = static_cast<uint32_t>(*reinterpret_cast<const uint32_t*>(after_type_pointer));
1313 bitmap_pointer = after_type_pointer + sizeof(bitmap_size);
1314 CHECK_LE(bitmap_pointer, oat_file_->End()) << oat_file_->GetLocation();
1315 methods_pointer = bitmap_pointer + bitmap_size;
1316 } else {
1317 methods_pointer = after_type_pointer;
1318 }
1319 CHECK_LE(methods_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstromcd937a92014-03-04 22:53:23 -08001320 }
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001321
Richard Uhler07b3c232015-03-31 15:57:54 -07001322 return OatFile::OatClass(oat_file_,
1323 status,
1324 type,
1325 bitmap_size,
1326 reinterpret_cast<const uint32_t*>(bitmap_pointer),
1327 reinterpret_cast<const OatMethodOffsets*>(methods_pointer));
Brian Carlstrome24fa612011-09-29 00:53:55 -07001328}
1329
David Sehr9aa352e2016-09-15 18:13:52 -07001330const DexFile::ClassDef* OatFile::OatDexFile::FindClassDef(const DexFile& dex_file,
1331 const char* descriptor,
1332 size_t hash) {
1333 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1334 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
1335 if (LIKELY((oat_dex_file != nullptr) && (oat_dex_file->GetTypeLookupTable() != nullptr))) {
1336 const uint32_t class_def_idx = oat_dex_file->GetTypeLookupTable()->Lookup(descriptor, hash);
1337 return (class_def_idx != DexFile::kDexNoIndex) ? &dex_file.GetClassDef(class_def_idx) : nullptr;
1338 }
1339 // Fast path for rare no class defs case.
1340 const uint32_t num_class_defs = dex_file.NumClassDefs();
1341 if (num_class_defs == 0) {
1342 return nullptr;
1343 }
1344 const DexFile::TypeId* type_id = dex_file.FindTypeId(descriptor);
1345 if (type_id != nullptr) {
1346 uint16_t type_idx = dex_file.GetIndexForTypeId(*type_id);
1347 return dex_file.FindClassDef(type_idx);
1348 }
1349 return nullptr;
1350}
1351
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001352OatFile::OatClass::OatClass(const OatFile* oat_file,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001353 mirror::Class::Status status,
Brian Carlstromba150c32013-08-27 17:31:03 -07001354 OatClassType type,
1355 uint32_t bitmap_size,
1356 const uint32_t* bitmap_pointer,
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001357 const OatMethodOffsets* methods_pointer)
Brian Carlstromba150c32013-08-27 17:31:03 -07001358 : oat_file_(oat_file), status_(status), type_(type),
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001359 bitmap_(bitmap_pointer), methods_pointer_(methods_pointer) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001360 switch (type_) {
1361 case kOatClassAllCompiled: {
1362 CHECK_EQ(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001363 CHECK(bitmap_pointer == nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001364 CHECK(methods_pointer != nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001365 break;
1366 }
1367 case kOatClassSomeCompiled: {
1368 CHECK_NE(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001369 CHECK(bitmap_pointer != nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001370 CHECK(methods_pointer != nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001371 break;
1372 }
1373 case kOatClassNoneCompiled: {
1374 CHECK_EQ(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001375 CHECK(bitmap_pointer == nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001376 CHECK(methods_pointer_ == nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001377 break;
1378 }
1379 case kOatClassMax: {
1380 LOG(FATAL) << "Invalid OatClassType " << type_;
1381 break;
1382 }
1383 }
1384}
Brian Carlstrome24fa612011-09-29 00:53:55 -07001385
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001386uint32_t OatFile::OatClass::GetOatMethodOffsetsOffset(uint32_t method_index) const {
1387 const OatMethodOffsets* oat_method_offsets = GetOatMethodOffsets(method_index);
1388 if (oat_method_offsets == nullptr) {
1389 return 0u;
1390 }
1391 return reinterpret_cast<const uint8_t*>(oat_method_offsets) - oat_file_->Begin();
1392}
1393
1394const OatMethodOffsets* OatFile::OatClass::GetOatMethodOffsets(uint32_t method_index) const {
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001395 // 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 -07001396 if (methods_pointer_ == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001397 CHECK_EQ(kOatClassNoneCompiled, type_);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001398 return nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07001399 }
1400 size_t methods_pointer_index;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001401 if (bitmap_ == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001402 CHECK_EQ(kOatClassAllCompiled, type_);
1403 methods_pointer_index = method_index;
1404 } else {
1405 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001406 if (!BitVector::IsBitSet(bitmap_, method_index)) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001407 return nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07001408 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001409 size_t num_set_bits = BitVector::NumSetBits(bitmap_, method_index);
1410 methods_pointer_index = num_set_bits;
Brian Carlstromba150c32013-08-27 17:31:03 -07001411 }
1412 const OatMethodOffsets& oat_method_offsets = methods_pointer_[methods_pointer_index];
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001413 return &oat_method_offsets;
1414}
1415
1416const OatFile::OatMethod OatFile::OatClass::GetOatMethod(uint32_t method_index) const {
1417 const OatMethodOffsets* oat_method_offsets = GetOatMethodOffsets(method_index);
1418 if (oat_method_offsets == nullptr) {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001419 return OatMethod(nullptr, 0);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001420 }
1421 if (oat_file_->IsExecutable() ||
1422 Runtime::Current() == nullptr || // This case applies for oatdump.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001423 Runtime::Current()->IsAotCompiler()) {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001424 return OatMethod(oat_file_->Begin(), oat_method_offsets->code_offset_);
Alex Light9dcc4572014-08-14 14:16:26 -07001425 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001426 // We aren't allowed to use the compiled code. We just force it down the interpreted / jit
1427 // version.
1428 return OatMethod(oat_file_->Begin(), 0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001429}
1430
Mathieu Chartiere401d142015-04-22 13:56:20 -07001431void OatFile::OatMethod::LinkMethod(ArtMethod* method) const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001432 CHECK(method != nullptr);
Ian Rogersef7d42f2014-01-06 12:55:46 -08001433 method->SetEntryPointFromQuickCompiledCode(GetQuickCode());
Brian Carlstromae826982011-11-09 01:33:42 -08001434}
1435
Richard Uhlerd1537b52016-03-29 13:27:41 -07001436bool OatFile::HasPatchInfo() const {
1437 return GetOatHeader().HasPatchInfo();
1438}
1439
Andreas Gampe7ba64962014-10-23 11:37:40 -07001440bool OatFile::IsPic() const {
Igor Murashkin46774762014-10-22 11:37:02 -07001441 return GetOatHeader().IsPic();
Andreas Gampe7ba64962014-10-23 11:37:40 -07001442 // TODO: Check against oat_patches. b/18144996
1443}
1444
Sebastien Hertz0de11332015-05-13 12:14:05 +02001445bool OatFile::IsDebuggable() const {
1446 return GetOatHeader().IsDebuggable();
1447}
1448
Andreas Gampe29d38e72016-03-23 15:31:51 +00001449CompilerFilter::Filter OatFile::GetCompilerFilter() const {
1450 return GetOatHeader().GetCompilerFilter();
Calin Juravleb077e152016-02-18 18:47:37 +00001451}
1452
Andreas Gampe7848da42015-04-09 11:15:04 -07001453static constexpr char kDexClassPathEncodingSeparator = '*';
1454
1455std::string OatFile::EncodeDexFileDependencies(const std::vector<const DexFile*>& dex_files) {
1456 std::ostringstream out;
1457
1458 for (const DexFile* dex_file : dex_files) {
1459 out << dex_file->GetLocation().c_str();
1460 out << kDexClassPathEncodingSeparator;
1461 out << dex_file->GetLocationChecksum();
1462 out << kDexClassPathEncodingSeparator;
1463 }
1464
1465 return out.str();
1466}
1467
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001468bool OatFile::CheckStaticDexFileDependencies(const char* dex_dependencies, std::string* msg) {
Andreas Gampe7848da42015-04-09 11:15:04 -07001469 if (dex_dependencies == nullptr || dex_dependencies[0] == 0) {
1470 // No dependencies.
1471 return true;
1472 }
1473
1474 // Assumption: this is not performance-critical. So it's OK to do this with a std::string and
1475 // Split() instead of manual parsing of the combined char*.
1476 std::vector<std::string> split;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001477 Split(dex_dependencies, kDexClassPathEncodingSeparator, &split);
Andreas Gampe7848da42015-04-09 11:15:04 -07001478 if (split.size() % 2 != 0) {
1479 // Expected pairs of location and checksum.
1480 *msg = StringPrintf("Odd number of elements in dependency list %s", dex_dependencies);
1481 return false;
1482 }
1483
1484 for (auto it = split.begin(), end = split.end(); it != end; it += 2) {
1485 std::string& location = *it;
1486 std::string& checksum = *(it + 1);
1487 int64_t converted = strtoll(checksum.c_str(), nullptr, 10);
1488 if (converted == 0) {
1489 // Conversion error.
1490 *msg = StringPrintf("Conversion error for %s", checksum.c_str());
1491 return false;
1492 }
1493
1494 uint32_t dex_checksum;
1495 std::string error_msg;
1496 if (DexFile::GetChecksum(DexFile::GetDexCanonicalLocation(location.c_str()).c_str(),
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001497 &dex_checksum,
1498 &error_msg)) {
Andreas Gampe7848da42015-04-09 11:15:04 -07001499 if (converted != dex_checksum) {
1500 *msg = StringPrintf("Checksums don't match for %s: %" PRId64 " vs %u",
1501 location.c_str(), converted, dex_checksum);
1502 return false;
1503 }
1504 } else {
1505 // Problem retrieving checksum.
1506 // TODO: odex files?
1507 *msg = StringPrintf("Could not retrieve checksum for %s: %s", location.c_str(),
1508 error_msg.c_str());
1509 return false;
1510 }
1511 }
1512
1513 return true;
1514}
1515
1516bool OatFile::GetDexLocationsFromDependencies(const char* dex_dependencies,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001517 std::vector<std::string>* locations) {
1518 DCHECK(locations != nullptr);
Andreas Gampe7848da42015-04-09 11:15:04 -07001519 if (dex_dependencies == nullptr || dex_dependencies[0] == 0) {
1520 return true;
1521 }
1522
1523 // Assumption: this is not performance-critical. So it's OK to do this with a std::string and
1524 // Split() instead of manual parsing of the combined char*.
1525 std::vector<std::string> split;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001526 Split(dex_dependencies, kDexClassPathEncodingSeparator, &split);
Andreas Gampe7848da42015-04-09 11:15:04 -07001527 if (split.size() % 2 != 0) {
1528 // Expected pairs of location and checksum.
1529 return false;
1530 }
1531
1532 for (auto it = split.begin(), end = split.end(); it != end; it += 2) {
1533 locations->push_back(*it);
1534 }
1535
1536 return true;
1537}
1538
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001539OatFile::OatClass OatFile::FindOatClass(const DexFile& dex_file,
1540 uint16_t class_def_idx,
1541 bool* found) {
1542 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
1543 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Mathieu Chartier1b868492016-11-16 16:22:37 -08001544 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001545 *found = false;
1546 return OatFile::OatClass::Invalid();
1547 }
1548 *found = true;
1549 return oat_dex_file->GetOatClass(class_def_idx);
1550}
1551
Mathieu Chartier1b868492016-11-16 16:22:37 -08001552void OatFile::OatDexFile::AssertAotCompiler() {
1553 CHECK(Runtime::Current()->IsAotCompiler());
1554}
1555
Brian Carlstrome24fa612011-09-29 00:53:55 -07001556} // namespace art