blob: ffbc26c647d9141d8d8c710ae225f42566451703 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Brian Carlstrome24fa612011-09-29 00:53:55 -070016
17#include "oat_file.h"
18
Brian Carlstrom700c8d32012-11-05 10:42:02 -080019#include <dlfcn.h>
David Srbecky1baabf02015-06-16 17:12:34 +000020#ifndef __APPLE__
21#include <link.h> // for dl_iterate_phdr.
22#endif
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070023#include <unistd.h>
24
25#include <cstdlib>
26#include <cstring>
Richard Uhlere5fed032015-03-18 08:21:11 -070027#include <sstream>
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070028#include <type_traits>
Shubham Ajmerab22dea02017-10-04 18:36:41 -070029#include <sys/stat.h>
Richard Uhlere5fed032015-03-18 08:21:11 -070030
Andreas Gampefa8429b2015-04-07 18:34:42 -070031// dlopen_ext support from bionic.
Bilyan Borisovbb661c02016-04-04 16:27:32 +010032#ifdef ART_TARGET_ANDROID
Andreas Gampefa8429b2015-04-07 18:34:42 -070033#include "android/dlext.h"
34#endif
35
Andreas Gampe46ee31b2016-12-14 10:11:49 -080036#include "android-base/stringprintf.h"
37
Andreas Gampec6ea7d02017-02-01 16:46:28 -080038#include "art_method.h"
Brian Carlstromba150c32013-08-27 17:31:03 -070039#include "base/bit_vector.h"
Andreas Gampe542451c2016-07-26 09:02:02 -070040#include "base/enums.h"
David Sehr891a50e2017-10-27 17:01:07 -070041#include "base/file_utils.h"
Andreas Gampe170331f2017-12-07 18:41:03 -080042#include "base/logging.h" // For VLOG_IS_ON.
David Sehr79e26072018-04-06 17:58:50 -070043#include "base/mem_map.h"
David Sehrc431b9d2018-03-02 12:01:51 -080044#include "base/os.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080045#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080046#include "base/systrace.h"
Elliott Hughes76160052012-12-12 16:31:20 -080047#include "base/unix_file/fd_file.h"
David Sehrc431b9d2018-03-02 12:01:51 -080048#include "base/utils.h"
David Sehr013fd802018-01-11 22:55:24 -080049#include "dex/art_dex_file_loader.h"
David Sehr9e734c72018-01-04 17:56:19 -080050#include "dex/dex_file_loader.h"
51#include "dex/dex_file_types.h"
52#include "dex/standard_dex_file.h"
David Sehr9c4a0152018-04-05 12:23:54 -070053#include "dex/type_lookup_table.h"
David Sehr0225f8e2018-01-31 08:52:24 +000054#include "dex/utf-inl.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080055#include "elf_file.h"
Alex Light84d76052014-08-22 17:49:35 -070056#include "elf_utils.h"
Vladimir Markoaad75c62016-10-03 08:46:48 +000057#include "gc_root.h"
Vladimir Marko6cfbdbc2017-07-25 13:26:39 +010058#include "gc/space/image_space.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080059#include "mirror/class.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070060#include "mirror/object-inl.h"
Andreas Gampe8cf9cb32017-07-19 09:28:38 -070061#include "oat.h"
Nicolas Geoffrayc04c8002015-07-14 11:37:54 +010062#include "oat_file-inl.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070063#include "oat_file_manager.h"
Andreas Gampe22f8e5c2014-07-09 11:38:21 -070064#include "runtime.h"
Vladimir Marko97d7e1c2016-10-04 14:44:28 +010065#include "vdex_file.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070066
67namespace art {
68
Andreas Gampe46ee31b2016-12-14 10:11:49 -080069using android::base::StringPrintf;
70
Andreas Gampe049cff02015-12-01 23:27:12 -080071// Whether OatFile::Open will try dlopen. Fallback is our own ELF loader.
David Srbecky1baabf02015-06-16 17:12:34 +000072static constexpr bool kUseDlopen = true;
Andreas Gampefa8429b2015-04-07 18:34:42 -070073
Andreas Gampe049cff02015-12-01 23:27:12 -080074// Whether OatFile::Open will try dlopen on the host. On the host we're not linking against
Andreas Gampefa8429b2015-04-07 18:34:42 -070075// bionic, so cannot take advantage of the support for changed semantics (loading the same soname
76// multiple times). However, if/when we switch the above, we likely want to switch this, too,
77// to get test coverage of the code paths.
David Srbecky1baabf02015-06-16 17:12:34 +000078static constexpr bool kUseDlopenOnHost = true;
Andreas Gampefa8429b2015-04-07 18:34:42 -070079
80// For debugging, Open will print DlOpen error message if set to true.
81static constexpr bool kPrintDlOpenErrorMessage = false;
82
Andreas Gampe049cff02015-12-01 23:27:12 -080083// Note for OatFileBase and descendents:
84//
85// These are used in OatFile::Open to try all our loaders.
86//
87// The process is simple:
88//
89// 1) Allocate an instance through the standard constructor (location, executable)
90// 2) Load() to try to open the file.
91// 3) ComputeFields() to populate the OatFile fields like begin_, using FindDynamicSymbolAddress.
92// 4) PreSetup() for any steps that should be done before the final setup.
93// 5) Setup() to complete the procedure.
Richard Uhlere5fed032015-03-18 08:21:11 -070094
Andreas Gampe049cff02015-12-01 23:27:12 -080095class OatFileBase : public OatFile {
96 public:
97 virtual ~OatFileBase() {}
Richard Uhlere5fed032015-03-18 08:21:11 -070098
Andreas Gampe049cff02015-12-01 23:27:12 -080099 template <typename kOatFileBaseSubType>
Nicolas Geoffray30025092018-04-19 14:43:29 +0100100 static OatFileBase* OpenOatFile(int zip_fd,
101 const std::string& vdex_filename,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100102 const std::string& elf_filename,
Alex Light84d76052014-08-22 17:49:35 -0700103 const std::string& location,
Andreas Gampe049cff02015-12-01 23:27:12 -0800104 uint8_t* requested_base,
105 uint8_t* oat_file_begin,
106 bool writable,
107 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800108 bool low_4gb,
Richard Uhlere5fed032015-03-18 08:21:11 -0700109 const char* abs_dex_location,
Andreas Gampe049cff02015-12-01 23:27:12 -0800110 std::string* error_msg);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800111
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700112 template <typename kOatFileBaseSubType>
Nicolas Geoffray30025092018-04-19 14:43:29 +0100113 static OatFileBase* OpenOatFile(int zip_fd,
114 int vdex_fd,
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700115 int oat_fd,
116 const std::string& vdex_filename,
117 const std::string& oat_filename,
118 uint8_t* requested_base,
119 uint8_t* oat_file_begin,
120 bool writable,
121 bool executable,
122 bool low_4gb,
123 const char* abs_dex_location,
124 std::string* error_msg);
125
Andreas Gampe049cff02015-12-01 23:27:12 -0800126 protected:
127 OatFileBase(const std::string& filename, bool executable) : OatFile(filename, executable) {}
Andreas Gampefa8429b2015-04-07 18:34:42 -0700128
Andreas Gampe049cff02015-12-01 23:27:12 -0800129 virtual const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
130 std::string* error_msg) const = 0;
131
Andreas Gampe4075f832016-05-18 13:09:54 -0700132 virtual void PreLoad() = 0;
133
David Brazdil7b49e6c2016-09-01 11:06:18 +0100134 bool LoadVdex(const std::string& vdex_filename,
135 bool writable,
136 bool low_4gb,
137 std::string* error_msg);
138
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700139 bool LoadVdex(int vdex_fd,
140 const std::string& vdex_filename,
141 bool writable,
142 bool low_4gb,
143 std::string* error_msg);
144
Andreas Gampe049cff02015-12-01 23:27:12 -0800145 virtual bool Load(const std::string& elf_filename,
146 uint8_t* oat_file_begin,
147 bool writable,
148 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800149 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800150 std::string* error_msg) = 0;
151
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700152 virtual bool Load(int oat_fd,
153 uint8_t* oat_file_begin,
154 bool writable,
155 bool executable,
156 bool low_4gb,
157 std::string* error_msg) = 0;
158
Andreas Gampe049cff02015-12-01 23:27:12 -0800159 bool ComputeFields(uint8_t* requested_base,
160 const std::string& file_path,
161 std::string* error_msg);
162
163 virtual void PreSetup(const std::string& elf_filename) = 0;
164
Nicolas Geoffray30025092018-04-19 14:43:29 +0100165 bool Setup(int zip_fd, const char* abs_dex_location, std::string* error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -0800166
167 // Setters exposed for ElfOatFile.
168
169 void SetBegin(const uint8_t* begin) {
170 begin_ = begin;
Andreas Gampefa8429b2015-04-07 18:34:42 -0700171 }
172
Andreas Gampe049cff02015-12-01 23:27:12 -0800173 void SetEnd(const uint8_t* end) {
174 end_ = end;
175 }
176
David Brazdilc93b3be2016-09-12 18:49:58 +0100177 void SetVdex(VdexFile* vdex) {
178 vdex_.reset(vdex);
179 }
180
Andreas Gampe049cff02015-12-01 23:27:12 -0800181 private:
182 DISALLOW_COPY_AND_ASSIGN(OatFileBase);
183};
184
185template <typename kOatFileBaseSubType>
Nicolas Geoffray30025092018-04-19 14:43:29 +0100186OatFileBase* OatFileBase::OpenOatFile(int zip_fd,
187 const std::string& vdex_filename,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100188 const std::string& elf_filename,
Andreas Gampe049cff02015-12-01 23:27:12 -0800189 const std::string& location,
190 uint8_t* requested_base,
191 uint8_t* oat_file_begin,
192 bool writable,
193 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800194 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800195 const char* abs_dex_location,
196 std::string* error_msg) {
197 std::unique_ptr<OatFileBase> ret(new kOatFileBaseSubType(location, executable));
Andreas Gampe4075f832016-05-18 13:09:54 -0700198
199 ret->PreLoad();
200
Andreas Gampe049cff02015-12-01 23:27:12 -0800201 if (!ret->Load(elf_filename,
202 oat_file_begin,
203 writable,
204 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800205 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800206 error_msg)) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800207 return nullptr;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800208 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800209
Andreas Gampe049cff02015-12-01 23:27:12 -0800210 if (!ret->ComputeFields(requested_base, elf_filename, error_msg)) {
211 return nullptr;
212 }
Andreas Gampe4075f832016-05-18 13:09:54 -0700213
David Sehr2300b2d2018-05-10 14:20:10 -0700214 ret->PreSetup(elf_filename);
215
David Srbeckyec2cdf42017-12-08 16:21:25 +0000216 if (!ret->LoadVdex(vdex_filename, writable, low_4gb, error_msg)) {
217 return nullptr;
218 }
219
Nicolas Geoffray30025092018-04-19 14:43:29 +0100220 if (!ret->Setup(zip_fd, abs_dex_location, error_msg)) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800221 return nullptr;
222 }
223
Dave Allison69dfe512014-07-11 17:11:58 +0000224 return ret.release();
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800225}
226
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700227template <typename kOatFileBaseSubType>
Nicolas Geoffray30025092018-04-19 14:43:29 +0100228OatFileBase* OatFileBase::OpenOatFile(int zip_fd,
229 int vdex_fd,
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700230 int oat_fd,
231 const std::string& vdex_location,
232 const std::string& oat_location,
233 uint8_t* requested_base,
234 uint8_t* oat_file_begin,
235 bool writable,
236 bool executable,
237 bool low_4gb,
238 const char* abs_dex_location,
239 std::string* error_msg) {
240 std::unique_ptr<OatFileBase> ret(new kOatFileBaseSubType(oat_location, executable));
241
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700242 if (!ret->Load(oat_fd,
243 oat_file_begin,
244 writable,
245 executable,
246 low_4gb,
247 error_msg)) {
248 return nullptr;
249 }
250
251 if (!ret->ComputeFields(requested_base, oat_location, error_msg)) {
252 return nullptr;
253 }
254
David Sehr2300b2d2018-05-10 14:20:10 -0700255 ret->PreSetup(oat_location);
256
David Srbeckyec2cdf42017-12-08 16:21:25 +0000257 if (!ret->LoadVdex(vdex_fd, vdex_location, writable, low_4gb, error_msg)) {
258 return nullptr;
259 }
260
Nicolas Geoffray30025092018-04-19 14:43:29 +0100261 if (!ret->Setup(zip_fd, abs_dex_location, error_msg)) {
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700262 return nullptr;
263 }
264
265 return ret.release();
266}
267
David Brazdil7b49e6c2016-09-01 11:06:18 +0100268bool OatFileBase::LoadVdex(const std::string& vdex_filename,
269 bool writable,
270 bool low_4gb,
271 std::string* error_msg) {
David Srbeckyec2cdf42017-12-08 16:21:25 +0000272 vdex_ = VdexFile::OpenAtAddress(vdex_begin_,
273 vdex_end_ - vdex_begin_,
Andreas Gampec1fc4492018-01-10 14:19:36 -0800274 vdex_begin_ != nullptr /* mmap_reuse */,
David Srbeckyec2cdf42017-12-08 16:21:25 +0000275 vdex_filename,
276 writable,
277 low_4gb,
278 /* unquicken*/ false,
279 error_msg);
David Brazdil7b49e6c2016-09-01 11:06:18 +0100280 if (vdex_.get() == nullptr) {
281 *error_msg = StringPrintf("Failed to load vdex file '%s' %s",
282 vdex_filename.c_str(),
283 error_msg->c_str());
284 return false;
285 }
286 return true;
287}
288
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700289bool OatFileBase::LoadVdex(int vdex_fd,
290 const std::string& vdex_filename,
291 bool writable,
292 bool low_4gb,
293 std::string* error_msg) {
294 if (vdex_fd != -1) {
295 struct stat s;
296 int rc = TEMP_FAILURE_RETRY(fstat(vdex_fd, &s));
297 if (rc == -1) {
298 PLOG(WARNING) << "Failed getting length of vdex file";
299 } else {
David Srbeckyec2cdf42017-12-08 16:21:25 +0000300 vdex_ = VdexFile::OpenAtAddress(vdex_begin_,
301 vdex_end_ - vdex_begin_,
Andreas Gampec1fc4492018-01-10 14:19:36 -0800302 vdex_begin_ != nullptr /* mmap_reuse */,
David Srbeckyec2cdf42017-12-08 16:21:25 +0000303 vdex_fd,
304 s.st_size,
305 vdex_filename,
306 writable,
307 low_4gb,
308 false /* unquicken */,
309 error_msg);
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700310 if (vdex_.get() == nullptr) {
311 *error_msg = "Failed opening vdex file.";
312 return false;
313 }
314 }
315 }
316 return true;
317}
318
Andreas Gampe049cff02015-12-01 23:27:12 -0800319bool OatFileBase::ComputeFields(uint8_t* requested_base,
320 const std::string& file_path,
321 std::string* error_msg) {
322 std::string symbol_error_msg;
323 begin_ = FindDynamicSymbolAddress("oatdata", &symbol_error_msg);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700324 if (begin_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800325 *error_msg = StringPrintf("Failed to find oatdata symbol in '%s' %s",
326 file_path.c_str(),
327 symbol_error_msg.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700328 return false;
329 }
330 if (requested_base != nullptr && begin_ != requested_base) {
Nicolas Geoffrayf97cf2a2016-03-09 15:36:23 +0000331 // Host can fail this check. Do not dump there to avoid polluting the output.
Andreas Gampe7ec09042016-04-01 17:20:49 -0700332 if (kIsTargetBuild && (kIsDebugBuild || VLOG_IS_ON(oat))) {
Andreas Gampe170331f2017-12-07 18:41:03 -0800333 PrintFileToLog("/proc/self/maps", android::base::LogSeverity::WARNING);
Nicolas Geoffrayf97cf2a2016-03-09 15:36:23 +0000334 }
Andreas Gampefa8429b2015-04-07 18:34:42 -0700335 *error_msg = StringPrintf("Failed to find oatdata symbol at expected address: "
Andreas Gampe049cff02015-12-01 23:27:12 -0800336 "oatdata=%p != expected=%p. See process maps in the log.",
337 begin_, requested_base);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700338 return false;
339 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800340 end_ = FindDynamicSymbolAddress("oatlastword", &symbol_error_msg);
Andreas Gampefa8429b2015-04-07 18:34:42 -0700341 if (end_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800342 *error_msg = StringPrintf("Failed to find oatlastword symbol in '%s' %s",
343 file_path.c_str(),
344 symbol_error_msg.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700345 return false;
346 }
347 // Readjust to be non-inclusive upper bound.
348 end_ += sizeof(uint32_t);
349
Vladimir Markob066d432018-01-03 13:14:37 +0000350 data_bimg_rel_ro_begin_ = FindDynamicSymbolAddress("oatdatabimgrelro", &symbol_error_msg);
351 if (data_bimg_rel_ro_begin_ != nullptr) {
352 data_bimg_rel_ro_end_ =
353 FindDynamicSymbolAddress("oatdatabimgrelrolastword", &symbol_error_msg);
354 if (data_bimg_rel_ro_end_ == nullptr) {
355 *error_msg =
356 StringPrintf("Failed to find oatdatabimgrelrolastword symbol in '%s'", file_path.c_str());
357 return false;
358 }
359 // Readjust to be non-inclusive upper bound.
360 data_bimg_rel_ro_end_ += sizeof(uint32_t);
361 }
362
Andreas Gampe049cff02015-12-01 23:27:12 -0800363 bss_begin_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbss", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700364 if (bss_begin_ == nullptr) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800365 // No .bss section.
Andreas Gampefa8429b2015-04-07 18:34:42 -0700366 bss_end_ = nullptr;
Andreas Gampefa8429b2015-04-07 18:34:42 -0700367 } else {
Andreas Gampe049cff02015-12-01 23:27:12 -0800368 bss_end_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbsslastword", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700369 if (bss_end_ == nullptr) {
David Srbeckyec2cdf42017-12-08 16:21:25 +0000370 *error_msg = StringPrintf("Failed to find oatbsslastword symbol in '%s'", file_path.c_str());
Andreas Gampefa8429b2015-04-07 18:34:42 -0700371 return false;
372 }
373 // Readjust to be non-inclusive upper bound.
374 bss_end_ += sizeof(uint32_t);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100375 // Find bss methods if present.
376 bss_methods_ =
377 const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbssmethods", &symbol_error_msg));
Vladimir Markoaad75c62016-10-03 08:46:48 +0000378 // Find bss roots if present.
379 bss_roots_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatbssroots", &symbol_error_msg));
Andreas Gampefa8429b2015-04-07 18:34:42 -0700380 }
381
David Srbeckyec2cdf42017-12-08 16:21:25 +0000382 vdex_begin_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatdex", &symbol_error_msg));
383 if (vdex_begin_ == nullptr) {
384 // No .vdex section.
385 vdex_end_ = nullptr;
386 } else {
387 vdex_end_ = const_cast<uint8_t*>(FindDynamicSymbolAddress("oatdexlastword", &symbol_error_msg));
388 if (vdex_end_ == nullptr) {
389 *error_msg = StringPrintf("Failed to find oatdexlastword symbol in '%s'", file_path.c_str());
390 return false;
391 }
392 // Readjust to be non-inclusive upper bound.
393 vdex_end_ += sizeof(uint32_t);
394 }
395
Andreas Gampe049cff02015-12-01 23:27:12 -0800396 return true;
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800397}
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800398
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100399// Read an unaligned entry from the OatDexFile data in OatFile and advance the read
400// position by the number of bytes read, i.e. sizeof(T).
401// Return true on success, false if the read would go beyond the end of the OatFile.
402template <typename T>
Vladimir Marko722fa982015-10-19 18:18:27 +0100403inline static bool ReadOatDexFileData(const OatFile& oat_file,
404 /*inout*/const uint8_t** oat,
405 /*out*/T* value) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100406 DCHECK(oat != nullptr);
407 DCHECK(value != nullptr);
408 DCHECK_LE(*oat, oat_file.End());
409 if (UNLIKELY(static_cast<size_t>(oat_file.End() - *oat) < sizeof(T))) {
410 return false;
411 }
412 static_assert(std::is_trivial<T>::value, "T must be a trivial type");
413 typedef __attribute__((__aligned__(1))) T unaligned_type;
414 *value = *reinterpret_cast<const unaligned_type*>(*oat);
415 *oat += sizeof(T);
416 return true;
417}
418
Vladimir Markof3c52b42017-11-17 17:32:12 +0000419static bool ReadIndexBssMapping(OatFile* oat_file,
420 /*inout*/const uint8_t** oat,
421 size_t dex_file_index,
422 const std::string& dex_file_location,
423 const char* tag,
424 /*out*/const IndexBssMapping** mapping,
425 std::string* error_msg) {
426 uint32_t index_bss_mapping_offset;
427 if (UNLIKELY(!ReadOatDexFileData(*oat_file, oat, &index_bss_mapping_offset))) {
428 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zd for '%s' truncated "
429 "after %s bss mapping offset",
430 oat_file->GetLocation().c_str(),
431 dex_file_index,
432 dex_file_location.c_str(),
433 tag);
434 return false;
435 }
436 const bool readable_index_bss_mapping_size =
437 index_bss_mapping_offset != 0u &&
438 index_bss_mapping_offset <= oat_file->Size() &&
439 IsAligned<alignof(IndexBssMapping)>(index_bss_mapping_offset) &&
440 oat_file->Size() - index_bss_mapping_offset >= IndexBssMapping::ComputeSize(0);
441 const IndexBssMapping* index_bss_mapping = readable_index_bss_mapping_size
442 ? reinterpret_cast<const IndexBssMapping*>(oat_file->Begin() + index_bss_mapping_offset)
443 : nullptr;
444 if (index_bss_mapping_offset != 0u &&
445 (UNLIKELY(index_bss_mapping == nullptr) ||
446 UNLIKELY(index_bss_mapping->size() == 0u) ||
447 UNLIKELY(oat_file->Size() - index_bss_mapping_offset <
448 IndexBssMapping::ComputeSize(index_bss_mapping->size())))) {
449 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with unaligned or "
450 " truncated %s bss mapping, offset %u of %zu, length %zu",
451 oat_file->GetLocation().c_str(),
452 dex_file_index,
453 dex_file_location.c_str(),
454 tag,
455 index_bss_mapping_offset,
456 oat_file->Size(),
457 index_bss_mapping != nullptr ? index_bss_mapping->size() : 0u);
458 return false;
459 }
460
461 *mapping = index_bss_mapping;
462 return true;
463}
464
465static void DCheckIndexToBssMapping(OatFile* oat_file,
466 uint32_t number_of_indexes,
467 size_t slot_size,
468 const IndexBssMapping* index_bss_mapping) {
469 if (kIsDebugBuild && index_bss_mapping != nullptr) {
470 size_t index_bits = IndexBssMappingEntry::IndexBits(number_of_indexes);
471 const IndexBssMappingEntry* prev_entry = nullptr;
472 for (const IndexBssMappingEntry& entry : *index_bss_mapping) {
473 CHECK_ALIGNED_PARAM(entry.bss_offset, slot_size);
474 // When loading a non-executable ElfOatFile, .bss symbols are not even
475 // looked up, so we cannot verify the offset against BssSize().
476 if (oat_file->IsExecutable()) {
477 CHECK_LT(entry.bss_offset, oat_file->BssSize());
478 }
479 uint32_t mask = entry.GetMask(index_bits);
480 CHECK_LE(POPCOUNT(mask) * slot_size, entry.bss_offset);
481 size_t index_mask_span = (mask != 0u) ? 32u - index_bits - CTZ(mask) : 0u;
482 CHECK_LE(index_mask_span, entry.GetIndex(index_bits));
483 if (prev_entry != nullptr) {
484 CHECK_LT(prev_entry->GetIndex(index_bits), entry.GetIndex(index_bits) - index_mask_span);
485 }
486 prev_entry = &entry;
487 }
488 CHECK_LT(prev_entry->GetIndex(index_bits), number_of_indexes);
489 }
490}
491
Nicolas Geoffray30025092018-04-19 14:43:29 +0100492bool OatFileBase::Setup(int zip_fd, const char* abs_dex_location, std::string* error_msg) {
Brian Carlstromf1b30302013-03-28 10:35:32 -0700493 if (!GetOatHeader().IsValid()) {
Andreas Gampe2bcb3b22014-12-12 15:25:14 -0800494 std::string cause = GetOatHeader().GetValidationErrorMessage();
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100495 *error_msg = StringPrintf("Invalid oat header for '%s': %s",
496 GetLocation().c_str(),
Andreas Gampe2bcb3b22014-12-12 15:25:14 -0800497 cause.c_str());
Brian Carlstromf1b30302013-03-28 10:35:32 -0700498 return false;
499 }
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100500 PointerSize pointer_size = GetInstructionSetPointerSize(GetOatHeader().GetInstructionSet());
501 size_t key_value_store_size =
502 (Size() >= sizeof(OatHeader)) ? GetOatHeader().GetKeyValueStoreSize() : 0u;
503 if (Size() < sizeof(OatHeader) + key_value_store_size) {
504 *error_msg = StringPrintf("In oat file '%s' found truncated OatHeader, "
505 "size = %zu < %zu + %zu",
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100506 GetLocation().c_str(),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100507 Size(),
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100508 sizeof(OatHeader),
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100509 key_value_store_size);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700510 return false;
511 }
512
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100513 size_t oat_dex_files_offset = GetOatHeader().GetOatDexFilesOffset();
514 if (oat_dex_files_offset < GetOatHeader().GetHeaderSize() || oat_dex_files_offset > Size()) {
515 *error_msg = StringPrintf("In oat file '%s' found invalid oat dex files offset: "
516 "%zu is not in [%zu, %zu]",
517 GetLocation().c_str(),
518 oat_dex_files_offset,
519 GetOatHeader().GetHeaderSize(),
520 Size());
521 return false;
522 }
523 const uint8_t* oat = Begin() + oat_dex_files_offset; // Jump to the OatDexFile records.
524
Vladimir Markob066d432018-01-03 13:14:37 +0000525 if (!IsAligned<sizeof(uint32_t)>(data_bimg_rel_ro_begin_) ||
526 !IsAligned<sizeof(uint32_t)>(data_bimg_rel_ro_end_) ||
527 data_bimg_rel_ro_begin_ > data_bimg_rel_ro_end_) {
528 *error_msg = StringPrintf("In oat file '%s' found unaligned or unordered databimgrelro "
529 "symbol(s): begin = %p, end = %p",
530 GetLocation().c_str(),
531 data_bimg_rel_ro_begin_,
532 data_bimg_rel_ro_end_);
533 return false;
534 }
535
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100536 DCHECK_GE(static_cast<size_t>(pointer_size), alignof(GcRoot<mirror::Object>));
537 if (!IsAligned<kPageSize>(bss_begin_) ||
538 !IsAlignedParam(bss_methods_, static_cast<size_t>(pointer_size)) ||
539 !IsAlignedParam(bss_roots_, static_cast<size_t>(pointer_size)) ||
Vladimir Markoaad75c62016-10-03 08:46:48 +0000540 !IsAligned<alignof(GcRoot<mirror::Object>)>(bss_end_)) {
541 *error_msg = StringPrintf("In oat file '%s' found unaligned bss symbol(s): "
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100542 "begin = %p, methods_ = %p, roots = %p, end = %p",
Vladimir Markoaad75c62016-10-03 08:46:48 +0000543 GetLocation().c_str(),
544 bss_begin_,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100545 bss_methods_,
Vladimir Markoaad75c62016-10-03 08:46:48 +0000546 bss_roots_,
547 bss_end_);
548 return false;
549 }
550
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100551 if ((bss_methods_ != nullptr && (bss_methods_ < bss_begin_ || bss_methods_ > bss_end_)) ||
552 (bss_roots_ != nullptr && (bss_roots_ < bss_begin_ || bss_roots_ > bss_end_)) ||
553 (bss_methods_ != nullptr && bss_roots_ != nullptr && bss_methods_ > bss_roots_)) {
554 *error_msg = StringPrintf("In oat file '%s' found bss symbol(s) outside .bss or unordered: "
Vladimir Marko0f3c7002017-09-07 14:15:56 +0100555 "begin = %p, methods = %p, roots = %p, end = %p",
Vladimir Markoaad75c62016-10-03 08:46:48 +0000556 GetLocation().c_str(),
Vladimir Markoaad75c62016-10-03 08:46:48 +0000557 bss_begin_,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100558 bss_methods_,
559 bss_roots_,
Vladimir Markoaad75c62016-10-03 08:46:48 +0000560 bss_end_);
561 return false;
562 }
563
Vladimir Markoe47f60c2018-02-21 13:43:28 +0000564 if (bss_methods_ != nullptr && bss_methods_ != bss_begin_) {
565 *error_msg = StringPrintf("In oat file '%s' found unexpected .bss gap before 'oatbssmethods': "
566 "begin = %p, methods = %p",
567 GetLocation().c_str(),
568 bss_begin_,
569 bss_methods_);
570 return false;
571 }
572
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100573 uint32_t dex_file_count = GetOatHeader().GetDexFileCount();
574 oat_dex_files_storage_.reserve(dex_file_count);
575 for (size_t i = 0; i < dex_file_count; i++) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100576 uint32_t dex_file_location_size;
577 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_location_size))) {
578 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu truncated after dex file "
579 "location size",
580 GetLocation().c_str(),
581 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700582 return false;
583 }
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100584 if (UNLIKELY(dex_file_location_size == 0U)) {
585 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu with empty location name",
586 GetLocation().c_str(),
587 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700588 return false;
589 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000590 if (UNLIKELY(static_cast<size_t>(End() - oat) < dex_file_location_size)) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100591 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu with truncated dex file "
592 "location",
593 GetLocation().c_str(),
594 i);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700595 return false;
596 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000597 const char* dex_file_location_data = reinterpret_cast<const char*>(oat);
598 oat += dex_file_location_size;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700599
Richard Uhlere5fed032015-03-18 08:21:11 -0700600 std::string dex_file_location = ResolveRelativeEncodedDexLocation(
601 abs_dex_location,
602 std::string(dex_file_location_data, dex_file_location_size));
Brian Carlstrome24fa612011-09-29 00:53:55 -0700603
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100604 uint32_t dex_file_checksum;
605 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_checksum))) {
606 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated after "
607 "dex file checksum",
608 GetLocation().c_str(),
609 i,
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700610 dex_file_location.c_str());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700611 return false;
612 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700613
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100614 uint32_t dex_file_offset;
615 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_file_offset))) {
616 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated "
617 "after dex file offsets",
618 GetLocation().c_str(),
619 i,
620 dex_file_location.c_str());
621 return false;
622 }
David Brazdil7b49e6c2016-09-01 11:06:18 +0100623 if (UNLIKELY(dex_file_offset > DexSize())) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100624 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
625 "offset %u > %zu",
626 GetLocation().c_str(),
627 i,
628 dex_file_location.c_str(),
629 dex_file_offset,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100630 DexSize());
Brian Carlstromfb331d72013-07-25 22:00:16 -0700631 return false;
632 }
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000633 const uint8_t* dex_file_pointer = nullptr;
634 if (UNLIKELY(dex_file_offset == 0U)) {
635 if (uncompressed_dex_files_ == nullptr) {
Andreas Gampefc604a72018-02-08 15:43:37 -0800636 // Do not support mixed-mode oat files.
637 if (i > 0) {
638 *error_msg = StringPrintf("In oat file '%s', unsupported uncompressed-dex-file for dex "
639 "file %zu (%s)",
640 GetLocation().c_str(),
641 i,
642 dex_file_location.c_str());
643 return false;
644 }
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000645 uncompressed_dex_files_.reset(new std::vector<std::unique_ptr<const DexFile>>());
646 // No dex files, load it from location.
647 const ArtDexFileLoader dex_file_loader;
Nicolas Geoffray30025092018-04-19 14:43:29 +0100648 bool loaded = false;
649 if (zip_fd != -1) {
650 loaded = dex_file_loader.OpenZip(zip_fd,
651 dex_file_location,
652 /* verify */ false,
653 /* verify_checksum */ false,
654 error_msg,
655 uncompressed_dex_files_.get());
656 } else {
657 loaded = dex_file_loader.Open(dex_file_location.c_str(),
658 dex_file_location,
659 /* verify */ false,
660 /* verify_checksum */ false,
661 error_msg,
662 uncompressed_dex_files_.get());
663 }
664 if (!loaded) {
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000665 if (Runtime::Current() == nullptr) {
666 // If there's no runtime, we're running oatdump, so return
667 // a half constructed oat file that oatdump knows how to deal with.
668 LOG(WARNING) << "Could not find associated dex files of oat file. "
669 << "Oatdump will only dump the header.";
670 return true;
671 } else {
672 return false;
673 }
674 }
Andreas Gampefc604a72018-02-08 15:43:37 -0800675 // The oat file may be out of date wrt/ the dex-file location. We need to be defensive
676 // here and ensure that at least the number of dex files still matches.
677 // Note: actual checksum comparisons are the duty of the OatFileAssistant and will be
678 // done after loading the OatFile.
679 if (uncompressed_dex_files_->size() != dex_file_count) {
680 *error_msg = StringPrintf("In oat file '%s', expected %u uncompressed dex files, but "
681 "found %zu in '%s'",
682 GetLocation().c_str(),
683 dex_file_count,
684 uncompressed_dex_files_->size(),
685 dex_file_location.c_str());
686 return false;
687 }
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000688 }
689 dex_file_pointer = uncompressed_dex_files_.get()->at(i)->Begin();
690 } else {
Andreas Gampefc604a72018-02-08 15:43:37 -0800691 // Do not support mixed-mode oat files.
692 if (uncompressed_dex_files_ != nullptr) {
693 *error_msg = StringPrintf("In oat file '%s', unsupported embedded dex-file for dex file "
694 "%zu (%s)",
695 GetLocation().c_str(),
696 i,
697 dex_file_location.c_str());
698 return false;
699 }
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000700 if (UNLIKELY(DexSize() - dex_file_offset < sizeof(DexFile::Header))) {
701 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
702 "offset %u of %zu but the size of dex file header is %zu",
703 GetLocation().c_str(),
704 i,
705 dex_file_location.c_str(),
706 dex_file_offset,
707 DexSize(),
708 sizeof(DexFile::Header));
709 return false;
710 }
711 dex_file_pointer = DexBegin() + dex_file_offset;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000712 }
Brian Carlstrom89521892011-12-07 22:05:07 -0800713
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700714 const bool valid_magic = DexFileLoader::IsMagicValid(dex_file_pointer);
Mathieu Chartier7b074bf2017-09-25 16:22:36 -0700715 if (UNLIKELY(!valid_magic)) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100716 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with invalid "
717 "dex file magic '%s'",
718 GetLocation().c_str(),
719 i,
720 dex_file_location.c_str(),
721 dex_file_pointer);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700722 return false;
723 }
Mathieu Chartiercf76bf82017-09-25 16:22:36 -0700724 if (UNLIKELY(!DexFileLoader::IsVersionAndMagicValid(dex_file_pointer))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100725 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with invalid "
726 "dex file version '%s'",
727 GetLocation().c_str(),
728 i,
729 dex_file_location.c_str(),
730 dex_file_pointer);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700731 return false;
732 }
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -0800733 const DexFile::Header* header = reinterpret_cast<const DexFile::Header*>(dex_file_pointer);
Nicolas Geoffrayf3075272018-01-08 12:41:19 +0000734 if (dex_file_offset != 0 && (DexSize() - dex_file_offset < header->file_size_)) {
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000735 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with dex file "
736 "offset %u and size %u truncated at %zu",
737 GetLocation().c_str(),
738 i,
739 dex_file_location.c_str(),
740 dex_file_offset,
741 header->file_size_,
David Brazdil7b49e6c2016-09-01 11:06:18 +0100742 DexSize());
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000743 return false;
744 }
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300745
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000746 uint32_t class_offsets_offset;
747 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &class_offsets_offset))) {
748 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' truncated "
749 "after class offsets offset",
750 GetLocation().c_str(),
751 i,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300752 dex_file_location.c_str());
753 return false;
754 }
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000755 if (UNLIKELY(class_offsets_offset > Size()) ||
756 UNLIKELY((Size() - class_offsets_offset) / sizeof(uint32_t) < header->class_defs_size_)) {
757 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with truncated "
758 "class offsets, offset %u of %zu, class defs %u",
759 GetLocation().c_str(),
760 i,
761 dex_file_location.c_str(),
762 class_offsets_offset,
763 Size(),
764 header->class_defs_size_);
765 return false;
766 }
767 if (UNLIKELY(!IsAligned<alignof(uint32_t)>(class_offsets_offset))) {
768 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with unaligned "
769 "class offsets, offset %u",
770 GetLocation().c_str(),
771 i,
772 dex_file_location.c_str(),
773 class_offsets_offset);
774 return false;
775 }
776 const uint32_t* class_offsets_pointer =
777 reinterpret_cast<const uint32_t*>(Begin() + class_offsets_offset);
778
779 uint32_t lookup_table_offset;
780 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &lookup_table_offset))) {
781 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zd for '%s' truncated "
782 "after lookup table offset",
783 GetLocation().c_str(),
784 i,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300785 dex_file_location.c_str());
786 return false;
787 }
788 const uint8_t* lookup_table_data = lookup_table_offset != 0u
789 ? Begin() + lookup_table_offset
790 : nullptr;
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000791 if (lookup_table_offset != 0u &&
792 (UNLIKELY(lookup_table_offset > Size()) ||
793 UNLIKELY(Size() - lookup_table_offset <
794 TypeLookupTable::RawDataLength(header->class_defs_size_)))) {
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100795 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zu for '%s' with truncated "
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000796 "type lookup table, offset %u of %zu, class defs %u",
Vladimir Marko06d7aaa2015-10-16 11:23:41 +0100797 GetLocation().c_str(),
798 i,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000799 dex_file_location.c_str(),
800 lookup_table_offset,
801 Size(),
802 header->class_defs_size_);
Brian Carlstromfb331d72013-07-25 22:00:16 -0700803 return false;
804 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700805
Mathieu Chartier120aa282017-08-05 16:03:03 -0700806 uint32_t dex_layout_sections_offset;
807 if (UNLIKELY(!ReadOatDexFileData(*this, &oat, &dex_layout_sections_offset))) {
808 *error_msg = StringPrintf("In oat file '%s' found OatDexFile #%zd for '%s' truncated "
809 "after dex layout sections offset",
810 GetLocation().c_str(),
811 i,
812 dex_file_location.c_str());
813 return false;
814 }
815 const DexLayoutSections* const dex_layout_sections = dex_layout_sections_offset != 0
816 ? reinterpret_cast<const DexLayoutSections*>(Begin() + dex_layout_sections_offset)
817 : nullptr;
818
Vladimir Markof3c52b42017-11-17 17:32:12 +0000819 const IndexBssMapping* method_bss_mapping;
820 const IndexBssMapping* type_bss_mapping;
821 const IndexBssMapping* string_bss_mapping;
822 if (!ReadIndexBssMapping(
823 this, &oat, i, dex_file_location, "method", &method_bss_mapping, error_msg) ||
824 !ReadIndexBssMapping(
825 this, &oat, i, dex_file_location, "type", &type_bss_mapping, error_msg) ||
826 !ReadIndexBssMapping(
827 this, &oat, i, dex_file_location, "string", &string_bss_mapping, error_msg)) {
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100828 return false;
829 }
Vladimir Markof3c52b42017-11-17 17:32:12 +0000830 DCheckIndexToBssMapping(
831 this, header->method_ids_size_, static_cast<size_t>(pointer_size), method_bss_mapping);
832 DCheckIndexToBssMapping(
833 this, header->type_ids_size_, sizeof(GcRoot<mirror::Class>), type_bss_mapping);
834 DCheckIndexToBssMapping(
835 this, header->string_ids_size_, sizeof(GcRoot<mirror::String>), string_bss_mapping);
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100836
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700837 std::string canonical_location =
838 DexFileLoader::GetDexCanonicalLocation(dex_file_location.c_str());
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100839
840 // Create the OatDexFile and add it to the owning container.
Vladimir Marko539690a2014-06-05 18:36:42 +0100841 OatDexFile* oat_dex_file = new OatDexFile(this,
842 dex_file_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100843 canonical_location,
Vladimir Marko539690a2014-06-05 18:36:42 +0100844 dex_file_checksum,
845 dex_file_pointer,
Artem Udovichenkod9786b02015-10-14 16:36:55 +0300846 lookup_table_data,
Vladimir Marko0eb882b2017-05-15 13:39:18 +0100847 method_bss_mapping,
Vladimir Markof3c52b42017-11-17 17:32:12 +0000848 type_bss_mapping,
849 string_bss_mapping,
Vladimir Marko9bdf1082016-01-21 12:15:52 +0000850 class_offsets_pointer,
Mathieu Chartier120aa282017-08-05 16:03:03 -0700851 dex_layout_sections);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100852 oat_dex_files_storage_.push_back(oat_dex_file);
853
854 // Add the location and canonical location (if different) to the oat_dex_files_ table.
Vladimir Marko3f5838d2014-08-07 18:07:18 +0100855 StringPiece key(oat_dex_file->GetDexFileLocation());
Vladimir Marko539690a2014-06-05 18:36:42 +0100856 oat_dex_files_.Put(key, oat_dex_file);
Vladimir Markoaa4497d2014-09-05 14:01:17 +0100857 if (canonical_location != dex_file_location) {
858 StringPiece canonical_key(oat_dex_file->GetCanonicalDexFileLocation());
859 oat_dex_files_.Put(canonical_key, oat_dex_file);
860 }
Brian Carlstrome24fa612011-09-29 00:53:55 -0700861 }
Vladimir Marko09d09432015-09-08 13:47:48 +0100862
Vladimir Markob066d432018-01-03 13:14:37 +0000863 Runtime* runtime = Runtime::Current();
864
865 if (DataBimgRelRoBegin() != nullptr) {
866 // Make .data.bimg.rel.ro read only. ClassLinker shall make it writable for relocation.
867 uint8_t* reloc_begin = const_cast<uint8_t*>(DataBimgRelRoBegin());
868 CheckedCall(mprotect, "protect relocations", reloc_begin, DataBimgRelRoSize(), PROT_READ);
869 if (UNLIKELY(runtime == nullptr)) {
870 // This must be oatdump without boot image.
871 } else if (!IsExecutable()) {
872 // Do not check whether we have a boot image if the oat file is not executable.
873 } else if (UNLIKELY(runtime->GetHeap()->GetBootImageSpaces().empty())) {
874 *error_msg = StringPrintf("Cannot load oat file '%s' with .data.bimg.rel.ro as executable "
875 "without boot image.",
876 GetLocation().c_str());
877 return false;
878 } else {
879 // ClassLinker shall perform the relocation when we register a dex file from
880 // this oat file. We do not do the relocation here to avoid dirtying the pages
881 // if the code is never actually ready to be executed.
882 }
883 }
884
Brian Carlstromf1b30302013-03-28 10:35:32 -0700885 return true;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700886}
887
Andreas Gampe049cff02015-12-01 23:27:12 -0800888////////////////////////
889// OatFile via dlopen //
890////////////////////////
891
Andreas Gampe049cff02015-12-01 23:27:12 -0800892class DlOpenOatFile FINAL : public OatFileBase {
893 public:
894 DlOpenOatFile(const std::string& filename, bool executable)
895 : OatFileBase(filename, executable),
896 dlopen_handle_(nullptr),
Richard Uhlera206c742016-05-24 15:04:22 -0700897 shared_objects_before_(0) {
Andreas Gampe049cff02015-12-01 23:27:12 -0800898 }
899
900 ~DlOpenOatFile() {
901 if (dlopen_handle_ != nullptr) {
Richard Uhlera206c742016-05-24 15:04:22 -0700902 if (!kIsTargetBuild) {
903 MutexLock mu(Thread::Current(), *Locks::host_dlopen_handles_lock_);
904 host_dlopen_handles_.erase(dlopen_handle_);
Mathieu Chartierc7d3f4b2016-06-01 10:48:19 -0700905 dlclose(dlopen_handle_);
906 } else {
907 dlclose(dlopen_handle_);
Richard Uhlera206c742016-05-24 15:04:22 -0700908 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800909 }
Andreas Gampe049cff02015-12-01 23:27:12 -0800910 }
911
912 protected:
913 const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
914 std::string* error_msg) const OVERRIDE {
915 const uint8_t* ptr =
916 reinterpret_cast<const uint8_t*>(dlsym(dlopen_handle_, symbol_name.c_str()));
917 if (ptr == nullptr) {
918 *error_msg = dlerror();
919 }
920 return ptr;
921 }
922
Andreas Gampe4075f832016-05-18 13:09:54 -0700923 void PreLoad() OVERRIDE;
924
Andreas Gampe049cff02015-12-01 23:27:12 -0800925 bool Load(const std::string& elf_filename,
926 uint8_t* oat_file_begin,
927 bool writable,
928 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800929 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800930 std::string* error_msg) OVERRIDE;
931
Shubham Ajmerab22dea02017-10-04 18:36:41 -0700932 bool Load(int, uint8_t*, bool, bool, bool, std::string*) {
933 return false;
934 }
935
Andreas Gampe049cff02015-12-01 23:27:12 -0800936 // Ask the linker where it mmaped the file and notify our mmap wrapper of the regions.
937 void PreSetup(const std::string& elf_filename) OVERRIDE;
938
939 private:
940 bool Dlopen(const std::string& elf_filename,
941 uint8_t* oat_file_begin,
942 std::string* error_msg);
943
Richard Uhlera206c742016-05-24 15:04:22 -0700944 // On the host, if the same library is loaded again with dlopen the same
945 // file handle is returned. This differs from the behavior of dlopen on the
946 // target, where dlopen reloads the library at a different address every
947 // time you load it. The runtime relies on the target behavior to ensure
948 // each instance of the loaded library has a unique dex cache. To avoid
949 // problems, we fall back to our own linker in the case when the same
950 // library is opened multiple times on host. dlopen_handles_ is used to
951 // detect that case.
952 // Guarded by host_dlopen_handles_lock_;
953 static std::unordered_set<void*> host_dlopen_handles_;
954
Andreas Gampe049cff02015-12-01 23:27:12 -0800955 // dlopen handle during runtime.
956 void* dlopen_handle_; // TODO: Unique_ptr with custom deleter.
957
958 // Dummy memory map objects corresponding to the regions mapped by dlopen.
959 std::vector<std::unique_ptr<MemMap>> dlopen_mmaps_;
960
Andreas Gampe4075f832016-05-18 13:09:54 -0700961 // The number of shared objects the linker told us about before loading. Used to
962 // (optimistically) optimize the PreSetup stage (see comment there).
963 size_t shared_objects_before_;
964
Andreas Gampe049cff02015-12-01 23:27:12 -0800965 DISALLOW_COPY_AND_ASSIGN(DlOpenOatFile);
966};
967
Richard Uhlera206c742016-05-24 15:04:22 -0700968std::unordered_set<void*> DlOpenOatFile::host_dlopen_handles_;
969
Andreas Gampe4075f832016-05-18 13:09:54 -0700970void DlOpenOatFile::PreLoad() {
971#ifdef __APPLE__
Andreas Gampe39004a62016-05-18 21:27:00 -0700972 UNUSED(shared_objects_before_);
Andreas Gampe4075f832016-05-18 13:09:54 -0700973 LOG(FATAL) << "Should not reach here.";
974 UNREACHABLE();
975#else
976 // Count the entries in dl_iterate_phdr we get at this point in time.
977 struct dl_iterate_context {
978 static int callback(struct dl_phdr_info *info ATTRIBUTE_UNUSED,
979 size_t size ATTRIBUTE_UNUSED,
980 void *data) {
981 reinterpret_cast<dl_iterate_context*>(data)->count++;
982 return 0; // Continue iteration.
983 }
984 size_t count = 0;
985 } context;
986
987 dl_iterate_phdr(dl_iterate_context::callback, &context);
988 shared_objects_before_ = context.count;
989#endif
990}
991
Andreas Gampe049cff02015-12-01 23:27:12 -0800992bool DlOpenOatFile::Load(const std::string& elf_filename,
993 uint8_t* oat_file_begin,
994 bool writable,
995 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -0800996 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -0800997 std::string* error_msg) {
998 // Use dlopen only when flagged to do so, and when it's OK to load things executable.
999 // TODO: Also try when not executable? The issue here could be re-mapping as writable (as
1000 // !executable is a sign that we may want to patch), which may not be allowed for
1001 // various reasons.
1002 if (!kUseDlopen) {
1003 *error_msg = "DlOpen is disabled.";
1004 return false;
1005 }
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001006 if (low_4gb) {
1007 *error_msg = "DlOpen does not support low 4gb loading.";
1008 return false;
1009 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001010 if (writable) {
1011 *error_msg = "DlOpen does not support writable loading.";
1012 return false;
1013 }
1014 if (!executable) {
1015 *error_msg = "DlOpen does not support non-executable loading.";
1016 return false;
1017 }
1018
1019 // dlopen always returns the same library if it is already opened on the host. For this reason
1020 // we only use dlopen if we are the target or we do not already have the dex file opened. Having
1021 // the same library loaded multiple times at different addresses is required for class unloading
1022 // and for having dex caches arrays in the .bss section.
1023 if (!kIsTargetBuild) {
1024 if (!kUseDlopenOnHost) {
1025 *error_msg = "DlOpen disabled for host.";
1026 return false;
1027 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001028 }
1029
1030 bool success = Dlopen(elf_filename, oat_file_begin, error_msg);
1031 DCHECK(dlopen_handle_ != nullptr || !success);
1032
1033 return success;
1034}
1035
1036bool DlOpenOatFile::Dlopen(const std::string& elf_filename,
1037 uint8_t* oat_file_begin,
1038 std::string* error_msg) {
1039#ifdef __APPLE__
1040 // The dl_iterate_phdr syscall is missing. There is similar API on OSX,
1041 // but let's fallback to the custom loading code for the time being.
1042 UNUSED(elf_filename, oat_file_begin);
1043 *error_msg = "Dlopen unsupported on Mac.";
1044 return false;
1045#else
1046 {
1047 UniqueCPtr<char> absolute_path(realpath(elf_filename.c_str(), nullptr));
1048 if (absolute_path == nullptr) {
1049 *error_msg = StringPrintf("Failed to find absolute path for '%s'", elf_filename.c_str());
1050 return false;
1051 }
Bilyan Borisovbb661c02016-04-04 16:27:32 +01001052#ifdef ART_TARGET_ANDROID
Anton Kirilov3a2e78e2017-01-06 13:33:42 +00001053 android_dlextinfo extinfo = {};
Andreas Gampe049cff02015-12-01 23:27:12 -08001054 extinfo.flags = ANDROID_DLEXT_FORCE_LOAD | // Force-load, don't reuse handle
1055 // (open oat files multiple
1056 // times).
1057 ANDROID_DLEXT_FORCE_FIXED_VADDR; // Take a non-zero vaddr as absolute
1058 // (non-pic boot image).
Andreas Gampe226b91e2015-12-02 10:29:33 -08001059 if (oat_file_begin != nullptr) { //
1060 extinfo.flags |= ANDROID_DLEXT_LOAD_AT_FIXED_ADDRESS; // Use the requested addr if
1061 extinfo.reserved_addr = oat_file_begin; // vaddr = 0.
1062 } // (pic boot image).
Andreas Gampe049cff02015-12-01 23:27:12 -08001063 dlopen_handle_ = android_dlopen_ext(absolute_path.get(), RTLD_NOW, &extinfo);
1064#else
Andreas Gampe049cff02015-12-01 23:27:12 -08001065 UNUSED(oat_file_begin);
Julien Duraj1af0c4f2016-11-16 14:05:48 +00001066 static_assert(!kIsTargetBuild || kIsTargetLinux, "host_dlopen_handles_ will leak handles");
Mathieu Chartierc7d3f4b2016-06-01 10:48:19 -07001067 MutexLock mu(Thread::Current(), *Locks::host_dlopen_handles_lock_);
Richard Uhlera206c742016-05-24 15:04:22 -07001068 dlopen_handle_ = dlopen(absolute_path.get(), RTLD_NOW);
1069 if (dlopen_handle_ != nullptr) {
Richard Uhlera206c742016-05-24 15:04:22 -07001070 if (!host_dlopen_handles_.insert(dlopen_handle_).second) {
1071 dlclose(dlopen_handle_);
1072 dlopen_handle_ = nullptr;
1073 *error_msg = StringPrintf("host dlopen re-opened '%s'", elf_filename.c_str());
1074 return false;
1075 }
1076 }
Bilyan Borisovbb661c02016-04-04 16:27:32 +01001077#endif // ART_TARGET_ANDROID
Andreas Gampe049cff02015-12-01 23:27:12 -08001078 }
1079 if (dlopen_handle_ == nullptr) {
1080 *error_msg = StringPrintf("Failed to dlopen '%s': %s", elf_filename.c_str(), dlerror());
1081 return false;
1082 }
1083 return true;
1084#endif
1085}
1086
1087void DlOpenOatFile::PreSetup(const std::string& elf_filename) {
Andreas Gampe74f07b52015-12-02 11:53:26 -08001088#ifdef __APPLE__
1089 UNUSED(elf_filename);
1090 LOG(FATAL) << "Should not reach here.";
1091 UNREACHABLE();
1092#else
Andreas Gampe049cff02015-12-01 23:27:12 -08001093 struct dl_iterate_context {
1094 static int callback(struct dl_phdr_info *info, size_t /* size */, void *data) {
1095 auto* context = reinterpret_cast<dl_iterate_context*>(data);
Andreas Gampe4075f832016-05-18 13:09:54 -07001096 context->shared_objects_seen++;
1097 if (context->shared_objects_seen < context->shared_objects_before) {
1098 // We haven't been called yet for anything we haven't seen before. Just continue.
1099 // Note: this is aggressively optimistic. If another thread was unloading a library,
1100 // we may miss out here. However, this does not happen often in practice.
1101 return 0;
1102 }
1103
Andreas Gampe049cff02015-12-01 23:27:12 -08001104 // See whether this callback corresponds to the file which we have just loaded.
1105 bool contains_begin = false;
1106 for (int i = 0; i < info->dlpi_phnum; i++) {
1107 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
1108 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
1109 info->dlpi_phdr[i].p_vaddr);
1110 size_t memsz = info->dlpi_phdr[i].p_memsz;
1111 if (vaddr <= context->begin_ && context->begin_ < vaddr + memsz) {
1112 contains_begin = true;
1113 break;
1114 }
1115 }
1116 }
1117 // Add dummy mmaps for this file.
1118 if (contains_begin) {
1119 for (int i = 0; i < info->dlpi_phnum; i++) {
1120 if (info->dlpi_phdr[i].p_type == PT_LOAD) {
1121 uint8_t* vaddr = reinterpret_cast<uint8_t*>(info->dlpi_addr +
1122 info->dlpi_phdr[i].p_vaddr);
1123 size_t memsz = info->dlpi_phdr[i].p_memsz;
1124 MemMap* mmap = MemMap::MapDummy(info->dlpi_name, vaddr, memsz);
1125 context->dlopen_mmaps_->push_back(std::unique_ptr<MemMap>(mmap));
1126 }
1127 }
1128 return 1; // Stop iteration and return 1 from dl_iterate_phdr.
1129 }
1130 return 0; // Continue iteration and return 0 from dl_iterate_phdr when finished.
1131 }
1132 const uint8_t* const begin_;
1133 std::vector<std::unique_ptr<MemMap>>* const dlopen_mmaps_;
Andreas Gampe4075f832016-05-18 13:09:54 -07001134 const size_t shared_objects_before;
1135 size_t shared_objects_seen;
1136 };
1137 dl_iterate_context context = { Begin(), &dlopen_mmaps_, shared_objects_before_, 0};
Andreas Gampe049cff02015-12-01 23:27:12 -08001138
1139 if (dl_iterate_phdr(dl_iterate_context::callback, &context) == 0) {
Andreas Gampe4075f832016-05-18 13:09:54 -07001140 // Hm. Maybe our optimization went wrong. Try another time with shared_objects_before == 0
1141 // before giving up. This should be unusual.
1142 VLOG(oat) << "Need a second run in PreSetup, didn't find with shared_objects_before="
1143 << shared_objects_before_;
1144 dl_iterate_context context0 = { Begin(), &dlopen_mmaps_, 0, 0};
1145 if (dl_iterate_phdr(dl_iterate_context::callback, &context0) == 0) {
1146 // OK, give up and print an error.
Andreas Gampe170331f2017-12-07 18:41:03 -08001147 PrintFileToLog("/proc/self/maps", android::base::LogSeverity::WARNING);
Andreas Gampe4075f832016-05-18 13:09:54 -07001148 LOG(ERROR) << "File " << elf_filename << " loaded with dlopen but cannot find its mmaps.";
1149 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001150 }
Andreas Gampe74f07b52015-12-02 11:53:26 -08001151#endif
Andreas Gampe049cff02015-12-01 23:27:12 -08001152}
1153
1154////////////////////////////////////////////////
1155// OatFile via our own ElfFile implementation //
1156////////////////////////////////////////////////
1157
1158class ElfOatFile FINAL : public OatFileBase {
1159 public:
1160 ElfOatFile(const std::string& filename, bool executable) : OatFileBase(filename, executable) {}
1161
Nicolas Geoffray30025092018-04-19 14:43:29 +01001162 static ElfOatFile* OpenElfFile(int zip_fd,
1163 File* file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001164 const std::string& location,
1165 uint8_t* requested_base,
1166 uint8_t* oat_file_begin, // Override base if not null
1167 bool writable,
1168 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001169 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001170 const char* abs_dex_location,
1171 std::string* error_msg);
1172
Nicolas Geoffray30025092018-04-19 14:43:29 +01001173 bool InitializeFromElfFile(int zip_fd,
1174 ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +01001175 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001176 const char* abs_dex_location,
1177 std::string* error_msg);
1178
1179 protected:
1180 const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name,
1181 std::string* error_msg) const OVERRIDE {
1182 const uint8_t* ptr = elf_file_->FindDynamicSymbolAddress(symbol_name);
1183 if (ptr == nullptr) {
1184 *error_msg = "(Internal implementation could not find symbol)";
1185 }
1186 return ptr;
1187 }
1188
Andreas Gampe4075f832016-05-18 13:09:54 -07001189 void PreLoad() OVERRIDE {
1190 }
1191
Andreas Gampe049cff02015-12-01 23:27:12 -08001192 bool Load(const std::string& elf_filename,
1193 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1194 bool writable,
1195 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001196 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001197 std::string* error_msg) OVERRIDE;
1198
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001199 bool Load(int oat_fd,
1200 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1201 bool writable,
1202 bool executable,
1203 bool low_4gb,
1204 std::string* error_msg) OVERRIDE;
1205
Andreas Gampe049cff02015-12-01 23:27:12 -08001206 void PreSetup(const std::string& elf_filename ATTRIBUTE_UNUSED) OVERRIDE {
1207 }
1208
1209 private:
1210 bool ElfFileOpen(File* file,
1211 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1212 bool writable,
1213 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001214 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001215 std::string* error_msg);
1216
1217 private:
1218 // Backing memory map for oat file during cross compilation.
1219 std::unique_ptr<ElfFile> elf_file_;
1220
1221 DISALLOW_COPY_AND_ASSIGN(ElfOatFile);
1222};
1223
Nicolas Geoffray30025092018-04-19 14:43:29 +01001224ElfOatFile* ElfOatFile::OpenElfFile(int zip_fd,
1225 File* file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001226 const std::string& location,
1227 uint8_t* requested_base,
1228 uint8_t* oat_file_begin, // Override base if not null
1229 bool writable,
1230 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001231 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001232 const char* abs_dex_location,
1233 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001234 ScopedTrace trace("Open elf file " + location);
Andreas Gampe049cff02015-12-01 23:27:12 -08001235 std::unique_ptr<ElfOatFile> oat_file(new ElfOatFile(location, executable));
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001236 bool success = oat_file->ElfFileOpen(file,
1237 oat_file_begin,
1238 writable,
1239 low_4gb,
1240 executable,
1241 error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -08001242 if (!success) {
1243 CHECK(!error_msg->empty());
1244 return nullptr;
1245 }
1246
1247 // Complete the setup.
1248 if (!oat_file->ComputeFields(requested_base, file->GetPath(), error_msg)) {
1249 return nullptr;
1250 }
1251
Nicolas Geoffray30025092018-04-19 14:43:29 +01001252 if (!oat_file->Setup(zip_fd, abs_dex_location, error_msg)) {
Andreas Gampe049cff02015-12-01 23:27:12 -08001253 return nullptr;
1254 }
1255
1256 return oat_file.release();
1257}
1258
Nicolas Geoffray30025092018-04-19 14:43:29 +01001259bool ElfOatFile::InitializeFromElfFile(int zip_fd,
1260 ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +01001261 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001262 const char* abs_dex_location,
1263 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001264 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -08001265 if (IsExecutable()) {
1266 *error_msg = "Cannot initialize from elf file in executable mode.";
1267 return false;
1268 }
1269 elf_file_.reset(elf_file);
David Brazdilc93b3be2016-09-12 18:49:58 +01001270 SetVdex(vdex_file);
Andreas Gampe049cff02015-12-01 23:27:12 -08001271 uint64_t offset, size;
1272 bool has_section = elf_file->GetSectionOffsetAndSize(".rodata", &offset, &size);
1273 CHECK(has_section);
1274 SetBegin(elf_file->Begin() + offset);
1275 SetEnd(elf_file->Begin() + size + offset);
1276 // Ignore the optional .bss section when opening non-executable.
Nicolas Geoffray30025092018-04-19 14:43:29 +01001277 return Setup(zip_fd, abs_dex_location, error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -08001278}
1279
1280bool ElfOatFile::Load(const std::string& elf_filename,
1281 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1282 bool writable,
1283 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001284 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001285 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001286 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -08001287 std::unique_ptr<File> file(OS::OpenFileForReading(elf_filename.c_str()));
1288 if (file == nullptr) {
1289 *error_msg = StringPrintf("Failed to open oat filename for reading: %s", strerror(errno));
1290 return false;
1291 }
1292 return ElfOatFile::ElfFileOpen(file.get(),
1293 oat_file_begin,
1294 writable,
1295 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001296 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001297 error_msg);
1298}
1299
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001300bool ElfOatFile::Load(int oat_fd,
1301 uint8_t* oat_file_begin, // Override where the file is loaded to if not null
1302 bool writable,
1303 bool executable,
1304 bool low_4gb,
1305 std::string* error_msg) {
1306 ScopedTrace trace(__PRETTY_FUNCTION__);
1307 if (oat_fd != -1) {
1308 std::unique_ptr<File> file = std::make_unique<File>(oat_fd, false);
1309 file->DisableAutoClose();
1310 if (file == nullptr) {
1311 *error_msg = StringPrintf("Failed to open oat filename for reading: %s",
1312 strerror(errno));
1313 return false;
1314 }
1315 return ElfOatFile::ElfFileOpen(file.get(),
1316 oat_file_begin,
1317 writable,
1318 executable,
1319 low_4gb,
1320 error_msg);
1321 }
1322 return false;
1323}
1324
Andreas Gampe049cff02015-12-01 23:27:12 -08001325bool ElfOatFile::ElfFileOpen(File* file,
1326 uint8_t* oat_file_begin,
1327 bool writable,
1328 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001329 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001330 std::string* error_msg) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001331 ScopedTrace trace(__PRETTY_FUNCTION__);
Andreas Gampe049cff02015-12-01 23:27:12 -08001332 // TODO: rename requested_base to oat_data_begin
1333 elf_file_.reset(ElfFile::Open(file,
1334 writable,
1335 /*program_header_only*/true,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001336 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001337 error_msg,
1338 oat_file_begin));
1339 if (elf_file_ == nullptr) {
1340 DCHECK(!error_msg->empty());
1341 return false;
1342 }
Brian Carlstromf5b0f2c2016-10-14 01:04:26 -07001343 bool loaded = elf_file_->Load(file, executable, low_4gb, error_msg);
Andreas Gampe049cff02015-12-01 23:27:12 -08001344 DCHECK(loaded || !error_msg->empty());
1345 return loaded;
1346}
1347
1348//////////////////////////
1349// General OatFile code //
1350//////////////////////////
1351
1352std::string OatFile::ResolveRelativeEncodedDexLocation(
1353 const char* abs_dex_location, const std::string& rel_dex_location) {
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00001354 // For host, we still do resolution as the rel_dex_location might be absolute
1355 // for a target dex (for example /system/foo/foo.apk).
1356 if (abs_dex_location != nullptr && (rel_dex_location[0] != '/' || !kIsTargetBuild)) {
Andreas Gampe049cff02015-12-01 23:27:12 -08001357 // Strip :classes<N>.dex used for secondary multidex files.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001358 std::string base = DexFileLoader::GetBaseLocation(rel_dex_location);
1359 std::string multidex_suffix = DexFileLoader::GetMultiDexSuffix(rel_dex_location);
Andreas Gampe049cff02015-12-01 23:27:12 -08001360
1361 // Check if the base is a suffix of the provided abs_dex_location.
Nicolas Geoffrayf3075272018-01-08 12:41:19 +00001362 std::string target_suffix = ((rel_dex_location[0] != '/') ? "/" : "") + base;
Andreas Gampe049cff02015-12-01 23:27:12 -08001363 std::string abs_location(abs_dex_location);
1364 if (abs_location.size() > target_suffix.size()) {
1365 size_t pos = abs_location.size() - target_suffix.size();
1366 if (abs_location.compare(pos, std::string::npos, target_suffix) == 0) {
1367 return abs_location + multidex_suffix;
1368 }
1369 }
1370 }
1371 return rel_dex_location;
1372}
1373
1374static void CheckLocation(const std::string& location) {
1375 CHECK(!location.empty());
1376}
1377
Nicolas Geoffray30025092018-04-19 14:43:29 +01001378OatFile* OatFile::OpenWithElfFile(int zip_fd,
1379 ElfFile* elf_file,
David Brazdilc93b3be2016-09-12 18:49:58 +01001380 VdexFile* vdex_file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001381 const std::string& location,
1382 const char* abs_dex_location,
1383 std::string* error_msg) {
1384 std::unique_ptr<ElfOatFile> oat_file(new ElfOatFile(location, false /* executable */));
Nicolas Geoffray30025092018-04-19 14:43:29 +01001385 return oat_file->InitializeFromElfFile(zip_fd, elf_file, vdex_file, abs_dex_location, error_msg)
Andreas Gampe049cff02015-12-01 23:27:12 -08001386 ? oat_file.release()
1387 : nullptr;
1388}
1389
Nicolas Geoffray30025092018-04-19 14:43:29 +01001390OatFile* OatFile::Open(int zip_fd,
1391 const std::string& oat_filename,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001392 const std::string& oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001393 uint8_t* requested_base,
1394 uint8_t* oat_file_begin,
1395 bool executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001396 bool low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001397 const char* abs_dex_location,
1398 std::string* error_msg) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001399 ScopedTrace trace("Open oat file " + oat_location);
1400 CHECK(!oat_filename.empty()) << oat_location;
1401 CheckLocation(oat_location);
Andreas Gampe54315c72016-05-18 21:10:42 -07001402
Calin Juravle367b9d82017-05-15 18:18:39 -07001403 std::string vdex_filename = GetVdexFilename(oat_filename);
David Brazdil7b49e6c2016-09-01 11:06:18 +01001404
1405 // Check that the files even exist, fast-fail.
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001406 if (!OS::FileExists(vdex_filename.c_str())) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001407 *error_msg = StringPrintf("File %s does not exist.", vdex_filename.c_str());
1408 return nullptr;
1409 } else if (!OS::FileExists(oat_filename.c_str())) {
1410 *error_msg = StringPrintf("File %s does not exist.", oat_filename.c_str());
Andreas Gampe54315c72016-05-18 21:10:42 -07001411 return nullptr;
1412 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001413
1414 // Try dlopen first, as it is required for native debuggability. This will fail fast if dlopen is
1415 // disabled.
Nicolas Geoffray30025092018-04-19 14:43:29 +01001416 OatFile* with_dlopen = OatFileBase::OpenOatFile<DlOpenOatFile>(zip_fd,
1417 vdex_filename,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001418 oat_filename,
1419 oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001420 requested_base,
1421 oat_file_begin,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001422 false /* writable */,
Andreas Gampe049cff02015-12-01 23:27:12 -08001423 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001424 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001425 abs_dex_location,
1426 error_msg);
1427 if (with_dlopen != nullptr) {
1428 return with_dlopen;
1429 }
1430 if (kPrintDlOpenErrorMessage) {
David Brazdil7b49e6c2016-09-01 11:06:18 +01001431 LOG(ERROR) << "Failed to dlopen: " << oat_filename << " with error " << *error_msg;
Andreas Gampe049cff02015-12-01 23:27:12 -08001432 }
Andreas Gampe049cff02015-12-01 23:27:12 -08001433 // If we aren't trying to execute, we just use our own ElfFile loader for a couple reasons:
1434 //
1435 // On target, dlopen may fail when compiling due to selinux restrictions on installd.
1436 //
1437 // We use our own ELF loader for Quick to deal with legacy apps that
1438 // open a generated dex file by name, remove the file, then open
1439 // another generated dex file with the same name. http://b/10614658
1440 //
1441 // On host, dlopen is expected to fail when cross compiling, so fall back to OpenElfFile.
1442 //
1443 //
1444 // Another independent reason is the absolute placement of boot.oat. dlopen on the host usually
1445 // does honor the virtual address encoded in the ELF file only for ET_EXEC files, not ET_DYN.
Nicolas Geoffray30025092018-04-19 14:43:29 +01001446 OatFile* with_internal = OatFileBase::OpenOatFile<ElfOatFile>(zip_fd,
1447 vdex_filename,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001448 oat_filename,
1449 oat_location,
Andreas Gampe049cff02015-12-01 23:27:12 -08001450 requested_base,
1451 oat_file_begin,
David Brazdil7b49e6c2016-09-01 11:06:18 +01001452 false /* writable */,
Andreas Gampe049cff02015-12-01 23:27:12 -08001453 executable,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001454 low_4gb,
Andreas Gampe049cff02015-12-01 23:27:12 -08001455 abs_dex_location,
1456 error_msg);
1457 return with_internal;
1458}
1459
Nicolas Geoffray30025092018-04-19 14:43:29 +01001460OatFile* OatFile::Open(int zip_fd,
1461 int vdex_fd,
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001462 int oat_fd,
1463 const std::string& oat_location,
1464 uint8_t* requested_base,
1465 uint8_t* oat_file_begin,
1466 bool executable,
1467 bool low_4gb,
1468 const char* abs_dex_location,
1469 std::string* error_msg) {
1470 CHECK(!oat_location.empty()) << oat_location;
1471
1472 std::string vdex_location = GetVdexFilename(oat_location);
1473
Nicolas Geoffray30025092018-04-19 14:43:29 +01001474 OatFile* with_internal = OatFileBase::OpenOatFile<ElfOatFile>(zip_fd,
1475 vdex_fd,
Shubham Ajmerab22dea02017-10-04 18:36:41 -07001476 oat_fd,
1477 vdex_location,
1478 oat_location,
1479 requested_base,
1480 oat_file_begin,
1481 false /* writable */,
1482 executable,
1483 low_4gb,
1484 abs_dex_location,
1485 error_msg);
1486 return with_internal;
1487}
1488
Nicolas Geoffray30025092018-04-19 14:43:29 +01001489OatFile* OatFile::OpenWritable(int zip_fd,
1490 File* file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001491 const std::string& location,
1492 const char* abs_dex_location,
1493 std::string* error_msg) {
1494 CheckLocation(location);
Nicolas Geoffray30025092018-04-19 14:43:29 +01001495 return ElfOatFile::OpenElfFile(zip_fd,
1496 file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001497 location,
1498 nullptr,
1499 nullptr,
1500 true,
1501 false,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001502 /*low_4gb*/false,
Andreas Gampe049cff02015-12-01 23:27:12 -08001503 abs_dex_location,
1504 error_msg);
1505}
1506
Nicolas Geoffray30025092018-04-19 14:43:29 +01001507OatFile* OatFile::OpenReadable(int zip_fd,
1508 File* file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001509 const std::string& location,
1510 const char* abs_dex_location,
1511 std::string* error_msg) {
1512 CheckLocation(location);
Nicolas Geoffray30025092018-04-19 14:43:29 +01001513 return ElfOatFile::OpenElfFile(zip_fd,
1514 file,
Andreas Gampe049cff02015-12-01 23:27:12 -08001515 location,
1516 nullptr,
1517 nullptr,
1518 false,
1519 false,
Mathieu Chartier0b4cbd02016-03-08 16:49:58 -08001520 /*low_4gb*/false,
Andreas Gampe049cff02015-12-01 23:27:12 -08001521 abs_dex_location,
1522 error_msg);
1523}
1524
1525OatFile::OatFile(const std::string& location, bool is_executable)
1526 : location_(location),
David Brazdil7b49e6c2016-09-01 11:06:18 +01001527 vdex_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001528 begin_(nullptr),
1529 end_(nullptr),
Vladimir Markob066d432018-01-03 13:14:37 +00001530 data_bimg_rel_ro_begin_(nullptr),
1531 data_bimg_rel_ro_end_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001532 bss_begin_(nullptr),
1533 bss_end_(nullptr),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001534 bss_methods_(nullptr),
Vladimir Markoaad75c62016-10-03 08:46:48 +00001535 bss_roots_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001536 is_executable_(is_executable),
David Srbeckyec2cdf42017-12-08 16:21:25 +00001537 vdex_begin_(nullptr),
1538 vdex_end_(nullptr),
Andreas Gampe049cff02015-12-01 23:27:12 -08001539 secondary_lookup_lock_("OatFile secondary lookup lock", kOatFileSecondaryLookupLock) {
1540 CHECK(!location_.empty());
1541}
1542
1543OatFile::~OatFile() {
1544 STLDeleteElements(&oat_dex_files_storage_);
1545}
1546
Brian Carlstrome24fa612011-09-29 00:53:55 -07001547const OatHeader& OatFile::GetOatHeader() const {
Ian Rogers30fab402012-01-23 15:43:46 -08001548 return *reinterpret_cast<const OatHeader*>(Begin());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001549}
1550
Ian Rogers13735952014-10-08 12:43:28 -07001551const uint8_t* OatFile::Begin() const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001552 CHECK(begin_ != nullptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001553 return begin_;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001554}
1555
Ian Rogers13735952014-10-08 12:43:28 -07001556const uint8_t* OatFile::End() const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001557 CHECK(end_ != nullptr);
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001558 return end_;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001559}
1560
David Brazdil7b49e6c2016-09-01 11:06:18 +01001561const uint8_t* OatFile::DexBegin() const {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001562 return vdex_->Begin();
David Brazdil7b49e6c2016-09-01 11:06:18 +01001563}
1564
1565const uint8_t* OatFile::DexEnd() const {
Nicolas Geoffray8eaa8e52017-11-13 17:47:50 +00001566 return vdex_->End();
David Brazdil7b49e6c2016-09-01 11:06:18 +01001567}
1568
Vladimir Markob066d432018-01-03 13:14:37 +00001569ArrayRef<const uint32_t> OatFile::GetBootImageRelocations() const {
1570 if (data_bimg_rel_ro_begin_ != nullptr) {
1571 const uint32_t* relocations = reinterpret_cast<const uint32_t*>(data_bimg_rel_ro_begin_);
1572 const uint32_t* relocations_end = reinterpret_cast<const uint32_t*>(data_bimg_rel_ro_end_);
1573 return ArrayRef<const uint32_t>(relocations, relocations_end - relocations);
1574 } else {
1575 return ArrayRef<const uint32_t>();
1576 }
1577}
1578
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001579ArrayRef<ArtMethod*> OatFile::GetBssMethods() const {
1580 if (bss_methods_ != nullptr) {
1581 ArtMethod** methods = reinterpret_cast<ArtMethod**>(bss_methods_);
1582 ArtMethod** methods_end =
1583 reinterpret_cast<ArtMethod**>(bss_roots_ != nullptr ? bss_roots_ : bss_end_);
1584 return ArrayRef<ArtMethod*>(methods, methods_end - methods);
1585 } else {
1586 return ArrayRef<ArtMethod*>();
1587 }
1588}
1589
Vladimir Markoaad75c62016-10-03 08:46:48 +00001590ArrayRef<GcRoot<mirror::Object>> OatFile::GetBssGcRoots() const {
1591 if (bss_roots_ != nullptr) {
1592 auto* roots = reinterpret_cast<GcRoot<mirror::Object>*>(bss_roots_);
1593 auto* roots_end = reinterpret_cast<GcRoot<mirror::Object>*>(bss_end_);
1594 return ArrayRef<GcRoot<mirror::Object>>(roots, roots_end - roots);
1595 } else {
1596 return ArrayRef<GcRoot<mirror::Object>>();
1597 }
1598}
1599
Ian Rogers8d31bbd2013-10-13 10:44:14 -07001600const OatFile::OatDexFile* OatFile::GetOatDexFile(const char* dex_location,
1601 const uint32_t* dex_location_checksum,
Richard Uhler9a37efc2016-08-05 16:32:55 -07001602 std::string* error_msg) const {
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001603 // NOTE: We assume here that the canonical location for a given dex_location never
1604 // changes. If it does (i.e. some symlink used by the filename changes) we may return
1605 // an incorrect OatDexFile. As long as we have a checksum to check, we shall return
1606 // an identical file or fail; otherwise we may see some unpredictable failures.
Calin Juravle4e1d5792014-07-15 23:56:47 +01001607
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001608 // TODO: Additional analysis of usage patterns to see if this can be simplified
1609 // without any performance loss, for example by not doing the first lock-free lookup.
1610
1611 const OatFile::OatDexFile* oat_dex_file = nullptr;
1612 StringPiece key(dex_location);
1613 // Try to find the key cheaply in the oat_dex_files_ map which holds dex locations
1614 // directly mentioned in the oat file and doesn't require locking.
1615 auto primary_it = oat_dex_files_.find(key);
1616 if (primary_it != oat_dex_files_.end()) {
1617 oat_dex_file = primary_it->second;
1618 DCHECK(oat_dex_file != nullptr);
1619 } else {
1620 // This dex_location is not one of the dex locations directly mentioned in the
1621 // oat file. The correct lookup is via the canonical location but first see in
1622 // the secondary_oat_dex_files_ whether we've looked up this location before.
1623 MutexLock mu(Thread::Current(), secondary_lookup_lock_);
1624 auto secondary_lb = secondary_oat_dex_files_.lower_bound(key);
1625 if (secondary_lb != secondary_oat_dex_files_.end() && key == secondary_lb->first) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001626 oat_dex_file = secondary_lb->second; // May be null.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001627 } else {
1628 // We haven't seen this dex_location before, we must check the canonical location.
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001629 std::string dex_canonical_location = DexFileLoader::GetDexCanonicalLocation(dex_location);
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001630 if (dex_canonical_location != dex_location) {
1631 StringPiece canonical_key(dex_canonical_location);
1632 auto canonical_it = oat_dex_files_.find(canonical_key);
1633 if (canonical_it != oat_dex_files_.end()) {
1634 oat_dex_file = canonical_it->second;
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001635 } // else keep null.
1636 } // else keep null.
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001637
1638 // Copy the key to the string_cache_ and store the result in secondary map.
1639 string_cache_.emplace_back(key.data(), key.length());
1640 StringPiece key_copy(string_cache_.back());
1641 secondary_oat_dex_files_.PutBefore(secondary_lb, key_copy, oat_dex_file);
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001642 }
1643 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001644
1645 if (oat_dex_file == nullptr) {
1646 if (error_msg != nullptr) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001647 std::string dex_canonical_location = DexFileLoader::GetDexCanonicalLocation(dex_location);
Richard Uhler9a37efc2016-08-05 16:32:55 -07001648 *error_msg = "Failed to find OatDexFile for DexFile " + std::string(dex_location)
1649 + " (canonical path " + dex_canonical_location + ") in OatFile " + GetLocation();
1650 }
1651 return nullptr;
Vladimir Marko3f5838d2014-08-07 18:07:18 +01001652 }
Brian Carlstrom756ee4e2013-10-03 15:46:12 -07001653
Richard Uhler9a37efc2016-08-05 16:32:55 -07001654 if (dex_location_checksum != nullptr &&
1655 oat_dex_file->GetDexFileLocationChecksum() != *dex_location_checksum) {
1656 if (error_msg != nullptr) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -07001657 std::string dex_canonical_location = DexFileLoader::GetDexCanonicalLocation(dex_location);
Richard Uhler9a37efc2016-08-05 16:32:55 -07001658 std::string checksum = StringPrintf("0x%08x", oat_dex_file->GetDexFileLocationChecksum());
1659 std::string required_checksum = StringPrintf("0x%08x", *dex_location_checksum);
1660 *error_msg = "OatDexFile for DexFile " + std::string(dex_location)
1661 + " (canonical path " + dex_canonical_location + ") in OatFile " + GetLocation()
1662 + " has checksum " + checksum + " but " + required_checksum + " was required";
Brian Carlstrom0d6adac2014-02-05 17:39:16 -08001663 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001664 return nullptr;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001665 }
Richard Uhler9a37efc2016-08-05 16:32:55 -07001666 return oat_dex_file;
Brian Carlstromaded5f72011-10-07 17:15:04 -07001667}
1668
Brian Carlstrome24fa612011-09-29 00:53:55 -07001669OatFile::OatDexFile::OatDexFile(const OatFile* oat_file,
Elliott Hughesaa6a5882012-01-13 19:39:16 -08001670 const std::string& dex_file_location,
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001671 const std::string& canonical_dex_file_location,
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001672 uint32_t dex_file_location_checksum,
Ian Rogers13735952014-10-08 12:43:28 -07001673 const uint8_t* dex_file_pointer,
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001674 const uint8_t* lookup_table_data,
Vladimir Markof3c52b42017-11-17 17:32:12 +00001675 const IndexBssMapping* method_bss_mapping_data,
1676 const IndexBssMapping* type_bss_mapping_data,
1677 const IndexBssMapping* string_bss_mapping_data,
Vladimir Marko09d09432015-09-08 13:47:48 +01001678 const uint32_t* oat_class_offsets_pointer,
Mathieu Chartier120aa282017-08-05 16:03:03 -07001679 const DexLayoutSections* dex_layout_sections)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001680 : oat_file_(oat_file),
1681 dex_file_location_(dex_file_location),
Vladimir Markoaa4497d2014-09-05 14:01:17 +01001682 canonical_dex_file_location_(canonical_dex_file_location),
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001683 dex_file_location_checksum_(dex_file_location_checksum),
Brian Carlstrom89521892011-12-07 22:05:07 -08001684 dex_file_pointer_(dex_file_pointer),
Artem Udovichenkod9786b02015-10-14 16:36:55 +03001685 lookup_table_data_(lookup_table_data),
Vladimir Marko0eb882b2017-05-15 13:39:18 +01001686 method_bss_mapping_(method_bss_mapping_data),
Vladimir Markof3c52b42017-11-17 17:32:12 +00001687 type_bss_mapping_(type_bss_mapping_data),
1688 string_bss_mapping_(string_bss_mapping_data),
Vladimir Marko09d09432015-09-08 13:47:48 +01001689 oat_class_offsets_pointer_(oat_class_offsets_pointer),
Mathieu Chartier120aa282017-08-05 16:03:03 -07001690 dex_layout_sections_(dex_layout_sections) {
David Sehr9aa352e2016-09-15 18:13:52 -07001691 // Initialize TypeLookupTable.
1692 if (lookup_table_data_ != nullptr) {
1693 // Peek the number of classes from the DexFile.
1694 const DexFile::Header* dex_header = reinterpret_cast<const DexFile::Header*>(dex_file_pointer_);
1695 const uint32_t num_class_defs = dex_header->class_defs_size_;
1696 if (lookup_table_data_ + TypeLookupTable::RawDataLength(num_class_defs) > GetOatFile()->End()) {
1697 LOG(WARNING) << "found truncated lookup table in " << dex_file_location_;
1698 } else {
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08001699 const uint8_t* dex_data = dex_file_pointer_;
1700 // TODO: Clean this up to create the type lookup table after the dex file has been created?
1701 if (CompactDexFile::IsMagicValid(dex_header->magic_)) {
1702 dex_data += dex_header->data_off_;
1703 }
1704 lookup_table_ = TypeLookupTable::Open(dex_data, lookup_table_data_, num_class_defs);
David Sehr9aa352e2016-09-15 18:13:52 -07001705 }
1706 }
1707}
Brian Carlstrome24fa612011-09-29 00:53:55 -07001708
Mathieu Chartier1b868492016-11-16 16:22:37 -08001709OatFile::OatDexFile::OatDexFile(std::unique_ptr<TypeLookupTable>&& lookup_table)
1710 : lookup_table_(std::move(lookup_table)) {}
1711
Brian Carlstrome24fa612011-09-29 00:53:55 -07001712OatFile::OatDexFile::~OatDexFile() {}
1713
Ian Rogers05f28c62012-10-23 18:12:13 -07001714size_t OatFile::OatDexFile::FileSize() const {
1715 return reinterpret_cast<const DexFile::Header*>(dex_file_pointer_)->file_size_;
1716}
1717
Igor Murashkinb1d8c312015-08-04 11:18:43 -07001718std::unique_ptr<const DexFile> OatFile::OatDexFile::OpenDexFile(std::string* error_msg) const {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001719 ScopedTrace trace(__PRETTY_FUNCTION__);
Aart Bik37d6a3b2016-06-21 18:30:10 -07001720 static constexpr bool kVerify = false;
1721 static constexpr bool kVerifyChecksum = false;
David Sehr013fd802018-01-11 22:55:24 -08001722 const ArtDexFileLoader dex_file_loader;
1723 return dex_file_loader.Open(dex_file_pointer_,
1724 FileSize(),
1725 dex_file_location_,
1726 dex_file_location_checksum_,
1727 this,
1728 kVerify,
1729 kVerifyChecksum,
1730 error_msg);
Brian Carlstrom89521892011-12-07 22:05:07 -08001731}
1732
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001733uint32_t OatFile::OatDexFile::GetOatClassOffset(uint16_t class_def_index) const {
1734 return oat_class_offsets_pointer_[class_def_index];
1735}
1736
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001737OatFile::OatClass OatFile::OatDexFile::GetOatClass(uint16_t class_def_index) const {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001738 uint32_t oat_class_offset = GetOatClassOffset(class_def_index);
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001739
Ian Rogers13735952014-10-08 12:43:28 -07001740 const uint8_t* oat_class_pointer = oat_file_->Begin() + oat_class_offset;
Brian Carlstrom7571e8b2013-08-12 17:04:14 -07001741 CHECK_LT(oat_class_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001742
Ian Rogers13735952014-10-08 12:43:28 -07001743 const uint8_t* status_pointer = oat_class_pointer;
Brian Carlstromba150c32013-08-27 17:31:03 -07001744 CHECK_LT(status_pointer, oat_file_->End()) << oat_file_->GetLocation();
Vladimir Marko2c64a832018-01-04 11:31:56 +00001745 ClassStatus status = enum_cast<ClassStatus>(*reinterpret_cast<const int16_t*>(status_pointer));
1746 CHECK_LE(status, ClassStatus::kLast);
Brian Carlstromba150c32013-08-27 17:31:03 -07001747
Ian Rogers13735952014-10-08 12:43:28 -07001748 const uint8_t* type_pointer = status_pointer + sizeof(uint16_t);
Brian Carlstromba150c32013-08-27 17:31:03 -07001749 CHECK_LT(type_pointer, oat_file_->End()) << oat_file_->GetLocation();
1750 OatClassType type = static_cast<OatClassType>(*reinterpret_cast<const uint16_t*>(type_pointer));
1751 CHECK_LT(type, kOatClassMax);
1752
Ian Rogers13735952014-10-08 12:43:28 -07001753 const uint8_t* after_type_pointer = type_pointer + sizeof(int16_t);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001754 CHECK_LE(after_type_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07001755
Brian Carlstromcd937a92014-03-04 22:53:23 -08001756 uint32_t bitmap_size = 0;
Ian Rogers13735952014-10-08 12:43:28 -07001757 const uint8_t* bitmap_pointer = nullptr;
1758 const uint8_t* methods_pointer = nullptr;
Ian Rogers97b52f82014-08-14 11:34:07 -07001759 if (type != kOatClassNoneCompiled) {
1760 if (type == kOatClassSomeCompiled) {
1761 bitmap_size = static_cast<uint32_t>(*reinterpret_cast<const uint32_t*>(after_type_pointer));
1762 bitmap_pointer = after_type_pointer + sizeof(bitmap_size);
1763 CHECK_LE(bitmap_pointer, oat_file_->End()) << oat_file_->GetLocation();
1764 methods_pointer = bitmap_pointer + bitmap_size;
1765 } else {
1766 methods_pointer = after_type_pointer;
1767 }
1768 CHECK_LE(methods_pointer, oat_file_->End()) << oat_file_->GetLocation();
Brian Carlstromcd937a92014-03-04 22:53:23 -08001769 }
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001770
Richard Uhler07b3c232015-03-31 15:57:54 -07001771 return OatFile::OatClass(oat_file_,
1772 status,
1773 type,
1774 bitmap_size,
1775 reinterpret_cast<const uint32_t*>(bitmap_pointer),
1776 reinterpret_cast<const OatMethodOffsets*>(methods_pointer));
Brian Carlstrome24fa612011-09-29 00:53:55 -07001777}
1778
David Sehr9aa352e2016-09-15 18:13:52 -07001779const DexFile::ClassDef* OatFile::OatDexFile::FindClassDef(const DexFile& dex_file,
1780 const char* descriptor,
1781 size_t hash) {
1782 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1783 DCHECK_EQ(ComputeModifiedUtf8Hash(descriptor), hash);
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08001784 bool used_lookup_table = false;
1785 const DexFile::ClassDef* lookup_table_classdef = nullptr;
David Sehr9aa352e2016-09-15 18:13:52 -07001786 if (LIKELY((oat_dex_file != nullptr) && (oat_dex_file->GetTypeLookupTable() != nullptr))) {
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08001787 used_lookup_table = true;
David Sehr9aa352e2016-09-15 18:13:52 -07001788 const uint32_t class_def_idx = oat_dex_file->GetTypeLookupTable()->Lookup(descriptor, hash);
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08001789 lookup_table_classdef = (class_def_idx != dex::kDexNoIndex)
1790 ? &dex_file.GetClassDef(class_def_idx)
1791 : nullptr;
1792 if (!kIsDebugBuild) {
1793 return lookup_table_classdef;
1794 }
David Sehr9aa352e2016-09-15 18:13:52 -07001795 }
1796 // Fast path for rare no class defs case.
1797 const uint32_t num_class_defs = dex_file.NumClassDefs();
1798 if (num_class_defs == 0) {
1799 return nullptr;
1800 }
1801 const DexFile::TypeId* type_id = dex_file.FindTypeId(descriptor);
1802 if (type_id != nullptr) {
Andreas Gampea5b09a62016-11-17 15:21:22 -08001803 dex::TypeIndex type_idx = dex_file.GetIndexForTypeId(*type_id);
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -08001804 const DexFile::ClassDef* found_class_def = dex_file.FindClassDef(type_idx);
1805 if (kIsDebugBuild && used_lookup_table) {
1806 DCHECK_EQ(found_class_def, lookup_table_classdef);
1807 }
1808 return found_class_def;
David Sehr9aa352e2016-09-15 18:13:52 -07001809 }
1810 return nullptr;
1811}
1812
Mathieu Chartier120aa282017-08-05 16:03:03 -07001813// Madvise the dex file based on the state we are moving to.
1814void OatDexFile::MadviseDexFile(const DexFile& dex_file, MadviseState state) {
Mathieu Chartierc42cb0e2017-10-13 11:35:00 -07001815 Runtime* const runtime = Runtime::Current();
1816 const bool low_ram = runtime->GetHeap()->IsLowMemoryMode();
Mathieu Chartier150d25d2017-08-28 09:52:55 -07001817 // TODO: Also do madvise hints for non low ram devices.
Mathieu Chartierc42cb0e2017-10-13 11:35:00 -07001818 if (!low_ram) {
Mathieu Chartierbe8303d2017-08-17 17:39:39 -07001819 return;
1820 }
Mathieu Chartierc42cb0e2017-10-13 11:35:00 -07001821 if (state == MadviseState::kMadviseStateAtLoad && runtime->MAdviseRandomAccess()) {
1822 // Default every dex file to MADV_RANDOM when its loaded by default for low ram devices.
1823 // Other devices have enough page cache to get performance benefits from loading more pages
1824 // into the page cache.
David Sehrc431b9d2018-03-02 12:01:51 -08001825 DexLayoutSection::MadviseLargestPageAlignedRegion(dex_file.Begin(),
1826 dex_file.Begin() + dex_file.Size(),
1827 MADV_RANDOM);
Mathieu Chartier120aa282017-08-05 16:03:03 -07001828 }
1829 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
1830 if (oat_dex_file != nullptr) {
1831 // Should always be there.
1832 const DexLayoutSections* const sections = oat_dex_file->GetDexLayoutSections();
1833 CHECK(sections != nullptr);
1834 sections->Madvise(&dex_file, state);
1835 }
1836}
1837
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001838OatFile::OatClass::OatClass(const OatFile* oat_file,
Vladimir Marko2c64a832018-01-04 11:31:56 +00001839 ClassStatus status,
Brian Carlstromba150c32013-08-27 17:31:03 -07001840 OatClassType type,
1841 uint32_t bitmap_size,
1842 const uint32_t* bitmap_pointer,
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001843 const OatMethodOffsets* methods_pointer)
Brian Carlstromba150c32013-08-27 17:31:03 -07001844 : oat_file_(oat_file), status_(status), type_(type),
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001845 bitmap_(bitmap_pointer), methods_pointer_(methods_pointer) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001846 switch (type_) {
1847 case kOatClassAllCompiled: {
1848 CHECK_EQ(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001849 CHECK(bitmap_pointer == nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001850 CHECK(methods_pointer != nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001851 break;
1852 }
1853 case kOatClassSomeCompiled: {
1854 CHECK_NE(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001855 CHECK(bitmap_pointer != nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001856 CHECK(methods_pointer != nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001857 break;
1858 }
1859 case kOatClassNoneCompiled: {
1860 CHECK_EQ(0U, bitmap_size);
Brian Carlstromcd937a92014-03-04 22:53:23 -08001861 CHECK(bitmap_pointer == nullptr);
Ian Rogers97b52f82014-08-14 11:34:07 -07001862 CHECK(methods_pointer_ == nullptr);
Brian Carlstromba150c32013-08-27 17:31:03 -07001863 break;
1864 }
1865 case kOatClassMax: {
1866 LOG(FATAL) << "Invalid OatClassType " << type_;
1867 break;
1868 }
1869 }
1870}
Brian Carlstrome24fa612011-09-29 00:53:55 -07001871
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001872uint32_t OatFile::OatClass::GetOatMethodOffsetsOffset(uint32_t method_index) const {
1873 const OatMethodOffsets* oat_method_offsets = GetOatMethodOffsets(method_index);
1874 if (oat_method_offsets == nullptr) {
1875 return 0u;
1876 }
1877 return reinterpret_cast<const uint8_t*>(oat_method_offsets) - oat_file_->Begin();
1878}
1879
1880const OatMethodOffsets* OatFile::OatClass::GetOatMethodOffsets(uint32_t method_index) const {
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001881 // 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 -07001882 if (methods_pointer_ == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001883 CHECK_EQ(kOatClassNoneCompiled, type_);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001884 return nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07001885 }
1886 size_t methods_pointer_index;
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001887 if (bitmap_ == nullptr) {
Brian Carlstromba150c32013-08-27 17:31:03 -07001888 CHECK_EQ(kOatClassAllCompiled, type_);
1889 methods_pointer_index = method_index;
1890 } else {
1891 CHECK_EQ(kOatClassSomeCompiled, type_);
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001892 if (!BitVector::IsBitSet(bitmap_, method_index)) {
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001893 return nullptr;
Brian Carlstromba150c32013-08-27 17:31:03 -07001894 }
Vladimir Markod3c5beb2014-04-11 16:32:51 +01001895 size_t num_set_bits = BitVector::NumSetBits(bitmap_, method_index);
1896 methods_pointer_index = num_set_bits;
Brian Carlstromba150c32013-08-27 17:31:03 -07001897 }
1898 const OatMethodOffsets& oat_method_offsets = methods_pointer_[methods_pointer_index];
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001899 return &oat_method_offsets;
1900}
1901
1902const OatFile::OatMethod OatFile::OatClass::GetOatMethod(uint32_t method_index) const {
1903 const OatMethodOffsets* oat_method_offsets = GetOatMethodOffsets(method_index);
1904 if (oat_method_offsets == nullptr) {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001905 return OatMethod(nullptr, 0);
Brian Carlstrom2cbaccb2014-09-14 20:34:17 -07001906 }
1907 if (oat_file_->IsExecutable() ||
1908 Runtime::Current() == nullptr || // This case applies for oatdump.
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001909 Runtime::Current()->IsAotCompiler()) {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001910 return OatMethod(oat_file_->Begin(), oat_method_offsets->code_offset_);
Alex Light9dcc4572014-08-14 14:16:26 -07001911 }
Mathieu Chartiere5f13e52015-02-24 09:37:21 -08001912 // We aren't allowed to use the compiled code. We just force it down the interpreted / jit
1913 // version.
1914 return OatMethod(oat_file_->Begin(), 0);
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001915}
1916
Mathieu Chartiere401d142015-04-22 13:56:20 -07001917void OatFile::OatMethod::LinkMethod(ArtMethod* method) const {
Andreas Gampefa8429b2015-04-07 18:34:42 -07001918 CHECK(method != nullptr);
Ian Rogersef7d42f2014-01-06 12:55:46 -08001919 method->SetEntryPointFromQuickCompiledCode(GetQuickCode());
Brian Carlstromae826982011-11-09 01:33:42 -08001920}
1921
Andreas Gampe7ba64962014-10-23 11:37:40 -07001922bool OatFile::IsPic() const {
Igor Murashkin46774762014-10-22 11:37:02 -07001923 return GetOatHeader().IsPic();
Andreas Gampe7ba64962014-10-23 11:37:40 -07001924 // TODO: Check against oat_patches. b/18144996
1925}
1926
Sebastien Hertz0de11332015-05-13 12:14:05 +02001927bool OatFile::IsDebuggable() const {
1928 return GetOatHeader().IsDebuggable();
1929}
1930
Andreas Gampe29d38e72016-03-23 15:31:51 +00001931CompilerFilter::Filter OatFile::GetCompilerFilter() const {
1932 return GetOatHeader().GetCompilerFilter();
Calin Juravleb077e152016-02-18 18:47:37 +00001933}
1934
Calin Juravle44e5efa2017-09-12 00:54:26 -07001935std::string OatFile::GetClassLoaderContext() const {
1936 return GetOatHeader().GetStoreValueByKey(OatHeader::kClassPathKey);
Igor Murashkin2ffb7032017-11-08 13:35:21 -08001937}
Calin Juravle44e5efa2017-09-12 00:54:26 -07001938
Calin Juravle0e09dfc2018-02-12 19:01:09 -08001939const char* OatFile::GetCompilationReason() const {
1940 return GetOatHeader().GetStoreValueByKey(OatHeader::kCompilationReasonKey);
1941}
1942
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001943OatFile::OatClass OatFile::FindOatClass(const DexFile& dex_file,
1944 uint16_t class_def_idx,
1945 bool* found) {
1946 DCHECK_NE(class_def_idx, DexFile::kDexNoIndex16);
1947 const OatFile::OatDexFile* oat_dex_file = dex_file.GetOatDexFile();
Mathieu Chartier1b868492016-11-16 16:22:37 -08001948 if (oat_dex_file == nullptr || oat_dex_file->GetOatFile() == nullptr) {
Vladimir Marko97d7e1c2016-10-04 14:44:28 +01001949 *found = false;
1950 return OatFile::OatClass::Invalid();
1951 }
1952 *found = true;
1953 return oat_dex_file->GetOatClass(class_def_idx);
1954}
1955
Mathieu Chartier1b868492016-11-16 16:22:37 -08001956void OatFile::OatDexFile::AssertAotCompiler() {
1957 CHECK(Runtime::Current()->IsAotCompiler());
1958}
1959
Brian Carlstrome24fa612011-09-29 00:53:55 -07001960} // namespace art