blob: 82b39331dd8398c8960f39b0e4dc9ae4cbffb2c6 [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.
Andreas Gampec60e1b72015-07-30 08:57:50 -070031#ifdef __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"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080037#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080038#include "base/unix_file/fd_file.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080039#include "elf_file.h"
Alex Light84d76052014-08-22 17:49:35 -070040#include "elf_utils.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080041#include "oat.h"
David Srbecky1baabf02015-06-16 17:12:34 +000042#include "mem_map.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080043#include "mirror/class.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070044#include "mirror/object-inl.h"
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +010045#include "oat_file-inl.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070046#include "oat_file_manager.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070047#include "os.h"
Andreas Gampe22f8e5c2014-07-09 11:38:21 -070048#include "runtime.h"
Vladimir Marko9bdf1082016-01-21 12:15:52 +000049#include "type_lookup_table.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080050#include "utils.h"
Vladimir Marko09d09432015-09-08 13:47:48 +010051#include "utils/dex_cache_arrays_layout-inl.h"
Ian Rogers1809a722013-08-09 22:05:32 -070052#include "vmap_table.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070053
54namespace art {
55
Andreas Gampe049cff02015-12-01 23:27:12 -080056// Whether OatFile::Open will try dlopen. Fallback is our own ELF loader.
David Srbecky1baabf02015-06-16 17:12:34 +000057static constexpr bool kUseDlopen = true;
Andreas Gampefa8429b2015-04-07 18:34:42 -070058
Andreas Gampe049cff02015-12-01 23:27:12 -080059// Whether OatFile::Open will try dlopen on the host. On the host we're not linking against
Andreas Gampefa8429b2015-04-07 18:34:42 -070060// bionic, so cannot take advantage of the support for changed semantics (loading the same soname
61// multiple times). However, if/when we switch the above, we likely want to switch this, too,
62// to get test coverage of the code paths.
David Srbecky1baabf02015-06-16 17:12:34 +000063static constexpr bool kUseDlopenOnHost = true;
Andreas Gampefa8429b2015-04-07 18:34:42 -070064
65// For debugging, Open will print DlOpen error message if set to true.
66static constexpr bool kPrintDlOpenErrorMessage = false;
67
Andreas Gampe049cff02015-12-01 23:27:12 -080068// Note for OatFileBase and descendents:
69//
70// These are used in OatFile::Open to try all our loaders.
71//
72// The process is simple:
73//
74// 1) Allocate an instance through the standard constructor (location, executable)
75// 2) Load() to try to open the file.
76// 3) ComputeFields() to populate the OatFile fields like begin_, using FindDynamicSymbolAddress.
77// 4) PreSetup() for any steps that should be done before the final setup.
78// 5) Setup() to complete the procedure.
Richard Uhlere5fed032015-03-18 08:21:11 -070079
Andreas Gampe049cff02015-12-01 23:27:12 -080080class OatFileBase : public OatFile {
81 public:
82 virtual ~OatFileBase() {}
Richard Uhlere5fed032015-03-18 08:21:11 -070083
Andreas Gampe049cff02015-12-01 23:27:12 -080084 template <typename kOatFileBaseSubType>
85 static OatFileBase* OpenOatFile(const std::string& elf_filename,
Alex Light84d76052014-08-22 17:49:35 -070086 const std::string& location,
Andreas Gampe049cff02015-12-01 23:27:12 -080087 uint8_t* requested_base,
88 uint8_t* oat_file_begin,
89 bool writable,
90 bool executable,
Richard Uhlere5fed032015-03-18 08:21:11 -070091 const char* abs_dex_location,
Andreas Gampe049cff02015-12-01 23:27:12 -080092 std::string* error_msg);
Brian Carlstrom700c8d32012-11-05 10:42:02 -080093
Andreas Gampe049cff02015-12-01 23:27:12 -080094 protected:
95 OatFileBase(const std::string& filename, bool executable) : OatFile(filename, executable) {}
Andreas Gampefa8429b2015-04-07 18:34:42 -070096
Andreas Gampe049cff02015-12-01 23:27:12 -080097 virtual const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
98 std::string* error_msg) const = 0;
99
100 virtual bool Load(const std::string& elf_filename,
101 uint8_t* oat_file_begin,
102 bool writable,
103 bool executable,
104 std::string* error_msg) = 0;
105
106 bool ComputeFields(uint8_t* requested_base,
107 const std::string& file_path,
108 std::string* error_msg);
109
110 virtual void PreSetup(const std::string& elf_filename) = 0;
111
112 bool Setup(const char* abs_dex_location, std::string* error_msg);
113
114 // Setters exposed for ElfOatFile.
115
116 void SetBegin(const uint8_t* begin) {
117 begin_ = begin;
Andreas Gampefa8429b2015-04-07 18:34:42 -0700118 }
119
Andreas Gampe049cff02015-12-01 23:27:12 -0800120 void SetEnd(const uint8_t* end) {
121 end_ = end;
122 }
123
124 private:
125 DISALLOW_COPY_AND_ASSIGN(OatFileBase);
126};
127
128template <typename kOatFileBaseSubType>
129OatFileBase* OatFileBase::OpenOatFile(const std::string& elf_filename,
130 const std::string& location,
131 uint8_t* requested_base,
132 uint8_t* oat_file_begin,
133 bool writable,
134 bool executable,
135 const char* abs_dex_location,
136 std::string* error_msg) {
137 std::unique_ptr<OatFileBase> ret(new kOatFileBaseSubType(location, executable));
138 if (!ret->Load(elf_filename,
139 oat_file_begin,
140 writable,
141 executable,
142 error_msg)) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800143 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800144 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800145
Andreas Gampe049cff02015-12-01 23:27:12 -0800146 if (!ret->ComputeFields(requested_base, elf_filename, error_msg)) {
147 return nullptr;
148 }
149
150 ret->PreSetup(elf_filename);
151
152 if (!ret->Setup(abs_dex_location, error_msg)) {
153 return nullptr;
154 }
155
Dave Allison69dfe512014-07-11 17:11:58 +0000156 return ret.release();
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800157}
158
Andreas Gampe049cff02015-12-01 23:27:12 -0800159bool OatFileBase::ComputeFields(uint8_t* requested_base,
160 const std::string& file_path,
161 std::string* error_msg) {
162 std::string symbol_error_msg;
163 begin_ = FindDynamicSymbolAddress("oatdata", &symbol_error_msg);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700164 if (begin_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800165 *error_msg = StringPrintf("Failed to find oatdata symbol in '%s' %s",
166 file_path.c_str(),
167 symbol_error_msg.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700168 return false;
169 }
170 if (requested_base != nullptr && begin_ != requested_base) {
171 PrintFileToLog("/proc/self/maps", LogSeverity::WARNING);
172 *error_msg = StringPrintf("Failed to find oatdata symbol at expected address: "
Andreas Gampe049cff02015-12-01 23:27:12 -0800173 "oatdata=%p != expected=%p. See process maps in the log.",
174 begin_, requested_base);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700175 return false;
176 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800177 end_ = FindDynamicSymbolAddress("oatlastword", &symbol_error_msg);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700178 if (end_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800179 *error_msg = StringPrintf("Failed to find oatlastword symbol in '%s' %s",
180 file_path.c_str(),
181 symbol_error_msg.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700182 return false;
183 }
184 // Readjust to be non-inclusive upper bound.
185 end_ += sizeof(uint32_t);
186
Andreas Gampe049cff02015-12-01 23:27:12 -0800187 bss_begin_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbss", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700188 if (bss_begin_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800189 // No .bss section.
Andreas Gampefa8429b2015-04-07 18:34:42 -0700190 bss_end_ = nullptr;
Andreas Gampefa8429b2015-04-07 18:34:42 -0700191 } else {
Andreas Gampe049cff02015-12-01 23:27:12 -0800192 bss_end_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbsslastword", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700193 if (bss_end_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800194 *error_msg = StringPrintf("Failed to find oatbasslastword symbol in '%s'", file_path.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700195 return false;
196 }
197 // Readjust to be non-inclusive upper bound.
198 bss_end_ += sizeof(uint32_t);
199 }
200
Andreas Gampe049cff02015-12-01 23:27:12 -0800201 return true;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800202}
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800203
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100204// Read an unaligned entry from the OatDexFile data in OatFile and advance the read
205// position by the number of bytes read, i.e. sizeof(T).
206// Return true on success, false if the read would go beyond the end of the OatFile.
207template <typename T>
Vladimir Marko722fa982015-10-19 18:18:27 +0100208inline static bool ReadOatDexFileData(const OatFile& oat_file,
209 /*inout*/const uint8_t** oat,
210 /*out*/T* value) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100211 DCHECK(oat != nullptr);
212 DCHECK(value != nullptr);
213 DCHECK_LE(*oat, oat_file.End());
214 if (UNLIKELY(static_cast<size_t>(oat_file.End() - *oat) < sizeof(T))) {
215 return false;
216 }
217 static_assert(std::is_trivial<T>::value, "T must be a trivial type");
218 typedef __attribute__((__aligned__(1))) T unaligned_type;
219 *value = *reinterpret_cast<const unaligned_type*>(*oat);
220 *oat += sizeof(T);
221 return true;
222}
223
Andreas Gampe049cff02015-12-01 23:27:12 -0800224bool OatFileBase::Setup(const char* abs_dex_location, std::string* error_msg) {
Brian Carlstromf1b30302013-03-28 10:35:32 -0700225 if (!GetOatHeader().IsValid()) {
Andreas Gampe2bcb3b22014-12-12 15:25:14 -0800226 std::string cause = GetOatHeader().GetValidationErrorMessage();
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100227 *error_msg = StringPrintf("Invalid oat header for '%s': %s",
228 GetLocation().c_str(),
Andreas Gampe2bcb3b22014-12-12 15:25:14 -0800229 cause.c_str());
Brian Carlstromf1b30302013-03-28 10:35:32 -0700230 return false;
231 }
Ian Rogers13735952014-10-08 12:43:28 -0700232 const uint8_t* oat = Begin();
Brian Carlstrome24fa612011-09-29 00:53:55 -0700233 oat += sizeof(OatHeader);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700234 if (oat > End()) {
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700235 *error_msg = StringPrintf("In oat file '%s' found truncated OatHeader", GetLocation().c_str());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700236 return false;
237 }
Brian Carlstrom81f3ca12012-03-17 00:27:35 -0700238
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700239 oat += GetOatHeader().GetKeyValueStoreSize();
Brian Carlstromfb331d72013-07-25 22:00:16 -0700240 if (oat > End()) {
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700241 *error_msg = StringPrintf("In oat file '%s' found truncated variable-size data: "
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100242 "%p + %zu + %u <= %p",
243 GetLocation().c_str(),
244 Begin(),
245 sizeof(OatHeader),
246 GetOatHeader().GetKeyValueStoreSize(),
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700247 End());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700248 return false;
249 }
250
Vladimir Marko09d09432015-09-08 13:47:48 +0100251 size_t pointer_size = GetInstructionSetPointerSize(GetOatHeader().GetInstructionSet());
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100252 uint8_t* dex_cache_arrays = bss_begin_;
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100253 uint32_t dex_file_count = GetOatHeader().GetDexFileCount();
254 oat_dex_files_storage_.reserve(dex_file_count);
255 for (size_t i = 0; i < dex_file_count; i++) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100256 uint32_t dex_file_location_size;
257 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_location_size))) {
258 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu truncated after dex file "
259 "location size",
260 GetLocation().c_str(),
261 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700262 return false;
263 }
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100264 if (UNLIKELY(dex_file_location_size == 0U)) {
265 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu with empty location name",
266 GetLocation().c_str(),
267 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700268 return false;
269 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000270 if (UNLIKELY(static_cast<size_t>(End() - oat) < dex_file_location_size)) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100271 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu with truncated dex file "
272 "location",
273 GetLocation().c_str(),
274 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700275 return false;
276 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000277 const char* dex_file_location_data = reinterpret_cast<const char*>(oat);
278 oat += dex_file_location_size;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700279
Richard Uhlere5fed032015-03-18 08:21:11 -0700280 std::string dex_file_location = ResolveRelativeEncodedDexLocation(
281 abs_dex_location,
282 std::string(dex_file_location_data, dex_file_location_size));
Brian Carlstrome24fa612011-09-29 00:53:55 -0700283
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100284 uint32_t dex_file_checksum;
285 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_checksum))) {
286 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated after "
287 "dex file checksum",
288 GetLocation().c_str(),
289 i,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700290 dex_file_location.c_str());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700291 return false;
292 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700293
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100294 uint32_t dex_file_offset;
295 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_offset))) {
296 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated "
297 "after dex file offsets",
298 GetLocation().c_str(),
299 i,
300 dex_file_location.c_str());
301 return false;
302 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700303 if (UNLIKELY(dex_file_offset == 0U)) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100304 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with zero dex "
305 "file offset",
306 GetLocation().c_str(),
307 i,
308 dex_file_location.c_str());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700309 return false;
310 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700311 if (UNLIKELY(dex_file_offset > Size())) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100312 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
313 "offset %u > %zu",
314 GetLocation().c_str(),
315 i,
316 dex_file_location.c_str(),
317 dex_file_offset,
318 Size());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700319 return false;
320 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000321 if (UNLIKELY(Size() - dex_file_offset < sizeof(DexFile::Header))) {
322 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
323 "offset %u of %zu but the size of dex file header is %zu",
324 GetLocation().c_str(),
325 i,
326 dex_file_location.c_str(),
327 dex_file_offset,
328 Size(),
329 sizeof(DexFile::Header));
330 return false;
331 }
Brian Carlstrom89521892011-12-07 22:05:07 -0800332
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800333 const uint8_t* dex_file_pointer = Begin() + dex_file_offset;
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700334 if (UNLIKELY(!DexFile::IsMagicValid(dex_file_pointer))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100335 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with invalid "
336 "dex file magic '%s'",
337 GetLocation().c_str(),
338 i,
339 dex_file_location.c_str(),
340 dex_file_pointer);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700341 return false;
342 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700343 if (UNLIKELY(!DexFile::IsVersionValid(dex_file_pointer))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100344 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with invalid "
345 "dex file version '%s'",
346 GetLocation().c_str(),
347 i,
348 dex_file_location.c_str(),
349 dex_file_pointer);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700350 return false;
351 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800352 const DexFile::Header* header = reinterpret_cast<const DexFile::Header*>(dex_file_pointer);
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000353 if (Size() - dex_file_offset < header->file_size_) {
354 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
355 "offset %u and size %u truncated at %zu",
356 GetLocation().c_str(),
357 i,
358 dex_file_location.c_str(),
359 dex_file_offset,
360 header->file_size_,
361 Size());
362 return false;
363 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300364
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000365 uint32_t class_offsets_offset;
366 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &class_offsets_offset))) {
367 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated "
368 "after class offsets offset",
369 GetLocation().c_str(),
370 i,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300371 dex_file_location.c_str());
372 return false;
373 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000374 if (UNLIKELY(class_offsets_offset > Size()) ||
375 UNLIKELY((Size() - class_offsets_offset) / sizeof(uint32_t) < header->class_defs_size_)) {
376 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with truncated "
377 "class offsets, offset %u of %zu, class defs %u",
378 GetLocation().c_str(),
379 i,
380 dex_file_location.c_str(),
381 class_offsets_offset,
382 Size(),
383 header->class_defs_size_);
384 return false;
385 }
386 if (UNLIKELY(!IsAligned<alignof(uint32_t)>(class_offsets_offset))) {
387 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with unaligned "
388 "class offsets, offset %u",
389 GetLocation().c_str(),
390 i,
391 dex_file_location.c_str(),
392 class_offsets_offset);
393 return false;
394 }
395 const uint32_t* class_offsets_pointer =
396 reinterpret_cast<const uint32_t*>(Begin() + class_offsets_offset);
397
398 uint32_t lookup_table_offset;
399 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &lookup_table_offset))) {
400 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zd for '%s' truncated "
401 "after lookup table offset",
402 GetLocation().c_str(),
403 i,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300404 dex_file_location.c_str());
405 return false;
406 }
407 const uint8_t* lookup_table_data = lookup_table_offset != 0u
408 ? Begin() + lookup_table_offset
409 : nullptr;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000410 if (lookup_table_offset != 0u &&
411 (UNLIKELY(lookup_table_offset > Size()) ||
412 UNLIKELY(Size() - lookup_table_offset <
413 TypeLookupTable::RawDataLength(header->class_defs_size_)))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100414 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with truncated "
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000415 "type lookup table, offset %u of %zu, class defs %u",
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100416 GetLocation().c_str(),
417 i,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000418 dex_file_location.c_str(),
419 lookup_table_offset,
420 Size(),
421 header->class_defs_size_);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700422 return false;
423 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700424
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100425 uint8_t* current_dex_cache_arrays = nullptr;
Vladimir Marko09d09432015-09-08 13:47:48 +0100426 if (dex_cache_arrays != nullptr) {
427 DexCacheArraysLayout layout(pointer_size, *header);
428 if (layout.Size() != 0u) {
429 if (static_cast<size_t>(bss_end_ - dex_cache_arrays) < layout.Size()) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100430 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with "
431 "truncated dex cache arrays, %zu < %zu.",
432 GetLocation().c_str(),
433 i,
434 dex_file_location.c_str(),
435 static_cast<size_t>(bss_end_ - dex_cache_arrays),
436 layout.Size());
Vladimir Marko09d09432015-09-08 13:47:48 +0100437 return false;
438 }
439 current_dex_cache_arrays = dex_cache_arrays;
440 dex_cache_arrays += layout.Size();
441 }
442 }
443
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100444 std::string canonical_location = DexFile::GetDexCanonicalLocation(dex_file_location.c_str());
445
446 // Create the OatDexFile and add it to the owning container.
Vladimir Marko539690a2014-06-05 18:36:42 +0100447 OatDexFile* oat_dex_file = new OatDexFile(this,
448 dex_file_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100449 canonical_location,
Vladimir Marko539690a2014-06-05 18:36:42 +0100450 dex_file_checksum,
451 dex_file_pointer,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300452 lookup_table_data,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000453 class_offsets_pointer,
Vladimir Marko09d09432015-09-08 13:47:48 +0100454 current_dex_cache_arrays);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100455 oat_dex_files_storage_.push_back(oat_dex_file);
456
457 // Add the location and canonical location (if different) to the oat_dex_files_ table.
Vladimir Marko3f5838d2014-08-07 18:07:18 +0100458 StringPiece key(oat_dex_file->GetDexFileLocation());
Vladimir Marko539690a2014-06-05 18:36:42 +0100459 oat_dex_files_.Put(key, oat_dex_file);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100460 if (canonical_location != dex_file_location) {
461 StringPiece canonical_key(oat_dex_file->GetCanonicalDexFileLocation());
462 oat_dex_files_.Put(canonical_key, oat_dex_file);
463 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700464 }
Vladimir Marko09d09432015-09-08 13:47:48 +0100465
466 if (dex_cache_arrays != bss_end_) {
467 // We expect the bss section to be either empty (dex_cache_arrays and bss_end_
468 // both null) or contain just the dex cache arrays and nothing else.
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100469 *error_msg = StringPrintf("In oat file '%s' found unexpected bss size bigger by %zu bytes.",
Vladimir Marko09d09432015-09-08 13:47:48 +0100470 GetLocation().c_str(),
471 static_cast<size_t>(bss_end_ - dex_cache_arrays));
472 return false;
473 }
Brian Carlstromf1b30302013-03-28 10:35:32 -0700474 return true;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700475}
476
Andreas Gampe049cff02015-12-01 23:27:12 -0800477////////////////////////
478// OatFile via dlopen //
479////////////////////////
480
481static bool RegisterOatFileLocation(const std::string& location) {
482 if (!kIsTargetBuild) {
483 Runtime* const runtime = Runtime::Current();
484 if (runtime != nullptr && !runtime->IsAotCompiler()) {
485 return runtime->GetOatFileManager().RegisterOatFileLocation(location);
486 }
487 return false;
488 }
489 return true;
490}
491
492static void UnregisterOatFileLocation(const std::string& location) {
493 if (!kIsTargetBuild) {
494 Runtime* const runtime = Runtime::Current();
495 if (runtime != nullptr && !runtime->IsAotCompiler()) {
496 runtime->GetOatFileManager().UnRegisterOatFileLocation(location);
497 }
498 }
499}
500
501class DlOpenOatFile FINAL : public OatFileBase {
502 public:
503 DlOpenOatFile(const std::string& filename, bool executable)
504 : OatFileBase(filename, executable),
505 dlopen_handle_(nullptr),
506 first_oat_(RegisterOatFileLocation(filename)) {
507 }
508
509 ~DlOpenOatFile() {
510 if (dlopen_handle_ != nullptr) {
511 dlclose(dlopen_handle_);
512 }
513 UnregisterOatFileLocation(GetLocation());
514 }
515
516 protected:
517 const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
518 std::string* error_msg) const OVERRIDE {
519 const uint8_t* ptr =
520 reinterpret_cast<const uint8_t*>(dlsym(dlopen_handle_, symbol_name.c_str()));
521 if (ptr == nullptr) {
522 *error_msg = dlerror();
523 }
524 return ptr;
525 }
526
527 bool Load(const std::string& elf_filename,
528 uint8_t* oat_file_begin,
529 bool writable,
530 bool executable,
531 std::string* error_msg) OVERRIDE;
532
533 // Ask the linker where it mmaped the file and notify our mmap wrapper of the regions.
534 void PreSetup(const std::string& elf_filename) OVERRIDE;
535
536 private:
537 bool Dlopen(const std::string& elf_filename,
538 uint8_t* oat_file_begin,
539 std::string* error_msg);
540
541 // dlopen handle during runtime.
542 void* dlopen_handle_; // TODO: Unique_ptr with custom deleter.
543
544 // Dummy memory map objects corresponding to the regions mapped by dlopen.
545 std::vector<std::unique_ptr<MemMap>> dlopen_mmaps_;
546
547 // Track the registration status (= was this the first oat file) for the location.
548 const bool first_oat_;
549
550 DISALLOW_COPY_AND_ASSIGN(DlOpenOatFile);
551};
552
553bool DlOpenOatFile::Load(const std::string& elf_filename,
554 uint8_t* oat_file_begin,
555 bool writable,
556 bool executable,
557 std::string* error_msg) {
558 // Use dlopen only when flagged to do so, and when it's OK to load things executable.
559 // TODO: Also try when not executable? The issue here could be re-mapping as writable (as
560 // !executable is a sign that we may want to patch), which may not be allowed for
561 // various reasons.
562 if (!kUseDlopen) {
563 *error_msg = "DlOpen is disabled.";
564 return false;
565 }
566 if (writable) {
567 *error_msg = "DlOpen does not support writable loading.";
568 return false;
569 }
570 if (!executable) {
571 *error_msg = "DlOpen does not support non-executable loading.";
572 return false;
573 }
574
575 // dlopen always returns the same library if it is already opened on the host. For this reason
576 // we only use dlopen if we are the target or we do not already have the dex file opened. Having
577 // the same library loaded multiple times at different addresses is required for class unloading
578 // and for having dex caches arrays in the .bss section.
579 if (!kIsTargetBuild) {
580 if (!kUseDlopenOnHost) {
581 *error_msg = "DlOpen disabled for host.";
582 return false;
583 }
584 // For RAII, tracking multiple loads is done in the constructor and destructor. The result is
585 // stored in the first_oat_ flag.
586 if (!first_oat_) {
587 *error_msg = "Loading oat files multiple times with dlopen not supported on host.";
588 return false;
589 }
590 }
591
592 bool success = Dlopen(elf_filename, oat_file_begin, error_msg);
593 DCHECK(dlopen_handle_ != nullptr || !success);
594
595 return success;
596}
597
598bool DlOpenOatFile::Dlopen(const std::string& elf_filename,
599 uint8_t* oat_file_begin,
600 std::string* error_msg) {
601#ifdef __APPLE__
602 // The dl_iterate_phdr syscall is missing. There is similar API on OSX,
603 // but let's fallback to the custom loading code for the time being.
604 UNUSED(elf_filename, oat_file_begin);
605 *error_msg = "Dlopen unsupported on Mac.";
606 return false;
607#else
608 {
609 UniqueCPtr<char> absolute_path(realpath(elf_filename.c_str(), nullptr));
610 if (absolute_path == nullptr) {
611 *error_msg = StringPrintf("Failed to find absolute path for '%s'", elf_filename.c_str());
612 return false;
613 }
614#ifdef __ANDROID__
615 android_dlextinfo extinfo;
616 extinfo.flags = ANDROID_DLEXT_FORCE_LOAD | // Force-load, don't reuse handle
617 // (open oat files multiple
618 // times).
619 ANDROID_DLEXT_FORCE_FIXED_VADDR; // Take a non-zero vaddr as absolute
620 // (non-pic boot image).
Andreas Gampe226b91e2015-12-02 10:29:33 -0800621 if (oat_file_begin != nullptr) { //
622 extinfo.flags |= ANDROID_DLEXT_LOAD_AT_FIXED_ADDRESS; // Use the requested addr if
623 extinfo.reserved_addr = oat_file_begin; // vaddr = 0.
624 } // (pic boot image).
Andreas Gampe049cff02015-12-01 23:27:12 -0800625 dlopen_handle_ = android_dlopen_ext(absolute_path.get(), RTLD_NOW, &extinfo);
626#else
627 dlopen_handle_ = dlopen(absolute_path.get(), RTLD_NOW);
628 UNUSED(oat_file_begin);
629#endif
630 }
631 if (dlopen_handle_ == nullptr) {
632 *error_msg = StringPrintf("Failed to dlopen '%s': %s", elf_filename.c_str(), dlerror());
633 return false;
634 }
635 return true;
636#endif
637}
638
639void DlOpenOatFile::PreSetup(const std::string& elf_filename) {
Andreas Gampe74f07b52015-12-02 11:53:26 -0800640#ifdef __APPLE__
641 UNUSED(elf_filename);
642 LOG(FATAL) << "Should not reach here.";
643 UNREACHABLE();
644#else
Andreas Gampe049cff02015-12-01 23:27:12 -0800645 struct dl_iterate_context {
646 static int callback(struct dl_phdr_info *info, size_t /* size */, void *data) {
647 auto* context = reinterpret_cast<dl_iterate_context*>(data);
648 // See whether this callback corresponds to the file which we have just loaded.
649 bool contains_begin = false;
650 for (int i = 0; i < info->dlpi_phnum; i++) {
651 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
652 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
653 info->dlpi_phdr[i].p_vaddr);
654 size_t memsz = info->dlpi_phdr[i].p_memsz;
655 if (vaddr <= context->begin_ && context->begin_ < vaddr + memsz) {
656 contains_begin = true;
657 break;
658 }
659 }
660 }
661 // Add dummy mmaps for this file.
662 if (contains_begin) {
663 for (int i = 0; i < info->dlpi_phnum; i++) {
664 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
665 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
666 info->dlpi_phdr[i].p_vaddr);
667 size_t memsz = info->dlpi_phdr[i].p_memsz;
668 MemMap* mmap = MemMap::MapDummy(info->dlpi_name, vaddr, memsz);
669 context->dlopen_mmaps_->push_back(std::unique_ptr<MemMap>(mmap));
670 }
671 }
672 return 1; // Stop iteration and return 1 from dl_iterate_phdr.
673 }
674 return 0; // Continue iteration and return 0 from dl_iterate_phdr when finished.
675 }
676 const uint8_t* const begin_;
677 std::vector<std::unique_ptr<MemMap>>* const dlopen_mmaps_;
678 } context = { Begin(), &dlopen_mmaps_ };
679
680 if (dl_iterate_phdr(dl_iterate_context::callback, &context) == 0) {
681 PrintFileToLog("/proc/self/maps", LogSeverity::WARNING);
Roland Levillain91d65e02016-01-19 15:59:16 +0000682 LOG(ERROR) << "File " << elf_filename << " loaded with dlopen but cannot find its mmaps.";
Andreas Gampe049cff02015-12-01 23:27:12 -0800683 }
Andreas Gampe74f07b52015-12-02 11:53:26 -0800684#endif
Andreas Gampe049cff02015-12-01 23:27:12 -0800685}
686
687////////////////////////////////////////////////
688// OatFile via our own ElfFile implementation //
689////////////////////////////////////////////////
690
691class ElfOatFile FINAL : public OatFileBase {
692 public:
693 ElfOatFile(const std::string& filename, bool executable) : OatFileBase(filename, executable) {}
694
695 static ElfOatFile* OpenElfFile(File* file,
696 const std::string& location,
697 uint8_t* requested_base,
698 uint8_t* oat_file_begin, // Override base if not null
699 bool writable,
700 bool executable,
701 const char* abs_dex_location,
702 std::string* error_msg);
703
704 bool InitializeFromElfFile(ElfFile* elf_file,
705 const char* abs_dex_location,
706 std::string* error_msg);
707
708 protected:
709 const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
710 std::string* error_msg) const OVERRIDE {
711 const uint8_t* ptr = elf_file_->FindDynamicSymbolAddress(symbol_name);
712 if (ptr == nullptr) {
713 *error_msg = "(Internal implementation could not find symbol)";
714 }
715 return ptr;
716 }
717
718 bool Load(const std::string& elf_filename,
719 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
720 bool writable,
721 bool executable,
722 std::string* error_msg) OVERRIDE;
723
724 void PreSetup(const std::string& elf_filename ATTRIBUTE_UNUSED) OVERRIDE {
725 }
726
727 private:
728 bool ElfFileOpen(File* file,
729 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
730 bool writable,
731 bool executable,
732 std::string* error_msg);
733
734 private:
735 // Backing memory map for oat file during cross compilation.
736 std::unique_ptr<ElfFile> elf_file_;
737
738 DISALLOW_COPY_AND_ASSIGN(ElfOatFile);
739};
740
741ElfOatFile* ElfOatFile::OpenElfFile(File* file,
742 const std::string& location,
743 uint8_t* requested_base,
744 uint8_t* oat_file_begin, // Override base if not null
745 bool writable,
746 bool executable,
747 const char* abs_dex_location,
748 std::string* error_msg) {
749 std::unique_ptr<ElfOatFile> oat_file(new ElfOatFile(location, executable));
750 bool success = oat_file->ElfFileOpen(file, oat_file_begin, writable, executable, error_msg);
751 if (!success) {
752 CHECK(!error_msg->empty());
753 return nullptr;
754 }
755
756 // Complete the setup.
757 if (!oat_file->ComputeFields(requested_base, file->GetPath(), error_msg)) {
758 return nullptr;
759 }
760
761 if (!oat_file->Setup(abs_dex_location, error_msg)) {
762 return nullptr;
763 }
764
765 return oat_file.release();
766}
767
768bool ElfOatFile::InitializeFromElfFile(ElfFile* elf_file,
769 const char* abs_dex_location,
770 std::string* error_msg) {
771 if (IsExecutable()) {
772 *error_msg = "Cannot initialize from elf file in executable mode.";
773 return false;
774 }
775 elf_file_.reset(elf_file);
776 uint64_t offset, size;
777 bool has_section = elf_file->GetSectionOffsetAndSize(".rodata", &offset, &size);
778 CHECK(has_section);
779 SetBegin(elf_file->Begin() + offset);
780 SetEnd(elf_file->Begin() + size + offset);
781 // Ignore the optional .bss section when opening non-executable.
782 return Setup(abs_dex_location, error_msg);
783}
784
785bool ElfOatFile::Load(const std::string& elf_filename,
786 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
787 bool writable,
788 bool executable,
789 std::string* error_msg) {
790 std::unique_ptr<File> file(OS::OpenFileForReading(elf_filename.c_str()));
791 if (file == nullptr) {
792 *error_msg = StringPrintf("Failed to open oat filename for reading: %s", strerror(errno));
793 return false;
794 }
795 return ElfOatFile::ElfFileOpen(file.get(),
796 oat_file_begin,
797 writable,
798 executable,
799 error_msg);
800}
801
802bool ElfOatFile::ElfFileOpen(File* file,
803 uint8_t* oat_file_begin,
804 bool writable,
805 bool executable,
806 std::string* error_msg) {
807 // TODO: rename requested_base to oat_data_begin
808 elf_file_.reset(ElfFile::Open(file,
809 writable,
810 /*program_header_only*/true,
811 error_msg,
812 oat_file_begin));
813 if (elf_file_ == nullptr) {
814 DCHECK(!error_msg->empty());
815 return false;
816 }
817 bool loaded = elf_file_->Load(executable, error_msg);
818 DCHECK(loaded || !error_msg->empty());
819 return loaded;
820}
821
822//////////////////////////
823// General OatFile code //
824//////////////////////////
825
826std::string OatFile::ResolveRelativeEncodedDexLocation(
827 const char* abs_dex_location, const std::string& rel_dex_location) {
828 if (abs_dex_location != nullptr && rel_dex_location[0] != '/') {
829 // Strip :classes<N>.dex used for secondary multidex files.
830 std::string base = DexFile::GetBaseLocation(rel_dex_location);
831 std::string multidex_suffix = DexFile::GetMultiDexSuffix(rel_dex_location);
832
833 // Check if the base is a suffix of the provided abs_dex_location.
834 std::string target_suffix = "/" + base;
835 std::string abs_location(abs_dex_location);
836 if (abs_location.size() > target_suffix.size()) {
837 size_t pos = abs_location.size() - target_suffix.size();
838 if (abs_location.compare(pos, std::string::npos, target_suffix) == 0) {
839 return abs_location + multidex_suffix;
840 }
841 }
842 }
843 return rel_dex_location;
844}
845
846static void CheckLocation(const std::string& location) {
847 CHECK(!location.empty());
848}
849
850OatFile* OatFile::OpenWithElfFile(ElfFile* elf_file,
851 const std::string& location,
852 const char* abs_dex_location,
853 std::string* error_msg) {
854 std::unique_ptr<ElfOatFile> oat_file(new ElfOatFile(location, false /* executable */));
855 return oat_file->InitializeFromElfFile(elf_file, abs_dex_location, error_msg)
856 ? oat_file.release()
857 : nullptr;
858}
859
860OatFile* OatFile::Open(const std::string& filename,
861 const std::string& location,
862 uint8_t* requested_base,
863 uint8_t* oat_file_begin,
864 bool executable,
865 const char* abs_dex_location,
866 std::string* error_msg) {
867 CHECK(!filename.empty()) << location;
868 CheckLocation(location);
869 std::unique_ptr<OatFile> ret;
870
871 // Try dlopen first, as it is required for native debuggability. This will fail fast if dlopen is
872 // disabled.
873 OatFile* with_dlopen = OatFileBase::OpenOatFile<DlOpenOatFile>(filename,
874 location,
875 requested_base,
876 oat_file_begin,
877 false,
878 executable,
879 abs_dex_location,
880 error_msg);
881 if (with_dlopen != nullptr) {
882 return with_dlopen;
883 }
884 if (kPrintDlOpenErrorMessage) {
885 LOG(ERROR) << "Failed to dlopen: " << *error_msg;
886 }
887
888 // If we aren't trying to execute, we just use our own ElfFile loader for a couple reasons:
889 //
890 // On target, dlopen may fail when compiling due to selinux restrictions on installd.
891 //
892 // We use our own ELF loader for Quick to deal with legacy apps that
893 // open a generated dex file by name, remove the file, then open
894 // another generated dex file with the same name. http://b/10614658
895 //
896 // On host, dlopen is expected to fail when cross compiling, so fall back to OpenElfFile.
897 //
898 //
899 // Another independent reason is the absolute placement of boot.oat. dlopen on the host usually
900 // does honor the virtual address encoded in the ELF file only for ET_EXEC files, not ET_DYN.
901 OatFile* with_internal = OatFileBase::OpenOatFile<ElfOatFile>(filename,
902 location,
903 requested_base,
904 oat_file_begin,
905 false,
906 executable,
907 abs_dex_location,
908 error_msg);
909 return with_internal;
910}
911
912OatFile* OatFile::OpenWritable(File* file,
913 const std::string& location,
914 const char* abs_dex_location,
915 std::string* error_msg) {
916 CheckLocation(location);
917 return ElfOatFile::OpenElfFile(file,
918 location,
919 nullptr,
920 nullptr,
921 true,
922 false,
923 abs_dex_location,
924 error_msg);
925}
926
927OatFile* OatFile::OpenReadable(File* file,
928 const std::string& location,
929 const char* abs_dex_location,
930 std::string* error_msg) {
931 CheckLocation(location);
932 return ElfOatFile::OpenElfFile(file,
933 location,
934 nullptr,
935 nullptr,
936 false,
937 false,
938 abs_dex_location,
939 error_msg);
940}
941
942OatFile::OatFile(const std::string& location, bool is_executable)
943 : location_(location),
944 begin_(nullptr),
945 end_(nullptr),
946 bss_begin_(nullptr),
947 bss_end_(nullptr),
948 is_executable_(is_executable),
949 secondary_lookup_lock_("OatFile secondary lookup lock", kOatFileSecondaryLookupLock) {
950 CHECK(!location_.empty());
951}
952
953OatFile::~OatFile() {
954 STLDeleteElements(&oat_dex_files_storage_);
955}
956
Brian Carlstrome24fa612011-09-29 00:53:55 -0700957const OatHeader& OatFile::GetOatHeader() const {
Ian Rogers30fab402012-01-23 15:43:46 -0800958 return *reinterpret_cast<const OatHeader*>(Begin());
Brian Carlstrome24fa612011-09-29 00:53:55 -0700959}
960
Ian Rogers13735952014-10-08 12:43:28 -0700961const uint8_t* OatFile::Begin() const {
Andreas Gampefa8429b2015-04-07 18:34:42 -0700962 CHECK(begin_ != nullptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800963 return begin_;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700964}
965
Ian Rogers13735952014-10-08 12:43:28 -0700966const uint8_t* OatFile::End() const {
Andreas Gampefa8429b2015-04-07 18:34:42 -0700967 CHECK(end_ != nullptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800968 return end_;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700969}
970
Vladimir Marko5c42c292015-02-25 12:02:49 +0000971const uint8_t* OatFile::BssBegin() const {
972 return bss_begin_;
973}
974
975const uint8_t* OatFile::BssEnd() const {
976 return bss_end_;
977}
978
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700979const OatFile::OatDexFile* OatFile::GetOatDexFile(const char* dex_location,
980 const uint32_t* dex_location_checksum,
Ian Rogers7fe2c692011-12-06 16:35:59 -0800981 bool warn_if_not_found) const {
Vladimir Marko3f5838d2014-08-07 18:07:18 +0100982 // NOTE: We assume here that the canonical location for a given dex_location never
983 // changes. If it does (i.e. some symlink used by the filename changes) we may return
984 // an incorrect OatDexFile. As long as we have a checksum to check, we shall return
985 // an identical file or fail; otherwise we may see some unpredictable failures.
Calin Juravle4e1d5792014-07-15 23:56:47 +0100986
Vladimir Marko3f5838d2014-08-07 18:07:18 +0100987 // TODO: Additional analysis of usage patterns to see if this can be simplified
988 // without any performance loss, for example by not doing the first lock-free lookup.
989
990 const OatFile::OatDexFile* oat_dex_file = nullptr;
991 StringPiece key(dex_location);
992 // Try to find the key cheaply in the oat_dex_files_ map which holds dex locations
993 // directly mentioned in the oat file and doesn't require locking.
994 auto primary_it = oat_dex_files_.find(key);
995 if (primary_it != oat_dex_files_.end()) {
996 oat_dex_file = primary_it->second;
997 DCHECK(oat_dex_file != nullptr);
998 } else {
999 // This dex_location is not one of the dex locations directly mentioned in the
1000 // oat file. The correct lookup is via the canonical location but first see in
1001 // the secondary_oat_dex_files_ whether we've looked up this location before.
1002 MutexLock mu(Thread::Current(), secondary_lookup_lock_);
1003 auto secondary_lb = secondary_oat_dex_files_.lower_bound(key);
1004 if (secondary_lb != secondary_oat_dex_files_.end() && key == secondary_lb->first) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001005 oat_dex_file = secondary_lb->second; // May be null.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001006 } else {
1007 // We haven't seen this dex_location before, we must check the canonical location.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001008 std::string dex_canonical_location = DexFile::GetDexCanonicalLocation(dex_location);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001009 if (dex_canonical_location != dex_location) {
1010 StringPiece canonical_key(dex_canonical_location);
1011 auto canonical_it = oat_dex_files_.find(canonical_key);
1012 if (canonical_it != oat_dex_files_.end()) {
1013 oat_dex_file = canonical_it->second;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001014 } // else keep null.
1015 } // else keep null.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001016
1017 // Copy the key to the string_cache_ and store the result in secondary map.
1018 string_cache_.emplace_back(key.data(), key.length());
1019 StringPiece key_copy(string_cache_.back());
1020 secondary_oat_dex_files_.PutBefore(secondary_lb, key_copy, oat_dex_file);
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001021 }
1022 }
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001023 if (oat_dex_file != nullptr &&
1024 (dex_location_checksum == nullptr ||
1025 oat_dex_file->GetDexFileLocationChecksum() == *dex_location_checksum)) {
1026 return oat_dex_file;
1027 }
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001028
1029 if (warn_if_not_found) {
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001030 std::string dex_canonical_location = DexFile::GetDexCanonicalLocation(dex_location);
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001031 std::string checksum("<unspecified>");
Andreas Gampefa8429b2015-04-07 18:34:42 -07001032 if (dex_location_checksum != nullptr) {
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001033 checksum = StringPrintf("0x%08x", *dex_location_checksum);
1034 }
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001035 LOG(WARNING) << "Failed to find OatDexFile for DexFile " << dex_location
Calin Juravle4e1d5792014-07-15 23:56:47 +01001036 << " ( canonical path " << dex_canonical_location << ")"
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001037 << " with checksum " << checksum << " in OatFile " << GetLocation();
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001038 if (kIsDebugBuild) {
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001039 for (const OatDexFile* odf : oat_dex_files_storage_) {
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001040 LOG(WARNING) << "OatFile " << GetLocation()
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001041 << " contains OatDexFile " << odf->GetDexFileLocation()
1042 << " (canonical path " << odf->GetCanonicalDexFileLocation() << ")"
1043 << " with checksum 0x" << std::hex << odf->GetDexFileLocationChecksum();
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001044 }
Ian Rogers7fe2c692011-12-06 16:35:59 -08001045 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001046 }
Calin Juravle4e1d5792014-07-15 23:56:47 +01001047
Andreas Gampefa8429b2015-04-07 18:34:42 -07001048 return nullptr;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001049}
1050
Brian Carlstrome24fa612011-09-29 00:53:55 -07001051OatFile::OatDexFile::OatDexFile(const OatFile* oat_file,
Elliott Hughesaa6a5882012-01-13 19:39:16 -08001052 const std::string& dex_file_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001053 const std::string& canonical_dex_file_location,
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001054 uint32_t dex_file_location_checksum,
Ian Rogers13735952014-10-08 12:43:28 -07001055 const uint8_t* dex_file_pointer,
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001056 const uint8_t* lookup_table_data,
Vladimir Marko09d09432015-09-08 13:47:48 +01001057 const uint32_t* oat_class_offsets_pointer,
Vladimir Marko06d7aaa2015-10-16 11:23:41 +01001058 uint8_t* dex_cache_arrays)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001059 : oat_file_(oat_file),
1060 dex_file_location_(dex_file_location),
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001061 canonical_dex_file_location_(canonical_dex_file_location),
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001062 dex_file_location_checksum_(dex_file_location_checksum),
Brian Carlstrom89521892011-12-07 22:05:07 -08001063 dex_file_pointer_(dex_file_pointer),
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001064 lookup_table_data_(lookup_table_data),
Vladimir Marko09d09432015-09-08 13:47:48 +01001065 oat_class_offsets_pointer_(oat_class_offsets_pointer),
1066 dex_cache_arrays_(dex_cache_arrays) {}
Brian Carlstrome24fa612011-09-29 00:53:55 -07001067
1068OatFile::OatDexFile::~OatDexFile() {}
1069
Ian Rogers05f28c62012-10-23 18:12:13 -07001070size_t OatFile::OatDexFile::FileSize() const {
1071 return reinterpret_cast<const DexFile::Header*>(dex_file_pointer_)->file_size_;
1072}
1073
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001074std::unique_ptr<const DexFile> OatFile::OatDexFile::OpenDexFile(std::string* error_msg) const {
Ian Rogers05f28c62012-10-23 18:12:13 -07001075 return DexFile::Open(dex_file_pointer_, FileSize(), dex_file_location_,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001076 dex_file_location_checksum_, this, error_msg);
Brian Carlstrom89521892011-12-07 22:05:07 -08001077}
1078
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001079uint32_t OatFile::OatDexFile::GetOatClassOffset(uint16_t class_def_index) const {
1080 return oat_class_offsets_pointer_[class_def_index];
1081}
1082
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001083OatFile::OatClass OatFile::OatDexFile::GetOatClass(uint16_t class_def_index) const {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001084 uint32_t oat_class_offset = GetOatClassOffset(class_def_index);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001085
Ian Rogers13735952014-10-08 12:43:28 -07001086 const uint8_t* oat_class_pointer = oat_file_->Begin() + oat_class_offset;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001087 CHECK_LT(oat_class_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001088
Ian Rogers13735952014-10-08 12:43:28 -07001089 const uint8_t* status_pointer = oat_class_pointer;
Brian Carlstromba150c32013-08-27 17:31:03 -07001090 CHECK_LT(status_pointer, oat_file_->End()) << oat_file_->GetLocation();
1091 mirror::Class::Status status =
1092 static_cast<mirror::Class::Status>(*reinterpret_cast<const int16_t*>(status_pointer));
1093 CHECK_LT(status, mirror::Class::kStatusMax);
1094
Ian Rogers13735952014-10-08 12:43:28 -07001095 const uint8_t* type_pointer = status_pointer + sizeof(uint16_t);
Brian Carlstromba150c32013-08-27 17:31:03 -07001096 CHECK_LT(type_pointer, oat_file_->End()) << oat_file_->GetLocation();
1097 OatClassType type = static_cast<OatClassType>(*reinterpret_cast<const uint16_t*>(type_pointer));
1098 CHECK_LT(type, kOatClassMax);
1099
Ian Rogers13735952014-10-08 12:43:28 -07001100 const uint8_t* after_type_pointer = type_pointer + sizeof(int16_t);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001101 CHECK_LE(after_type_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07001102
Brian Carlstromcd937a92014-03-04 22:53:23 -08001103 uint32_t bitmap_size = 0;
Ian Rogers13735952014-10-08 12:43:28 -07001104 const uint8_t* bitmap_pointer = nullptr;
1105 const uint8_t* methods_pointer = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07001106 if (type != kOatClassNoneCompiled) {
1107 if (type == kOatClassSomeCompiled) {
1108 bitmap_size = static_cast<uint32_t>(*reinterpret_cast<const uint32_t*>(after_type_pointer));
1109 bitmap_pointer = after_type_pointer + sizeof(bitmap_size);
1110 CHECK_LE(bitmap_pointer, oat_file_->End()) << oat_file_->GetLocation();
1111 methods_pointer = bitmap_pointer + bitmap_size;
1112 } else {
1113 methods_pointer = after_type_pointer;
1114 }
1115 CHECK_LE(methods_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstromcd937a92014-03-04 22:53:23 -08001116 }
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001117
Richard Uhler07b3c232015-03-31 15:57:54 -07001118 return OatFile::OatClass(oat_file_,
1119 status,
1120 type,
1121 bitmap_size,
1122 reinterpret_cast<const uint32_t*>(bitmap_pointer),
1123 reinterpret_cast<const OatMethodOffsets*>(methods_pointer));
Brian Carlstrome24fa612011-09-29 00:53:55 -07001124}
1125
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001126OatFile::OatClass::OatClass(const OatFile* oat_file,
Ian Rogers2dd0e2c2013-01-24 12:42:14 -08001127 mirror::Class::Status status,
Brian Carlstromba150c32013-08-27 17:31:03 -07001128 OatClassType type,
1129 uint32_t bitmap_size,
1130 const uint32_t* bitmap_pointer,
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001131 const OatMethodOffsets* methods_pointer)
Brian Carlstromba150c32013-08-27 17:31:03 -07001132 : oat_file_(oat_file), status_(status), type_(type),
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001133 bitmap_(bitmap_pointer), methods_pointer_(methods_pointer) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001134 switch (type_) {
1135 case kOatClassAllCompiled: {
1136 CHECK_EQ(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001137 CHECK(bitmap_pointer == nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001138 CHECK(methods_pointer != nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001139 break;
1140 }
1141 case kOatClassSomeCompiled: {
1142 CHECK_NE(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001143 CHECK(bitmap_pointer != nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001144 CHECK(methods_pointer != nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001145 break;
1146 }
1147 case kOatClassNoneCompiled: {
1148 CHECK_EQ(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001149 CHECK(bitmap_pointer == nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001150 CHECK(methods_pointer_ == nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001151 break;
1152 }
1153 case kOatClassMax: {
1154 LOG(FATAL) << "Invalid OatClassType " << type_;
1155 break;
1156 }
1157 }
1158}
Brian Carlstrome24fa612011-09-29 00:53:55 -07001159
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001160uint32_t OatFile::OatClass::GetOatMethodOffsetsOffset(uint32_t method_index) const {
1161 const OatMethodOffsets* oat_method_offsets = GetOatMethodOffsets(method_index);
1162 if (oat_method_offsets == nullptr) {
1163 return 0u;
1164 }
1165 return reinterpret_cast<const uint8_t*>(oat_method_offsets) - oat_file_->Begin();
1166}
1167
1168const OatMethodOffsets* OatFile::OatClass::GetOatMethodOffsets(uint32_t method_index) const {
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001169 // 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 -07001170 if (methods_pointer_ == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001171 CHECK_EQ(kOatClassNoneCompiled, type_);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001172 return nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07001173 }
1174 size_t methods_pointer_index;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001175 if (bitmap_ == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001176 CHECK_EQ(kOatClassAllCompiled, type_);
1177 methods_pointer_index = method_index;
1178 } else {
1179 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001180 if (!BitVector::IsBitSet(bitmap_, method_index)) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001181 return nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07001182 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001183 size_t num_set_bits = BitVector::NumSetBits(bitmap_, method_index);
1184 methods_pointer_index = num_set_bits;
Brian Carlstromba150c32013-08-27 17:31:03 -07001185 }
1186 const OatMethodOffsets& oat_method_offsets = methods_pointer_[methods_pointer_index];
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001187 return &oat_method_offsets;
1188}
1189
1190const OatFile::OatMethod OatFile::OatClass::GetOatMethod(uint32_t method_index) const {
1191 const OatMethodOffsets* oat_method_offsets = GetOatMethodOffsets(method_index);
1192 if (oat_method_offsets == nullptr) {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001193 return OatMethod(nullptr, 0);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001194 }
1195 if (oat_file_->IsExecutable() ||
1196 Runtime::Current() == nullptr || // This case applies for oatdump.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001197 Runtime::Current()->IsAotCompiler()) {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001198 return OatMethod(oat_file_->Begin(), oat_method_offsets->code_offset_);
Alex Light9dcc4572014-08-14 14:16:26 -07001199 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001200 // We aren't allowed to use the compiled code. We just force it down the interpreted / jit
1201 // version.
1202 return OatMethod(oat_file_->Begin(), 0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001203}
1204
Mathieu Chartiere401d142015-04-22 13:56:20 -07001205void OatFile::OatMethod::LinkMethod(ArtMethod* method) const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001206 CHECK(method != nullptr);
Ian Rogersef7d42f2014-01-06 12:55:46 -08001207 method->SetEntryPointFromQuickCompiledCode(GetQuickCode());
Brian Carlstromae826982011-11-09 01:33:42 -08001208}
1209
Andreas Gampe7ba64962014-10-23 11:37:40 -07001210bool OatFile::IsPic() const {
Igor Murashkin46774762014-10-22 11:37:02 -07001211 return GetOatHeader().IsPic();
Andreas Gampe7ba64962014-10-23 11:37:40 -07001212 // TODO: Check against oat_patches. b/18144996
1213}
1214
Sebastien Hertz0de11332015-05-13 12:14:05 +02001215bool OatFile::IsDebuggable() const {
1216 return GetOatHeader().IsDebuggable();
1217}
1218
Andreas Gampe7848da42015-04-09 11:15:04 -07001219static constexpr char kDexClassPathEncodingSeparator = '*';
1220
1221std::string OatFile::EncodeDexFileDependencies(const std::vector<const DexFile*>& dex_files) {
1222 std::ostringstream out;
1223
1224 for (const DexFile* dex_file : dex_files) {
1225 out << dex_file->GetLocation().c_str();
1226 out << kDexClassPathEncodingSeparator;
1227 out << dex_file->GetLocationChecksum();
1228 out << kDexClassPathEncodingSeparator;
1229 }
1230
1231 return out.str();
1232}
1233
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001234bool OatFile::CheckStaticDexFileDependencies(const char* dex_dependencies, std::string* msg) {
Andreas Gampe7848da42015-04-09 11:15:04 -07001235 if (dex_dependencies == nullptr || dex_dependencies[0] == 0) {
1236 // No dependencies.
1237 return true;
1238 }
1239
1240 // Assumption: this is not performance-critical. So it's OK to do this with a std::string and
1241 // Split() instead of manual parsing of the combined char*.
1242 std::vector<std::string> split;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001243 Split(dex_dependencies, kDexClassPathEncodingSeparator, &split);
Andreas Gampe7848da42015-04-09 11:15:04 -07001244 if (split.size() % 2 != 0) {
1245 // Expected pairs of location and checksum.
1246 *msg = StringPrintf("Odd number of elements in dependency list %s", dex_dependencies);
1247 return false;
1248 }
1249
1250 for (auto it = split.begin(), end = split.end(); it != end; it += 2) {
1251 std::string& location = *it;
1252 std::string& checksum = *(it + 1);
1253 int64_t converted = strtoll(checksum.c_str(), nullptr, 10);
1254 if (converted == 0) {
1255 // Conversion error.
1256 *msg = StringPrintf("Conversion error for %s", checksum.c_str());
1257 return false;
1258 }
1259
1260 uint32_t dex_checksum;
1261 std::string error_msg;
1262 if (DexFile::GetChecksum(DexFile::GetDexCanonicalLocation(location.c_str()).c_str(),
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001263 &dex_checksum,
1264 &error_msg)) {
Andreas Gampe7848da42015-04-09 11:15:04 -07001265 if (converted != dex_checksum) {
1266 *msg = StringPrintf("Checksums don't match for %s: %" PRId64 " vs %u",
1267 location.c_str(), converted, dex_checksum);
1268 return false;
1269 }
1270 } else {
1271 // Problem retrieving checksum.
1272 // TODO: odex files?
1273 *msg = StringPrintf("Could not retrieve checksum for %s: %s", location.c_str(),
1274 error_msg.c_str());
1275 return false;
1276 }
1277 }
1278
1279 return true;
1280}
1281
1282bool OatFile::GetDexLocationsFromDependencies(const char* dex_dependencies,
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001283 std::vector<std::string>* locations) {
1284 DCHECK(locations != nullptr);
Andreas Gampe7848da42015-04-09 11:15:04 -07001285 if (dex_dependencies == nullptr || dex_dependencies[0] == 0) {
1286 return true;
1287 }
1288
1289 // Assumption: this is not performance-critical. So it's OK to do this with a std::string and
1290 // Split() instead of manual parsing of the combined char*.
1291 std::vector<std::string> split;
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001292 Split(dex_dependencies, kDexClassPathEncodingSeparator, &split);
Andreas Gampe7848da42015-04-09 11:15:04 -07001293 if (split.size() % 2 != 0) {
1294 // Expected pairs of location and checksum.
1295 return false;
1296 }
1297
1298 for (auto it = split.begin(), end = split.end(); it != end; it += 2) {
1299 locations->push_back(*it);
1300 }
1301
1302 return true;
1303}
1304
Brian Carlstrome24fa612011-09-29 00:53:55 -07001305} // namespace art