blob: d50528edee931787978d51785ccfd15d455d6617 [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
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 */
16
17#include "image_writer.h"
18
19#include <sys/stat.h>
Mathieu Chartierceb07b32015-12-10 09:33:21 -080020#include <lz4.h>
Brian Carlstrom7940e442013-07-12 13:46:57 -070021
Ian Rogers700a4022014-05-19 16:49:03 -070022#include <memory>
Vladimir Marko20f85592015-03-19 10:07:02 +000023#include <numeric>
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080024#include <unordered_set>
Brian Carlstrom7940e442013-07-12 13:46:57 -070025#include <vector>
26
Mathieu Chartierc7853442015-03-27 14:35:38 -070027#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070028#include "art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070029#include "base/logging.h"
30#include "base/unix_file/fd_file.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010031#include "class_linker-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070032#include "compiled_method.h"
33#include "dex_file-inl.h"
34#include "driver/compiler_driver.h"
Alex Light53cb16b2014-06-12 11:26:29 -070035#include "elf_file.h"
36#include "elf_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070037#include "elf_writer.h"
38#include "gc/accounting/card_table-inl.h"
39#include "gc/accounting/heap_bitmap.h"
Mathieu Chartier31e89252013-08-28 11:29:12 -070040#include "gc/accounting/space_bitmap-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070041#include "gc/heap.h"
42#include "gc/space/large_object_space.h"
43#include "gc/space/space-inl.h"
44#include "globals.h"
45#include "image.h"
46#include "intern_table.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070047#include "linear_alloc.h"
Mathieu Chartierad2541a2013-10-25 10:05:23 -070048#include "lock_word.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070049#include "mirror/abstract_method.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070050#include "mirror/array-inl.h"
51#include "mirror/class-inl.h"
52#include "mirror/class_loader.h"
53#include "mirror/dex_cache-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070054#include "mirror/method.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070055#include "mirror/object-inl.h"
56#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070057#include "mirror/string-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070058#include "oat.h"
59#include "oat_file.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070060#include "oat_file_manager.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070061#include "runtime.h"
62#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070063#include "handle_scope-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000064#include "utils/dex_cache_arrays_layout-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070065
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070066using ::art::mirror::Class;
67using ::art::mirror::DexCache;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070068using ::art::mirror::Object;
69using ::art::mirror::ObjectArray;
70using ::art::mirror::String;
Brian Carlstrom7940e442013-07-12 13:46:57 -070071
72namespace art {
73
Igor Murashkinf5b4c502014-11-14 15:01:59 -080074// Separate objects into multiple bins to optimize dirty memory use.
75static constexpr bool kBinObjects = true;
76
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080077// Return true if an object is already in an image space.
78bool ImageWriter::IsInBootImage(const void* obj) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080079 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080080 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080081 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080082 return false;
83 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -080084 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
85 const uint8_t* image_begin = boot_image_space->Begin();
86 // Real image end including ArtMethods and ArtField sections.
87 const uint8_t* image_end = image_begin + boot_image_space->GetImageHeader().GetImageSize();
88 if (image_begin <= obj && obj < image_end) {
89 return true;
90 }
91 }
92 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080093}
94
95bool ImageWriter::IsInBootOatFile(const void* ptr) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080096 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080097 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080098 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080099 return false;
100 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800101 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
102 const ImageHeader& image_header = boot_image_space->GetImageHeader();
103 if (image_header.GetOatFileBegin() <= ptr && ptr < image_header.GetOatFileEnd()) {
104 return true;
105 }
106 }
107 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800108}
109
Andreas Gampedd9d0552015-03-09 12:57:41 -0700110static void CheckNoDexObjectsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700111 SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampedd9d0552015-03-09 12:57:41 -0700112 Class* klass = obj->GetClass();
113 CHECK_NE(PrettyClass(klass), "com.android.dex.Dex");
114}
115
116static void CheckNoDexObjects() {
117 ScopedObjectAccess soa(Thread::Current());
118 Runtime::Current()->GetHeap()->VisitObjects(CheckNoDexObjectsCallback, nullptr);
119}
120
Vladimir Markof4da6752014-08-01 19:04:18 +0100121bool ImageWriter::PrepareImageAddressSpace() {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800122 target_ptr_size_ = InstructionSetPointerSize(compiler_driver_.GetInstructionSet());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800123 gc::Heap* const heap = Runtime::Current()->GetHeap();
Vladimir Markof4da6752014-08-01 19:04:18 +0100124 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700125 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof4da6752014-08-01 19:04:18 +0100126 PruneNonImageClasses(); // Remove junk
Mathieu Chartier901e0702016-02-19 13:42:48 -0800127 if (!compile_app_image_) {
128 // Avoid for app image since this may increase RAM and image size.
129 ComputeLazyFieldsForImageClasses(); // Add useful information
130 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100131 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100132 heap->CollectGarbage(false); // Remove garbage.
133
Andreas Gampedd9d0552015-03-09 12:57:41 -0700134 // Dex caches must not have their dex fields set in the image. These are memory buffers of mapped
135 // dex files.
136 //
137 // We may open them in the unstarted-runtime code for class metadata. Their fields should all be
138 // reset in PruneNonImageClasses and the objects reclaimed in the GC. Make sure that's actually
139 // true.
140 if (kIsDebugBuild) {
141 CheckNoDexObjects();
142 }
143
Vladimir Markof4da6752014-08-01 19:04:18 +0100144 if (kIsDebugBuild) {
145 ScopedObjectAccess soa(Thread::Current());
146 CheckNonImageClassesRemoved();
147 }
148
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700149 {
150 ScopedObjectAccess soa(Thread::Current());
151 CalculateNewObjectOffsets();
152 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100153
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700154 // This needs to happen after CalculateNewObjectOffsets since it relies on intern_table_bytes_ and
155 // bin size sums being calculated.
156 if (!AllocMemory()) {
157 return false;
158 }
159
Vladimir Markof4da6752014-08-01 19:04:18 +0100160 return true;
161}
162
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700163bool ImageWriter::Write(int image_fd,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800164 const std::vector<const char*>& image_filenames,
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800165 int oat_fd,
166 const std::vector<const char*>& oat_filenames,
167 const std::string& oat_location) {
168 // If image_fd or oat_fd are not kInvalidFd then we may have empty strings in image_filenames or
169 // oat_filenames.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800170 CHECK(!image_filenames.empty());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800171 if (image_fd != kInvalidFd) {
172 CHECK_EQ(image_filenames.size(), 1u);
173 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800174 CHECK(!oat_filenames.empty());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800175 if (oat_fd != kInvalidFd) {
176 CHECK_EQ(oat_filenames.size(), 1u);
177 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800178 CHECK_EQ(image_filenames.size(), oat_filenames.size());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700179
Jeff Haodcdc85b2015-12-04 14:06:18 -0800180 size_t oat_file_offset = 0;
181
182 for (size_t i = 0; i < oat_filenames.size(); ++i) {
183 const char* oat_filename = oat_filenames[i];
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800184 std::unique_ptr<File> oat_file;
185
186 if (oat_fd != -1) {
187 if (strlen(oat_filename) == 0u) {
188 oat_file.reset(new File(oat_fd, false));
189 } else {
190 oat_file.reset(new File(oat_fd, oat_filename, false));
191 }
192 int length = oat_file->GetLength();
193 if (length < 0) {
194 PLOG(ERROR) << "Oat file has negative length " << length;
195 return false;
196 } else {
197 // Leave the fd open since dex2oat still needs to write out the oat file with the fd.
198 oat_file->DisableAutoClose();
199 }
200 } else {
201 oat_file.reset(OS::OpenFileReadWrite(oat_filename));
202 }
203 if (oat_file == nullptr) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800204 PLOG(ERROR) << "Failed to open oat file " << oat_filename;
205 return false;
206 }
207 std::string error_msg;
208 oat_file_ = OatFile::OpenReadable(oat_file.get(), oat_filename, nullptr, &error_msg);
209 if (oat_file_ == nullptr) {
210 PLOG(ERROR) << "Failed to open writable oat file " << oat_filename;
211 oat_file->Erase();
212 return false;
213 }
214 Runtime::Current()->GetOatFileManager().RegisterOatFile(
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800215 std::unique_ptr<const OatFile>(oat_file_));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700216
Jeff Haodcdc85b2015-12-04 14:06:18 -0800217 const OatHeader& oat_header = oat_file_->GetOatHeader();
218 ImageInfo& image_info = GetImageInfo(oat_filename);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700219
Jeff Haodcdc85b2015-12-04 14:06:18 -0800220 size_t oat_loaded_size = 0;
221 size_t oat_data_offset = 0;
222 ElfWriter::GetOatElfInformation(oat_file.get(), &oat_loaded_size, &oat_data_offset);
223
224 DCHECK_EQ(image_info.oat_offset_, oat_file_offset);
225 oat_file_offset += oat_loaded_size;
226
227 if (i == 0) {
228 // Primary oat file, read the trampolines.
229 image_info.oat_address_offsets_[kOatAddressInterpreterToInterpreterBridge] =
230 oat_header.GetInterpreterToInterpreterBridgeOffset();
231 image_info.oat_address_offsets_[kOatAddressInterpreterToCompiledCodeBridge] =
232 oat_header.GetInterpreterToCompiledCodeBridgeOffset();
233 image_info.oat_address_offsets_[kOatAddressJNIDlsymLookup] =
234 oat_header.GetJniDlsymLookupOffset();
235 image_info.oat_address_offsets_[kOatAddressQuickGenericJNITrampoline] =
236 oat_header.GetQuickGenericJniTrampolineOffset();
237 image_info.oat_address_offsets_[kOatAddressQuickIMTConflictTrampoline] =
238 oat_header.GetQuickImtConflictTrampolineOffset();
239 image_info.oat_address_offsets_[kOatAddressQuickResolutionTrampoline] =
240 oat_header.GetQuickResolutionTrampolineOffset();
241 image_info.oat_address_offsets_[kOatAddressQuickToInterpreterBridge] =
242 oat_header.GetQuickToInterpreterBridgeOffset();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800243 }
244
245
246 {
247 ScopedObjectAccess soa(Thread::Current());
248 CreateHeader(oat_loaded_size, oat_data_offset);
249 CopyAndFixupNativeData();
250 }
251
252 SetOatChecksumFromElfFile(oat_file.get());
253
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800254 if (oat_fd != -1) {
255 // Leave fd open for caller.
256 if (oat_file->Flush() != 0) {
257 LOG(ERROR) << "Failed to flush oat file " << oat_filename << " for " << oat_location;
258 return false;
259 }
260 } else if (oat_file->FlushCloseOrErase() != 0) {
261 LOG(ERROR) << "Failed to flush and close oat file " << oat_filename
262 << " for " << oat_location;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800263 return false;
264 }
265 }
Alex Light53cb16b2014-06-12 11:26:29 -0700266
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700267 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700268 // TODO: heap validation can't handle these fix up passes.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800269 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700270 Runtime::Current()->GetHeap()->DisableObjectValidation();
271 CopyAndFixupObjects();
272 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700273
Jeff Haodcdc85b2015-12-04 14:06:18 -0800274 for (size_t i = 0; i < image_filenames.size(); ++i) {
275 const char* image_filename = image_filenames[i];
276 const char* oat_filename = oat_filenames[i];
277 ImageInfo& image_info = GetImageInfo(oat_filename);
278 std::unique_ptr<File> image_file;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800279 if (image_fd != kInvalidFd) {
280 if (strlen(image_filename) == 0u) {
281 image_file.reset(new File(image_fd, unix_file::kCheckSafeUsage));
Mathieu Chartier784bb092016-01-28 12:02:00 -0800282 // Empty the file in case it already exists.
283 if (image_file != nullptr) {
284 TEMP_FAILURE_RETRY(image_file->SetLength(0));
285 TEMP_FAILURE_RETRY(image_file->Flush());
286 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800287 } else {
288 LOG(ERROR) << "image fd " << image_fd << " name " << image_filename;
289 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800290 } else {
291 image_file.reset(OS::CreateEmptyFile(image_filename));
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800292 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800293
Jeff Haodcdc85b2015-12-04 14:06:18 -0800294 if (image_file == nullptr) {
295 LOG(ERROR) << "Failed to open image file " << image_filename;
296 return false;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800297 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800298
299 if (!compile_app_image_ && fchmod(image_file->Fd(), 0644) != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800300 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
301 image_file->Erase();
302 return EXIT_FAILURE;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800303 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800304
Jeff Haodcdc85b2015-12-04 14:06:18 -0800305 std::unique_ptr<char[]> compressed_data;
306 // Image data size excludes the bitmap and the header.
307 ImageHeader* const image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
308 const size_t image_data_size = image_header->GetImageSize() - sizeof(ImageHeader);
309 char* image_data = reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader);
310 size_t data_size;
311 const char* image_data_to_write;
Nicolas Geoffray83d4d722015-12-10 08:26:32 +0000312
Jeff Haodcdc85b2015-12-04 14:06:18 -0800313 CHECK_EQ(image_header->storage_mode_, image_storage_mode_);
314 switch (image_storage_mode_) {
315 case ImageHeader::kStorageModeLZ4: {
316 size_t compressed_max_size = LZ4_compressBound(image_data_size);
317 compressed_data.reset(new char[compressed_max_size]);
318 data_size = LZ4_compress(
319 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
320 &compressed_data[0],
321 image_data_size);
322 image_data_to_write = &compressed_data[0];
323 VLOG(compiler) << "Compressed from " << image_data_size << " to " << data_size;
324 break;
325 }
326 case ImageHeader::kStorageModeUncompressed: {
327 data_size = image_data_size;
328 image_data_to_write = image_data;
329 break;
330 }
331 default: {
332 LOG(FATAL) << "Unsupported";
333 UNREACHABLE();
334 }
335 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800336
Jeff Haodcdc85b2015-12-04 14:06:18 -0800337 // Write header first, as uncompressed.
338 image_header->data_size_ = data_size;
339 if (!image_file->WriteFully(image_info.image_->Begin(), sizeof(ImageHeader))) {
340 PLOG(ERROR) << "Failed to write image file header " << image_filename;
341 image_file->Erase();
342 return false;
343 }
344
345 // Write out the image + fields + methods.
346 const bool is_compressed = compressed_data != nullptr;
347 if (!image_file->WriteFully(image_data_to_write, data_size)) {
348 PLOG(ERROR) << "Failed to write image file data " << image_filename;
349 image_file->Erase();
350 return false;
351 }
352
353 // Write out the image bitmap at the page aligned start of the image end, also uncompressed for
354 // convenience.
355 const ImageSection& bitmap_section = image_header->GetImageSection(
356 ImageHeader::kSectionImageBitmap);
357 // Align up since data size may be unaligned if the image is compressed.
358 size_t bitmap_position_in_file = RoundUp(sizeof(ImageHeader) + data_size, kPageSize);
359 if (!is_compressed) {
360 CHECK_EQ(bitmap_position_in_file, bitmap_section.Offset());
361 }
362 if (!image_file->Write(reinterpret_cast<char*>(image_info.image_bitmap_->Begin()),
363 bitmap_section.Size(),
364 bitmap_position_in_file)) {
365 PLOG(ERROR) << "Failed to write image file " << image_filename;
366 image_file->Erase();
367 return false;
368 }
369 CHECK_EQ(bitmap_position_in_file + bitmap_section.Size(),
370 static_cast<size_t>(image_file->GetLength()));
371 if (image_file->FlushCloseOrErase() != 0) {
372 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
373 return false;
374 }
Andreas Gampe4303ba92014-11-06 01:00:46 -0800375 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700376 return true;
377}
378
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700379void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700380 DCHECK(object != nullptr);
381 DCHECK_NE(offset, 0U);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800382
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800383 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700384 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700385 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700386 DCHECK(IsImageOffsetAssigned(object));
387}
388
Mathieu Chartiere401d142015-04-22 13:56:20 -0700389void ImageWriter::UpdateImageOffset(mirror::Object* obj, uintptr_t offset) {
390 DCHECK(IsImageOffsetAssigned(obj)) << obj << " " << offset;
391 obj->SetLockWord(LockWord::FromForwardingAddress(offset), false);
392 DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0u);
393}
394
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800395void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700396 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800397 DCHECK_NE(image_objects_offset_begin_, 0u);
398
Jeff Haodcdc85b2015-12-04 14:06:18 -0800399 const char* oat_filename = GetOatFilename(object);
400 ImageInfo& image_info = GetImageInfo(oat_filename);
401 size_t bin_slot_offset = image_info.bin_slot_offsets_[bin_slot.GetBin()];
Vladimir Markocf36d492015-08-12 19:27:26 +0100402 size_t new_offset = bin_slot_offset + bin_slot.GetIndex();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800403 DCHECK_ALIGNED(new_offset, kObjectAlignment);
404
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700405 SetImageOffset(object, new_offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800406 DCHECK_LT(new_offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700407}
408
Ian Rogersef7d42f2014-01-06 12:55:46 -0800409bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800410 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700411 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700412 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700413}
414
Ian Rogersef7d42f2014-01-06 12:55:46 -0800415size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700416 DCHECK(object != nullptr);
417 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700418 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700419 size_t offset = lock_word.ForwardingAddress();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800420 const char* oat_filename = GetOatFilename(object);
421 const ImageInfo& image_info = GetConstImageInfo(oat_filename);
422 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700423 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700424}
425
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800426void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
427 DCHECK(object != nullptr);
428 DCHECK(!IsImageOffsetAssigned(object));
429 DCHECK(!IsImageBinSlotAssigned(object));
430
431 // Before we stomp over the lock word, save the hash code for later.
432 Monitor::Deflate(Thread::Current(), object);;
433 LockWord lw(object->GetLockWord(false));
434 switch (lw.GetState()) {
435 case LockWord::kFatLocked: {
436 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
437 break;
438 }
439 case LockWord::kThinLocked: {
440 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
441 break;
442 }
443 case LockWord::kUnlocked:
444 // No hash, don't need to save it.
445 break;
446 case LockWord::kHashCode:
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700447 DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
448 saved_hashcode_map_.emplace(object, lw.GetHashCode());
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800449 break;
450 default:
451 LOG(FATAL) << "Unreachable.";
452 UNREACHABLE();
453 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700454 object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700455 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800456 DCHECK(IsImageBinSlotAssigned(object));
457}
458
Vladimir Marko20f85592015-03-19 10:07:02 +0000459void ImageWriter::PrepareDexCacheArraySlots() {
Vladimir Markof60c7e22015-11-23 18:05:08 +0000460 // Prepare dex cache array starts based on the ordering specified in the CompilerDriver.
Vladimir Markof60c7e22015-11-23 18:05:08 +0000461 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
462 // when AssignImageBinSlot() assigns their indexes out or order.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800463 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
464 auto it = dex_file_oat_filename_map_.find(dex_file);
465 DCHECK(it != dex_file_oat_filename_map_.end()) << dex_file->GetLocation();
466 ImageInfo& image_info = GetImageInfo(it->second);
467 image_info.dex_cache_array_starts_.Put(dex_file, image_info.bin_slot_sizes_[kBinDexCacheArray]);
468 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
469 image_info.bin_slot_sizes_[kBinDexCacheArray] += layout.Size();
470 }
Vladimir Markof60c7e22015-11-23 18:05:08 +0000471
Vladimir Marko20f85592015-03-19 10:07:02 +0000472 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700473 Thread* const self = Thread::Current();
474 ReaderMutexLock mu(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800475 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700476 mirror::DexCache* dex_cache =
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800477 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800478 if (dex_cache == nullptr || IsInBootImage(dex_cache)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700479 continue;
480 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000481 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc7853442015-03-27 14:35:38 -0700482 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
Vladimir Marko20f85592015-03-19 10:07:02 +0000483 DCHECK(layout.Valid());
Jeff Haodcdc85b2015-12-04 14:06:18 -0800484 const char* oat_filename = GetOatFilenameForDexCache(dex_cache);
485 ImageInfo& image_info = GetImageInfo(oat_filename);
486 uint32_t start = image_info.dex_cache_array_starts_.Get(dex_file);
Vladimir Marko05792b92015-08-03 11:56:49 +0100487 DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800488 AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(),
489 start + layout.TypesOffset(),
490 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100491 DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800492 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(),
493 start + layout.MethodsOffset(),
494 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100495 DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800496 AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(),
497 start + layout.FieldsOffset(),
498 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100499 DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800500 AddDexCacheArrayRelocation(dex_cache->GetStrings(), start + layout.StringsOffset(), dex_cache);
Vladimir Marko20f85592015-03-19 10:07:02 +0000501 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000502}
503
Jeff Haodcdc85b2015-12-04 14:06:18 -0800504void ImageWriter::AddDexCacheArrayRelocation(void* array, size_t offset, DexCache* dex_cache) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100505 if (array != nullptr) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800506 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -0800507 const char* oat_filename = GetOatFilenameForDexCache(dex_cache);
508 native_object_relocations_.emplace(array,
509 NativeObjectRelocation { oat_filename, offset, kNativeObjectRelocationTypeDexCacheArray });
Vladimir Marko05792b92015-08-03 11:56:49 +0100510 }
511}
512
Mathieu Chartiere401d142015-04-22 13:56:20 -0700513void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) {
514 DCHECK(arr != nullptr);
515 if (kIsDebugBuild) {
516 for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800517 ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700518 if (method != nullptr && !method->IsRuntimeMethod()) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800519 mirror::Class* klass = method->GetDeclaringClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800520 CHECK(klass == nullptr || KeepClass(klass))
521 << PrettyClass(klass) << " should be a kept class";
Mathieu Chartiere401d142015-04-22 13:56:20 -0700522 }
523 }
524 }
525 // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
526 // ArtMethods.
527 pointer_arrays_.emplace(arr, kBinArtMethodClean);
528}
529
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800530void ImageWriter::AssignImageBinSlot(mirror::Object* object) {
531 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800532 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800533
534 // The magic happens here. We segregate objects into different bins based
535 // on how likely they are to get dirty at runtime.
536 //
537 // Likely-to-dirty objects get packed together into the same bin so that
538 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
539 // maximized.
540 //
541 // This means more pages will stay either clean or shared dirty (with zygote) and
542 // the app will use less of its own (private) memory.
543 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000544 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800545
546 if (kBinObjects) {
547 //
548 // Changing the bin of an object is purely a memory-use tuning.
549 // It has no change on runtime correctness.
550 //
551 // Memory analysis has determined that the following types of objects get dirtied
552 // the most:
553 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000554 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
555 // a fixed layout which helps improve generated code (using PC-relative addressing),
556 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
557 // Since these arrays are huge, most pages do not overlap other objects and it's not
558 // really important where they are for the clean/dirty separation. Due to their
Vladimir Marko05792b92015-08-03 11:56:49 +0100559 // special PC-relative addressing, we arbitrarily keep them at the end.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800560 // * Class'es which are verified [their clinit runs only at runtime]
561 // - classes in general [because their static fields get overwritten]
562 // - initialized classes with all-final statics are unlikely to be ever dirty,
563 // so bin them separately
564 // * Art Methods that are:
565 // - native [their native entry point is not looked up until runtime]
566 // - have declaring classes that aren't initialized
567 // [their interpreter/quick entry points are trampolines until the class
568 // becomes initialized]
569 //
570 // We also assume the following objects get dirtied either never or extremely rarely:
571 // * Strings (they are immutable)
572 // * Art methods that aren't native and have initialized declared classes
573 //
574 // We assume that "regular" bin objects are highly unlikely to become dirtied,
575 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
576 //
577 if (object->IsClass()) {
578 bin = kBinClassVerified;
579 mirror::Class* klass = object->AsClass();
580
Mathieu Chartiere401d142015-04-22 13:56:20 -0700581 // Add non-embedded vtable to the pointer array table if there is one.
582 auto* vtable = klass->GetVTable();
583 if (vtable != nullptr) {
584 AddMethodPointerArray(vtable);
585 }
586 auto* iftable = klass->GetIfTable();
587 if (iftable != nullptr) {
588 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
589 if (iftable->GetMethodArrayCount(i) > 0) {
590 AddMethodPointerArray(iftable->GetMethodArray(i));
591 }
592 }
593 }
594
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800595 if (klass->GetStatus() == Class::kStatusInitialized) {
596 bin = kBinClassInitialized;
597
598 // If the class's static fields are all final, put it into a separate bin
599 // since it's very likely it will stay clean.
600 uint32_t num_static_fields = klass->NumStaticFields();
601 if (num_static_fields == 0) {
602 bin = kBinClassInitializedFinalStatics;
603 } else {
604 // Maybe all the statics are final?
605 bool all_final = true;
606 for (uint32_t i = 0; i < num_static_fields; ++i) {
607 ArtField* field = klass->GetStaticField(i);
608 if (!field->IsFinal()) {
609 all_final = false;
610 break;
611 }
612 }
613
614 if (all_final) {
615 bin = kBinClassInitializedFinalStatics;
616 }
617 }
618 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800619 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
620 bin = kBinString; // Strings are almost always immutable (except for object header).
621 } // else bin = kBinRegular
622 }
623
Jeff Haodcdc85b2015-12-04 14:06:18 -0800624 const char* oat_filename = GetOatFilename(object);
625 ImageInfo& image_info = GetImageInfo(oat_filename);
626
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800627 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Jeff Haodcdc85b2015-12-04 14:06:18 -0800628 current_offset = image_info.bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
629 // Move the current bin size up to accommodate the object we just assigned a bin slot.
630 image_info.bin_slot_sizes_[bin] += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800631
632 BinSlot new_bin_slot(bin, current_offset);
633 SetImageBinSlot(object, new_bin_slot);
634
Jeff Haodcdc85b2015-12-04 14:06:18 -0800635 ++image_info.bin_slot_count_[bin];
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800636
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800637 // Grow the image closer to the end by the object we just assigned.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800638 image_info.image_end_ += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800639}
640
Mathieu Chartiere401d142015-04-22 13:56:20 -0700641bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
642 if (m->IsNative()) {
643 return true;
644 }
645 mirror::Class* declaring_class = m->GetDeclaringClass();
646 // Initialized is highly unlikely to dirty since there's no entry points to mutate.
647 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
648}
649
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800650bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
651 DCHECK(object != nullptr);
652
653 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
654 // If it's in some other state, then we haven't yet assigned an image bin slot.
655 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
656 return false;
657 } else if (kIsDebugBuild) {
658 LockWord lock_word = object->GetLockWord(false);
659 size_t offset = lock_word.ForwardingAddress();
660 BinSlot bin_slot(offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800661 const char* oat_filename = GetOatFilename(object);
662 const ImageInfo& image_info = GetConstImageInfo(oat_filename);
663 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()])
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800664 << "bin slot offset should not exceed the size of that bin";
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800665 }
666 return true;
667}
668
669ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
670 DCHECK(object != nullptr);
671 DCHECK(IsImageBinSlotAssigned(object));
672
673 LockWord lock_word = object->GetLockWord(false);
674 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
675 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
676
677 BinSlot bin_slot(static_cast<uint32_t>(offset));
Jeff Haodcdc85b2015-12-04 14:06:18 -0800678 const char* oat_filename = GetOatFilename(object);
679 const ImageInfo& image_info = GetConstImageInfo(oat_filename);
680 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()]);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800681
682 return bin_slot;
683}
684
Brian Carlstrom7940e442013-07-12 13:46:57 -0700685bool ImageWriter::AllocMemory() {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800686 for (const char* oat_filename : oat_filenames_) {
687 ImageInfo& image_info = GetImageInfo(oat_filename);
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800688 ImageSection unused_sections[ImageHeader::kSectionCount];
689 const size_t length = RoundUp(
690 image_info.CreateImageSections(target_ptr_size_, unused_sections),
691 kPageSize);
692
Jeff Haodcdc85b2015-12-04 14:06:18 -0800693 std::string error_msg;
694 image_info.image_.reset(MemMap::MapAnonymous("image writer image",
695 nullptr,
696 length,
697 PROT_READ | PROT_WRITE,
698 false,
699 false,
700 &error_msg));
701 if (UNLIKELY(image_info.image_.get() == nullptr)) {
702 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
703 return false;
704 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700705
Jeff Haodcdc85b2015-12-04 14:06:18 -0800706 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
707 CHECK_LE(image_info.image_end_, length);
708 image_info.image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
709 "image bitmap", image_info.image_->Begin(), RoundUp(image_info.image_end_, kPageSize)));
710 if (image_info.image_bitmap_.get() == nullptr) {
711 LOG(ERROR) << "Failed to allocate memory for image bitmap";
712 return false;
713 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700714 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700715 return true;
716}
717
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700718class ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
719 public:
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -0800720 bool operator()(Class* c) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700721 StackHandleScope<1> hs(Thread::Current());
722 mirror::Class::ComputeName(hs.NewHandle(c));
723 return true;
724 }
725};
726
Brian Carlstrom7940e442013-07-12 13:46:57 -0700727void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700728 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700729 ComputeLazyFieldsForClassesVisitor visitor;
730 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700731}
732
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800733static bool IsBootClassLoaderClass(mirror::Class* klass) SHARED_REQUIRES(Locks::mutator_lock_) {
734 return klass->GetClassLoader() == nullptr;
735}
736
737bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
738 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
739}
740
Mathieu Chartier901e0702016-02-19 13:42:48 -0800741bool ImageWriter::PruneAppImageClass(mirror::Class* klass) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800742 bool early_exit = false;
743 std::unordered_set<mirror::Class*> visited;
Mathieu Chartier901e0702016-02-19 13:42:48 -0800744 return PruneAppImageClassInternal(klass, &early_exit, &visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800745}
746
Mathieu Chartier901e0702016-02-19 13:42:48 -0800747bool ImageWriter::PruneAppImageClassInternal(
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800748 mirror::Class* klass,
749 bool* early_exit,
750 std::unordered_set<mirror::Class*>* visited) {
751 DCHECK(early_exit != nullptr);
752 DCHECK(visited != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800753 DCHECK(compile_app_image_);
Mathieu Chartier901e0702016-02-19 13:42:48 -0800754 if (klass == nullptr || IsInBootImage(klass)) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700755 return false;
756 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800757 auto found = prune_class_memo_.find(klass);
758 if (found != prune_class_memo_.end()) {
759 // Already computed, return the found value.
760 return found->second;
761 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800762 // Circular dependencies, return false but do not store the result in the memoization table.
763 if (visited->find(klass) != visited->end()) {
764 *early_exit = true;
765 return false;
766 }
767 visited->emplace(klass);
Mathieu Chartier901e0702016-02-19 13:42:48 -0800768 bool result = IsBootClassLoaderClass(klass);
769 std::string temp;
770 // Prune if not an image class, this handles any broken sets of image classes such as having a
771 // class in the set but not it's superclass.
772 result = result || !compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800773 bool my_early_exit = false; // Only for ourselves, ignore caller.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800774 // Remove classes that failed to verify since we don't want to have java.lang.VerifyError in the
775 // app image.
776 if (klass->GetStatus() == mirror::Class::kStatusError) {
777 result = true;
778 } else {
779 CHECK(klass->GetVerifyError() == nullptr) << PrettyClass(klass);
780 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800781 if (!result) {
782 // Check interfaces since these wont be visited through VisitReferences.)
783 mirror::IfTable* if_table = klass->GetIfTable();
784 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800785 result = result || PruneAppImageClassInternal(if_table->GetInterface(i),
786 &my_early_exit,
787 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800788 }
789 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800790 if (klass->IsObjectArrayClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800791 result = result || PruneAppImageClassInternal(klass->GetComponentType(),
792 &my_early_exit,
793 visited);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800794 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800795 // Check static fields and their classes.
796 size_t num_static_fields = klass->NumReferenceStaticFields();
797 if (num_static_fields != 0 && klass->IsResolved()) {
798 // Presumably GC can happen when we are cross compiling, it should not cause performance
799 // problems to do pointer size logic.
800 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
801 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
802 for (size_t i = 0u; i < num_static_fields; ++i) {
803 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
804 if (ref != nullptr) {
805 if (ref->IsClass()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800806 result = result || PruneAppImageClassInternal(ref->AsClass(),
807 &my_early_exit,
808 visited);
809 } else {
810 result = result || PruneAppImageClassInternal(ref->GetClass(),
811 &my_early_exit,
812 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800813 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800814 }
815 field_offset = MemberOffset(field_offset.Uint32Value() +
816 sizeof(mirror::HeapReference<mirror::Object>));
817 }
818 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800819 result = result || PruneAppImageClassInternal(klass->GetSuperClass(),
820 &my_early_exit,
821 visited);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800822 // Erase the element we stored earlier since we are exiting the function.
823 auto it = visited->find(klass);
824 DCHECK(it != visited->end());
825 visited->erase(it);
826 // Only store result if it is true or none of the calls early exited due to circular
827 // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
828 // a child call and we can remember the result.
829 if (result == true || !my_early_exit || visited->empty()) {
830 prune_class_memo_[klass] = result;
831 }
832 *early_exit |= my_early_exit;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800833 return result;
834}
835
836bool ImageWriter::KeepClass(Class* klass) {
837 if (klass == nullptr) {
838 return false;
839 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800840 if (compile_app_image_ && Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass)) {
841 // Already in boot image, return true.
842 return true;
843 }
844 std::string temp;
845 if (!compiler_driver_.IsImageClass(klass->GetDescriptor(&temp))) {
846 return false;
847 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800848 if (compile_app_image_) {
849 // For app images, we need to prune boot loader classes that are not in the boot image since
850 // these may have already been loaded when the app image is loaded.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800851 // Keep classes in the boot image space since we don't want to re-resolve these.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800852 return !PruneAppImageClass(klass);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800853 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800854 return true;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700855}
856
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700857class NonImageClassesVisitor : public ClassVisitor {
858 public:
859 explicit NonImageClassesVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
860
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -0800861 bool operator()(Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800862 if (!image_writer_->KeepClass(klass)) {
863 classes_to_prune_.insert(klass);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700864 }
865 return true;
866 }
867
Mathieu Chartier9b1c9b72016-02-02 10:09:58 -0800868 std::unordered_set<mirror::Class*> classes_to_prune_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700869 ImageWriter* const image_writer_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700870};
871
872void ImageWriter::PruneNonImageClasses() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700873 Runtime* runtime = Runtime::Current();
874 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700875 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700876
877 // Make a list of classes we would like to prune.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700878 NonImageClassesVisitor visitor(this);
879 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700880
881 // Remove the undesired classes from the class roots.
Mathieu Chartier901e0702016-02-19 13:42:48 -0800882 VLOG(compiler) << "Pruning " << visitor.classes_to_prune_.size() << " classes";
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800883 for (mirror::Class* klass : visitor.classes_to_prune_) {
884 std::string temp;
885 const char* name = klass->GetDescriptor(&temp);
886 VLOG(compiler) << "Pruning class " << name;
887 if (!compile_app_image_) {
888 DCHECK(IsBootClassLoaderClass(klass));
889 }
890 bool result = class_linker->RemoveClass(name, klass->GetClassLoader());
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800891 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700892 }
893
894 // Clear references to removed classes from the DexCaches.
Vladimir Marko05792b92015-08-03 11:56:49 +0100895 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700896
897 ScopedAssertNoThreadSuspension sa(self, __FUNCTION__);
898 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); // For ClassInClassTable
899 ReaderMutexLock mu2(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800900 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartier901e0702016-02-19 13:42:48 -0800901 if (self->IsJWeakCleared(data.weak_root)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700902 continue;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700903 }
Mathieu Chartier901e0702016-02-19 13:42:48 -0800904 mirror::DexCache* dex_cache = self->DecodeJObject(data.weak_root)->AsDexCache();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700905 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
906 Class* klass = dex_cache->GetResolvedType(i);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800907 if (klass != nullptr && !KeepClass(klass)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700908 dex_cache->SetResolvedType(i, nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700909 }
910 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100911 ArtMethod** resolved_methods = dex_cache->GetResolvedMethods();
912 for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) {
913 ArtMethod* method =
914 mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800915 DCHECK(method != nullptr) << "Expected resolution method instead of null method";
916 mirror::Class* declaring_class = method->GetDeclaringClass();
Alex Lightfcea56f2016-02-17 11:59:05 -0800917 // Copied methods may be held live by a class which was not an image class but have a
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800918 // declaring class which is an image class. Set it to the resolution method to be safe and
919 // prevent dangling pointers.
Alex Lightfcea56f2016-02-17 11:59:05 -0800920 if (method->MightBeCopied() || !KeepClass(declaring_class)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800921 mirror::DexCache::SetElementPtrSize(resolved_methods,
922 i,
923 resolution_method,
924 target_ptr_size_);
925 } else {
926 // Check that the class is still in the classes table.
927 DCHECK(class_linker->ClassInClassTable(declaring_class)) << "Class "
928 << PrettyClass(declaring_class) << " not in class linker table";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700929 }
930 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800931 ArtField** resolved_fields = dex_cache->GetResolvedFields();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700932 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800933 ArtField* field = mirror::DexCache::GetElementPtrSize(resolved_fields, i, target_ptr_size_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800934 if (field != nullptr && !KeepClass(field->GetDeclaringClass())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700935 dex_cache->SetResolvedField(i, nullptr, target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700936 }
937 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700938 // Clean the dex field. It might have been populated during the initialization phase, but
939 // contains data only valid during a real run.
940 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700941 }
Andreas Gampe8ac75952015-06-02 21:01:45 -0700942
943 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
944 class_linker->DropFindArrayClassCache();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800945
946 // Clear to save RAM.
947 prune_class_memo_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700948}
949
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800950void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700951 if (compiler_driver_.GetImageClasses() != nullptr) {
952 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700953 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700954 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700955}
956
957void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
958 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800959 if (obj->IsClass() && !image_writer->IsInBootImage(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700960 Class* klass = obj->AsClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800961 if (!image_writer->KeepClass(klass)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700962 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700963 std::string temp;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800964 CHECK(image_writer->KeepClass(klass)) << klass->GetDescriptor(&temp)
965 << " " << PrettyDescriptor(klass);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700966 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700967 }
968}
969
970void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700971 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700972 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700973 for (const std::string& image_class : *image_classes) {
974 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700975 }
976}
977
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800978mirror::String* ImageWriter::FindInternedString(mirror::String* string) {
979 Thread* const self = Thread::Current();
980 for (auto& pair : image_info_map_) {
981 const ImageInfo& image_info = pair.second;
982 mirror::String* const found = image_info.intern_table_->LookupStrong(self, string);
983 DCHECK(image_info.intern_table_->LookupWeak(self, string) == nullptr)
984 << string->ToModifiedUtf8();
985 if (found != nullptr) {
986 return found;
987 }
988 }
989 if (compile_app_image_) {
990 Runtime* const runtime = Runtime::Current();
991 mirror::String* found = runtime->GetInternTable()->LookupStrong(self, string);
992 // If we found it in the runtime intern table it could either be in the boot image or interned
993 // during app image compilation. If it was in the boot image return that, otherwise return null
994 // since it belongs to another image space.
995 if (found != nullptr && runtime->GetHeap()->ObjectIsInBootImageSpace(found)) {
996 return found;
997 }
998 DCHECK(runtime->GetInternTable()->LookupWeak(self, string) == nullptr)
999 << string->ToModifiedUtf8();
1000 }
1001 return nullptr;
1002}
1003
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001004void ImageWriter::CalculateObjectBinSlots(Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001005 DCHECK(obj != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001006 // if it is a string, we want to intern it if its not interned.
1007 if (obj->GetClass()->IsStringClass()) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001008 const char* oat_filename = GetOatFilename(obj);
1009 ImageInfo& image_info = GetImageInfo(oat_filename);
1010
Brian Carlstrom7940e442013-07-12 13:46:57 -07001011 // we must be an interned string that was forward referenced and already assigned
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001012 if (IsImageBinSlotAssigned(obj)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001013 DCHECK_EQ(obj, FindInternedString(obj->AsString()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001014 return;
1015 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001016 // Need to check if the string is already interned in another image info so that we don't have
1017 // the intern tables of two different images contain the same string.
1018 mirror::String* interned = FindInternedString(obj->AsString());
1019 if (interned == nullptr) {
1020 // Not in another image space, insert to our table.
1021 interned = image_info.intern_table_->InternStrongImageString(obj->AsString());
1022 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001023 if (obj != interned) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001024 if (!IsImageBinSlotAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001025 // interned obj is after us, allocate its location early
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001026 AssignImageBinSlot(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001027 }
1028 // point those looking for this object to the interned version.
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001029 SetImageBinSlot(obj, GetImageBinSlot(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001030 return;
1031 }
1032 // else (obj == interned), nothing to do but fall through to the normal case
1033 }
1034
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001035 AssignImageBinSlot(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001036}
1037
Jeff Haodcdc85b2015-12-04 14:06:18 -08001038ObjectArray<Object>* ImageWriter::CreateImageRoots(const char* oat_filename) const {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001039 Runtime* runtime = Runtime::Current();
1040 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001041 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001042 StackHandleScope<3> hs(self);
1043 Handle<Class> object_array_class(hs.NewHandle(
1044 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001045
Jeff Haodcdc85b2015-12-04 14:06:18 -08001046 std::unordered_set<const DexFile*> image_dex_files;
1047 for (auto& pair : dex_file_oat_filename_map_) {
1048 const DexFile* image_dex_file = pair.first;
1049 const char* image_oat_filename = pair.second;
1050 if (strcmp(oat_filename, image_oat_filename) == 0) {
1051 image_dex_files.insert(image_dex_file);
1052 }
1053 }
1054
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001055 // build an Object[] of all the DexCaches used in the source_space_.
1056 // Since we can't hold the dex lock when allocating the dex_caches
1057 // ObjectArray, we lock the dex lock twice, first to get the number
1058 // of dex caches first and then lock it again to copy the dex
1059 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001060 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001061 {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001062 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001063 // Count number of dex caches not in the boot image.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001064 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1065 mirror::DexCache* dex_cache =
1066 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001067 const DexFile* dex_file = dex_cache->GetDexFile();
1068 if (!IsInBootImage(dex_cache)) {
1069 dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1070 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001071 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001072 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001073 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001074 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001075 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
1076 {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001077 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001078 size_t non_image_dex_caches = 0;
1079 // Re-count number of non image dex caches.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001080 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1081 mirror::DexCache* dex_cache =
1082 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001083 const DexFile* dex_file = dex_cache->GetDexFile();
1084 if (!IsInBootImage(dex_cache)) {
1085 non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1086 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001087 }
1088 CHECK_EQ(dex_cache_count, non_image_dex_caches)
1089 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001090 size_t i = 0;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001091 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1092 mirror::DexCache* dex_cache =
1093 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001094 const DexFile* dex_file = dex_cache->GetDexFile();
1095 if (!IsInBootImage(dex_cache) && image_dex_files.find(dex_file) != image_dex_files.end()) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001096 dex_caches->Set<false>(i, dex_cache);
1097 ++i;
1098 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001099 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001100 }
1101
1102 // build an Object[] of the roots needed to restore the runtime
Mathieu Chartiere401d142015-04-22 13:56:20 -07001103 auto image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001104 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001105 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001106 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001107 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001108 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001109 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001110 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001111}
1112
Mathieu Chartier590fee92013-09-13 13:46:47 -07001113// Walk instance fields of the given Class. Separate function to allow recursion on the super
1114// class.
1115void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
1116 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001117 StackHandleScope<1> hs(Thread::Current());
1118 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1119 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001120 if (super != nullptr) {
1121 WalkInstanceFields(obj, super);
1122 }
1123 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001124 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Marko76649e82014-11-10 18:32:59 +00001125 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001126 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001127 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001128 if (value != nullptr) {
1129 WalkFieldsInOrder(value);
1130 }
Vladimir Marko76649e82014-11-10 18:32:59 +00001131 field_offset = MemberOffset(field_offset.Uint32Value() +
1132 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001133 }
1134}
1135
1136// For an unvisited object, visit it then all its children found via fields.
1137void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001138 if (IsInBootImage(obj)) {
1139 // Object is in the image, don't need to fix it up.
1140 return;
1141 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001142 // Use our own visitor routine (instead of GC visitor) to get better locality between
1143 // an object and its fields
1144 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001145 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001146 StackHandleScope<2> hs(Thread::Current());
1147 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
1148 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001149 // visit the object itself.
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001150 CalculateObjectBinSlots(h_obj.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001151 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001152 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001153 if (h_obj->IsClass()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001154 size_t num_reference_static_fields = klass->NumReferenceStaticFields();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001155 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001156 for (size_t i = 0; i < num_reference_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001157 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001158 if (value != nullptr) {
1159 WalkFieldsInOrder(value);
1160 }
Vladimir Marko76649e82014-11-10 18:32:59 +00001161 field_offset = MemberOffset(field_offset.Uint32Value() +
1162 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001163 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001164 // Visit and assign offsets for fields and field arrays.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001165 auto* as_klass = h_obj->AsClass();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001166 mirror::DexCache* dex_cache = as_klass->GetDexCache();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001167 DCHECK_NE(klass->GetStatus(), mirror::Class::kStatusError);
1168 if (compile_app_image_) {
1169 // Extra sanity, no boot loader classes should be left!
1170 CHECK(!IsBootClassLoaderClass(as_klass)) << PrettyClass(as_klass);
1171 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001172 LengthPrefixedArray<ArtField>* fields[] = {
1173 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
1174 };
Jeff Haodcdc85b2015-12-04 14:06:18 -08001175 const char* oat_file = GetOatFilenameForDexCache(dex_cache);
1176 ImageInfo& image_info = GetImageInfo(oat_file);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001177 {
1178 // Note: This table is only accessed from the image writer, so the lock is technically
1179 // unnecessary.
1180 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1181 // Insert in the class table for this iamge.
1182 image_info.class_table_->Insert(as_klass);
1183 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001184 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1185 // Total array length including header.
1186 if (cur_fields != nullptr) {
1187 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
1188 // Forward the entire array at once.
1189 auto it = native_object_relocations_.find(cur_fields);
1190 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
1191 << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001192 size_t& offset = image_info.bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001193 DCHECK(!IsInBootImage(cur_fields));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001194 native_object_relocations_.emplace(cur_fields,
1195 NativeObjectRelocation {oat_file, offset, kNativeObjectRelocationTypeArtFieldArray });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001196 offset += header_size;
1197 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +01001198 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001199 // Need to forward arrays separate of fields.
1200 ArtField* field = &cur_fields->At(i);
1201 auto it2 = native_object_relocations_.find(field);
1202 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
1203 << " already assigned " << PrettyField(field) << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001204 DCHECK(!IsInBootImage(field));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001205 native_object_relocations_.emplace(field,
1206 NativeObjectRelocation {oat_file, offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001207 offset += sizeof(ArtField);
1208 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001209 }
1210 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001211 // Visit and assign offsets for methods.
Alex Lighte64300b2015-12-15 15:02:47 -08001212 size_t num_methods = as_klass->NumMethods();
1213 if (num_methods != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001214 bool any_dirty = false;
Alex Lighte64300b2015-12-15 15:02:47 -08001215 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1216 if (WillMethodBeDirty(&m)) {
1217 any_dirty = true;
1218 break;
1219 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001220 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001221 NativeObjectRelocationType type = any_dirty
1222 ? kNativeObjectRelocationTypeArtMethodDirty
1223 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001224 Bin bin_type = BinTypeForNativeRelocationType(type);
1225 // Forward the entire array at once, but header first.
Alex Lighte64300b2015-12-15 15:02:47 -08001226 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1227 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01001228 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1229 method_size,
1230 method_alignment);
Alex Lighte64300b2015-12-15 15:02:47 -08001231 LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001232 auto it = native_object_relocations_.find(array);
Alex Lighte64300b2015-12-15 15:02:47 -08001233 CHECK(it == native_object_relocations_.end())
1234 << "Method array " << array << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001235 size_t& offset = image_info.bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001236 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001237 native_object_relocations_.emplace(array,
1238 NativeObjectRelocation {
1239 oat_file,
1240 offset,
1241 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty
1242 : kNativeObjectRelocationTypeArtMethodArrayClean });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001243 offset += header_size;
Alex Lighte64300b2015-12-15 15:02:47 -08001244 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001245 AssignMethodOffset(&m, type, oat_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001246 }
Alex Lighte64300b2015-12-15 15:02:47 -08001247 (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001248 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001249 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001250 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001251 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001252 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001253 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001254 mirror::Object* value = obj_array->Get(i);
1255 if (value != nullptr) {
1256 WalkFieldsInOrder(value);
1257 }
1258 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001259 } else if (h_obj->IsClassLoader()) {
1260 // Register the class loader if it has a class table.
1261 // The fake boot class loader should not get registered and we should end up with only one
1262 // class loader.
1263 mirror::ClassLoader* class_loader = h_obj->AsClassLoader();
1264 if (class_loader->GetClassTable() != nullptr) {
1265 class_loaders_.insert(class_loader);
1266 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001267 }
1268 }
1269}
1270
Jeff Haodcdc85b2015-12-04 14:06:18 -08001271void ImageWriter::AssignMethodOffset(ArtMethod* method,
1272 NativeObjectRelocationType type,
1273 const char* oat_filename) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001274 DCHECK(!IsInBootImage(method));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001275 auto it = native_object_relocations_.find(method);
1276 CHECK(it == native_object_relocations_.end()) << "Method " << method << " already assigned "
Mathieu Chartiere401d142015-04-22 13:56:20 -07001277 << PrettyMethod(method);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001278 ImageInfo& image_info = GetImageInfo(oat_filename);
1279 size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
1280 native_object_relocations_.emplace(method, NativeObjectRelocation { oat_filename, offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001281 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001282}
1283
Mathieu Chartier590fee92013-09-13 13:46:47 -07001284void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
1285 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1286 DCHECK(writer != nullptr);
1287 writer->WalkFieldsInOrder(obj);
1288}
1289
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001290void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
1291 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1292 DCHECK(writer != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001293 if (!writer->IsInBootImage(obj)) {
1294 writer->UnbinObjectsIntoOffset(obj);
1295 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001296}
1297
1298void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001299 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001300 CHECK(obj != nullptr);
1301
1302 // We know the bin slot, and the total bin sizes for all objects by now,
1303 // so calculate the object's final image offset.
1304
1305 DCHECK(IsImageBinSlotAssigned(obj));
1306 BinSlot bin_slot = GetImageBinSlot(obj);
1307 // Change the lockword from a bin slot into an offset
1308 AssignImageOffset(obj, bin_slot);
1309}
1310
Vladimir Markof4da6752014-08-01 19:04:18 +01001311void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001312 Thread* const self = Thread::Current();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001313 StackHandleScopeCollection handles(self);
1314 std::vector<Handle<ObjectArray<Object>>> image_roots;
1315 for (const char* oat_filename : oat_filenames_) {
1316 std::string image_filename = oat_filename;
1317 image_roots.push_back(handles.NewHandle(CreateImageRoots(image_filename.c_str())));
1318 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001319
Mathieu Chartiere401d142015-04-22 13:56:20 -07001320 auto* runtime = Runtime::Current();
1321 auto* heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001322
Mathieu Chartier31e89252013-08-28 11:29:12 -07001323 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001324 // know where image_roots is going to end up
Jeff Haodcdc85b2015-12-04 14:06:18 -08001325 image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001326
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001327 // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
1328 heap->VisitObjects(WalkFieldsCallback, this);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001329 // Write the image runtime methods.
1330 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1331 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1332 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
1333 image_methods_[ImageHeader::kCalleeSaveMethod] = runtime->GetCalleeSaveMethod(Runtime::kSaveAll);
1334 image_methods_[ImageHeader::kRefsOnlySaveMethod] =
1335 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly);
1336 image_methods_[ImageHeader::kRefsAndArgsSaveMethod] =
1337 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001338
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001339 // Add room for fake length prefixed array for holding the image methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001340 const auto image_method_type = kNativeObjectRelocationTypeArtMethodArrayClean;
1341 auto it = native_object_relocations_.find(&image_method_array_);
1342 CHECK(it == native_object_relocations_.end());
Jeff Haodcdc85b2015-12-04 14:06:18 -08001343 ImageInfo& default_image_info = GetImageInfo(default_oat_filename_);
1344 size_t& offset =
1345 default_image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(image_method_type)];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001346 if (!compile_app_image_) {
1347 native_object_relocations_.emplace(&image_method_array_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001348 NativeObjectRelocation { default_oat_filename_, offset, image_method_type });
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001349 }
Vladimir Marko14632852015-08-17 12:07:23 +01001350 size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001351 const size_t array_size = LengthPrefixedArray<ArtMethod>::ComputeSize(
Vladimir Marko14632852015-08-17 12:07:23 +01001352 0, ArtMethod::Size(target_ptr_size_), method_alignment);
Vladimir Markocf36d492015-08-12 19:27:26 +01001353 CHECK_ALIGNED_PARAM(array_size, method_alignment);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001354 offset += array_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001355 for (auto* m : image_methods_) {
1356 CHECK(m != nullptr);
1357 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001358 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1359 if (!IsInBootImage(m)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001360 AssignMethodOffset(m, kNativeObjectRelocationTypeArtMethodClean, default_oat_filename_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001361 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001362 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001363 // Calculate size of the dex cache arrays slot and prepare offsets.
1364 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001365
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001366 // Calculate the sizes of the intern tables and class tables.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001367 for (const char* oat_filename : oat_filenames_) {
1368 ImageInfo& image_info = GetImageInfo(oat_filename);
1369 // Calculate how big the intern table will be after being serialized.
1370 InternTable* const intern_table = image_info.intern_table_.get();
1371 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
1372 image_info.intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001373 // Calculate the size of the class table.
1374 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
1375 image_info.class_table_bytes_ += image_info.class_table_->WriteToMemory(nullptr);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001376 }
1377
Vladimir Markocf36d492015-08-12 19:27:26 +01001378 // Calculate bin slot offsets.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001379 for (const char* oat_filename : oat_filenames_) {
1380 ImageInfo& image_info = GetImageInfo(oat_filename);
1381 size_t bin_offset = image_objects_offset_begin_;
1382 for (size_t i = 0; i != kBinSize; ++i) {
1383 image_info.bin_slot_offsets_[i] = bin_offset;
1384 bin_offset += image_info.bin_slot_sizes_[i];
1385 if (i == kBinArtField) {
1386 static_assert(kBinArtField + 1 == kBinArtMethodClean, "Methods follow fields.");
1387 static_assert(alignof(ArtField) == 4u, "ArtField alignment is 4.");
1388 DCHECK_ALIGNED(bin_offset, 4u);
1389 DCHECK(method_alignment == 4u || method_alignment == 8u);
1390 bin_offset = RoundUp(bin_offset, method_alignment);
1391 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001392 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001393 // NOTE: There may be additional padding between the bin slots and the intern table.
1394 DCHECK_EQ(image_info.image_end_,
1395 GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_);
Vladimir Marko20f85592015-03-19 10:07:02 +00001396 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001397
Jeff Haodcdc85b2015-12-04 14:06:18 -08001398 // Calculate image offsets.
1399 size_t image_offset = 0;
1400 for (const char* oat_filename : oat_filenames_) {
1401 ImageInfo& image_info = GetImageInfo(oat_filename);
1402 image_info.image_begin_ = global_image_begin_ + image_offset;
1403 image_info.image_offset_ = image_offset;
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001404 ImageSection unused_sections[ImageHeader::kSectionCount];
1405 image_info.image_size_ = RoundUp(
1406 image_info.CreateImageSections(target_ptr_size_, unused_sections),
1407 kPageSize);
1408 // There should be no gaps until the next image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001409 image_offset += image_info.image_size_;
1410 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001411
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001412 // Transform each object's bin slot into an offset which will be used to do the final copy.
1413 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001414
Jeff Haodcdc85b2015-12-04 14:06:18 -08001415 // DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001416
Jeff Haodcdc85b2015-12-04 14:06:18 -08001417 size_t i = 0;
1418 for (const char* oat_filename : oat_filenames_) {
1419 ImageInfo& image_info = GetImageInfo(oat_filename);
1420 image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
1421 i++;
1422 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001423
Mathieu Chartiere401d142015-04-22 13:56:20 -07001424 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001425 for (auto& pair : native_object_relocations_) {
1426 NativeObjectRelocation& relocation = pair.second;
1427 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001428 ImageInfo& image_info = GetImageInfo(relocation.oat_filename);
1429 relocation.offset += image_info.bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001430 }
1431
Jeff Haodcdc85b2015-12-04 14:06:18 -08001432 // Note that image_info.image_end_ is left at end of used mirror object section.
Vladimir Markof4da6752014-08-01 19:04:18 +01001433}
1434
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001435size_t ImageWriter::ImageInfo::CreateImageSections(size_t target_ptr_size,
1436 ImageSection* out_sections) const {
1437 DCHECK(out_sections != nullptr);
1438 // Objects section
1439 auto* objects_section = &out_sections[ImageHeader::kSectionObjects];
1440 *objects_section = ImageSection(0u, image_end_);
1441 size_t cur_pos = objects_section->End();
1442 // Add field section.
1443 auto* field_section = &out_sections[ImageHeader::kSectionArtFields];
1444 *field_section = ImageSection(cur_pos, bin_slot_sizes_[kBinArtField]);
1445 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
1446 cur_pos = field_section->End();
1447 // Round up to the alignment the required by the method section.
1448 cur_pos = RoundUp(cur_pos, ArtMethod::Alignment(target_ptr_size));
1449 // Add method section.
1450 auto* methods_section = &out_sections[ImageHeader::kSectionArtMethods];
1451 *methods_section = ImageSection(cur_pos,
1452 bin_slot_sizes_[kBinArtMethodClean] +
1453 bin_slot_sizes_[kBinArtMethodDirty]);
1454 CHECK_EQ(bin_slot_offsets_[kBinArtMethodClean], methods_section->Offset());
1455 cur_pos = methods_section->End();
1456 // Add dex cache arrays section.
1457 auto* dex_cache_arrays_section = &out_sections[ImageHeader::kSectionDexCacheArrays];
1458 *dex_cache_arrays_section = ImageSection(cur_pos, bin_slot_sizes_[kBinDexCacheArray]);
1459 CHECK_EQ(bin_slot_offsets_[kBinDexCacheArray], dex_cache_arrays_section->Offset());
1460 cur_pos = dex_cache_arrays_section->End();
1461 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
1462 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1463 // Calculate the size of the interned strings.
1464 auto* interned_strings_section = &out_sections[ImageHeader::kSectionInternedStrings];
1465 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1466 cur_pos = interned_strings_section->End();
1467 // Round up to the alignment the class table expects. See HashSet::WriteToMemory.
1468 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1469 // Calculate the size of the class table section.
1470 auto* class_table_section = &out_sections[ImageHeader::kSectionClassTable];
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001471 *class_table_section = ImageSection(cur_pos, class_table_bytes_);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001472 cur_pos = class_table_section->End();
1473 // Image end goes right before the start of the image bitmap.
1474 return cur_pos;
1475}
1476
Vladimir Markof4da6752014-08-01 19:04:18 +01001477void ImageWriter::CreateHeader(size_t oat_loaded_size, size_t oat_data_offset) {
1478 CHECK_NE(0U, oat_loaded_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001479 const char* oat_filename = oat_file_->GetLocation().c_str();
1480 ImageInfo& image_info = GetImageInfo(oat_filename);
1481 const uint8_t* oat_file_begin = GetOatFileBegin(oat_filename);
Ian Rogers13735952014-10-08 12:43:28 -07001482 const uint8_t* oat_file_end = oat_file_begin + oat_loaded_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001483 image_info.oat_data_begin_ = const_cast<uint8_t*>(oat_file_begin) + oat_data_offset;
1484 const uint8_t* oat_data_end = image_info.oat_data_begin_ + oat_file_->Size();
1485 image_info.oat_size_ = oat_file_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001486
1487 // Create the image sections.
1488 ImageSection sections[ImageHeader::kSectionCount];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001489 const size_t image_end = image_info.CreateImageSections(target_ptr_size_, sections);
1490
Mathieu Chartiere401d142015-04-22 13:56:20 -07001491 // Finally bitmap section.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001492 const size_t bitmap_bytes = image_info.image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001493 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001494 *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001495 if (VLOG_IS_ON(compiler)) {
1496 LOG(INFO) << "Creating header for " << oat_filename;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001497 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001498 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001499 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1500 ++idx;
1501 }
1502 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001503 LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
1504 LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
1505 << " Image offset=" << image_info.image_offset_ << std::dec;
1506 LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
1507 << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
1508 << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
1509 << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001510 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001511 // Store boot image info for app image so that we can relocate.
1512 uint32_t boot_image_begin = 0;
1513 uint32_t boot_image_end = 0;
1514 uint32_t boot_oat_begin = 0;
1515 uint32_t boot_oat_end = 0;
1516 gc::Heap* const heap = Runtime::Current()->GetHeap();
1517 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001518
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001519 // Create the header, leave 0 for data size since we will fill this in as we are writing the
1520 // image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001521 new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_),
1522 image_end,
1523 sections,
1524 image_info.image_roots_address_,
1525 oat_file_->GetOatHeader().GetChecksum(),
1526 PointerToLowMemUInt32(oat_file_begin),
1527 PointerToLowMemUInt32(image_info.oat_data_begin_),
1528 PointerToLowMemUInt32(oat_data_end),
1529 PointerToLowMemUInt32(oat_file_end),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001530 boot_image_begin,
1531 boot_image_end - boot_image_begin,
1532 boot_oat_begin,
1533 boot_oat_end - boot_oat_begin,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001534 target_ptr_size_,
1535 compile_pic_,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001536 /*is_pic*/compile_app_image_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001537 image_storage_mode_,
1538 /*data_size*/0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001539}
1540
1541ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001542 auto it = native_object_relocations_.find(method);
1543 CHECK(it != native_object_relocations_.end()) << PrettyMethod(method) << " @ " << method;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001544 const char* oat_filename = GetOatFilename(method->GetDexCache());
1545 ImageInfo& image_info = GetImageInfo(oat_filename);
1546 CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects";
1547 return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001548}
1549
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001550class FixupRootVisitor : public RootVisitor {
1551 public:
1552 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1553 }
1554
1555 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001556 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001557 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001558 *roots[i] = image_writer_->GetImageAddress(*roots[i]);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001559 }
1560 }
1561
1562 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1563 const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001564 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001565 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001566 roots[i]->Assign(image_writer_->GetImageAddress(roots[i]->AsMirrorPtr()));
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001567 }
1568 }
1569
1570 private:
1571 ImageWriter* const image_writer_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001572};
1573
Mathieu Chartierc7853442015-03-27 14:35:38 -07001574void ImageWriter::CopyAndFixupNativeData() {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001575 const char* oat_filename = oat_file_->GetLocation().c_str();
1576 ImageInfo& image_info = GetImageInfo(oat_filename);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001577 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001578 for (auto& pair : native_object_relocations_) {
1579 NativeObjectRelocation& relocation = pair.second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001580 // Only work with fields and methods that are in the current oat file.
1581 if (strcmp(relocation.oat_filename, oat_filename) != 0) {
1582 continue;
1583 }
1584 auto* dest = image_info.image_->Begin() + relocation.offset;
1585 DCHECK_GE(dest, image_info.image_->Begin() + image_info.image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001586 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001587 switch (relocation.type) {
1588 case kNativeObjectRelocationTypeArtField: {
1589 memcpy(dest, pair.first, sizeof(ArtField));
1590 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
1591 GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass()));
1592 break;
1593 }
1594 case kNativeObjectRelocationTypeArtMethodClean:
1595 case kNativeObjectRelocationTypeArtMethodDirty: {
1596 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001597 reinterpret_cast<ArtMethod*>(dest),
1598 image_info);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001599 break;
1600 }
1601 // For arrays, copy just the header since the elements will get copied by their corresponding
1602 // relocations.
1603 case kNativeObjectRelocationTypeArtFieldArray: {
1604 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1605 break;
1606 }
1607 case kNativeObjectRelocationTypeArtMethodArrayClean:
1608 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markocf36d492015-08-12 19:27:26 +01001609 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(
1610 0,
Vladimir Marko14632852015-08-17 12:07:23 +01001611 ArtMethod::Size(target_ptr_size_),
1612 ArtMethod::Alignment(target_ptr_size_)));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001613 break;
Vladimir Marko05792b92015-08-03 11:56:49 +01001614 case kNativeObjectRelocationTypeDexCacheArray:
1615 // Nothing to copy here, everything is done in FixupDexCache().
1616 break;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001617 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001618 }
1619 }
1620 // Fixup the image method roots.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001621 auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001622 const ImageSection& methods_section = image_header->GetMethodsSection();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001623 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001624 ArtMethod* method = image_methods_[i];
1625 CHECK(method != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001626 // Only place runtime methods in the image of the default oat file.
1627 if (method->IsRuntimeMethod() && strcmp(default_oat_filename_, oat_filename) != 0) {
1628 continue;
1629 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001630 if (!IsInBootImage(method)) {
1631 auto it = native_object_relocations_.find(method);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001632 CHECK(it != native_object_relocations_.end()) << "No forwarding for " << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001633 NativeObjectRelocation& relocation = it->second;
1634 CHECK(methods_section.Contains(relocation.offset)) << relocation.offset << " not in "
1635 << methods_section;
1636 CHECK(relocation.IsArtMethodRelocation()) << relocation.type;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001637 method = reinterpret_cast<ArtMethod*>(global_image_begin_ + it->second.offset);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001638 }
1639 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001640 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001641 FixupRootVisitor root_visitor(this);
1642
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001643 // Write the intern table into the image.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001644 if (image_info.intern_table_bytes_ > 0) {
1645 const ImageSection& intern_table_section = image_header->GetImageSection(
1646 ImageHeader::kSectionInternedStrings);
1647 InternTable* const intern_table = image_info.intern_table_.get();
1648 uint8_t* const intern_table_memory_ptr =
1649 image_info.image_->Begin() + intern_table_section.Offset();
1650 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
1651 CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
1652 // Fixup the pointers in the newly written intern table to contain image addresses.
1653 InternTable temp_intern_table;
1654 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1655 // the VisitRoots() will update the memory directly rather than the copies.
1656 // This also relies on visit roots not doing any verification which could fail after we update
1657 // the roots to be the image addresses.
1658 temp_intern_table.AddTableFromMemory(intern_table_memory_ptr);
1659 CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
1660 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
1661 }
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001662 // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
1663 // class loaders. Writing multiple class tables into the image is currently unsupported.
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001664 if (image_info.class_table_bytes_ > 0u) {
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001665 const ImageSection& class_table_section = image_header->GetImageSection(
1666 ImageHeader::kSectionClassTable);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001667 uint8_t* const class_table_memory_ptr =
1668 image_info.image_->Begin() + class_table_section.Offset();
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001669 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001670
1671 ClassTable* table = image_info.class_table_.get();
1672 CHECK(table != nullptr);
1673 const size_t class_table_bytes = table->WriteToMemory(class_table_memory_ptr);
1674 CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
1675 // Fixup the pointers in the newly written class table to contain image addresses. See
1676 // above comment for intern tables.
1677 ClassTable temp_class_table;
1678 temp_class_table.ReadFromMemory(class_table_memory_ptr);
1679 CHECK_EQ(temp_class_table.NumZygoteClasses(), table->NumNonZygoteClasses() +
1680 table->NumZygoteClasses());
1681 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(&root_visitor,
1682 RootInfo(kRootUnknown));
1683 temp_class_table.VisitRoots(buffered_visitor);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001684 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001685}
1686
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001687void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001688 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001689 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1690 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001691 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001692 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07001693 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
1694 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001695 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001696 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001697}
1698
Mathieu Chartier590fee92013-09-13 13:46:47 -07001699void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001700 DCHECK(obj != nullptr);
1701 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001702 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1703}
1704
Mathieu Chartiere401d142015-04-22 13:56:20 -07001705void ImageWriter::FixupPointerArray(mirror::Object* dst, mirror::PointerArray* arr,
1706 mirror::Class* klass, Bin array_type) {
1707 CHECK(klass->IsArrayClass());
1708 CHECK(arr->IsIntArray() || arr->IsLongArray()) << PrettyClass(klass) << " " << arr;
1709 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001710 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001711 dst->SetClass(GetImageAddress(arr->GetClass()));
1712 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001713 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001714 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
1715 if (elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001716 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01001717 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001718 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001719 auto* method = reinterpret_cast<ArtMethod*>(elem);
1720 LOG(FATAL) << "No relocation entry for ArtMethod " << PrettyMethod(method) << " @ "
1721 << method << " idx=" << i << "/" << num_elements << " with declaring class "
1722 << PrettyClass(method->GetDeclaringClass());
1723 } else {
1724 CHECK_EQ(array_type, kBinArtField);
1725 auto* field = reinterpret_cast<ArtField*>(elem);
1726 LOG(FATAL) << "No relocation entry for ArtField " << PrettyField(field) << " @ "
1727 << field << " idx=" << i << "/" << num_elements << " with declaring class "
1728 << PrettyClass(field->GetDeclaringClass());
1729 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001730 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001731 } else {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001732 ImageInfo& image_info = GetImageInfo(it->second.oat_filename);
1733 elem = image_info.image_begin_ + it->second.offset;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001734 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001735 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001736 dest_array->SetElementPtrSize<false, true>(i, elem, target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001737 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001738}
1739
1740void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001741 if (IsInBootImage(obj)) {
1742 return;
1743 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001744 size_t offset = GetImageOffset(obj);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001745 const char* oat_filename = GetOatFilename(obj);
1746 ImageInfo& image_info = GetImageInfo(oat_filename);
1747 auto* dst = reinterpret_cast<Object*>(image_info.image_->Begin() + offset);
1748 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001749 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001750
Jeff Haodcdc85b2015-12-04 14:06:18 -08001751 image_info.image_bitmap_->Set(dst); // Mark the obj as live.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001752
1753 const size_t n = obj->SizeOf();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001754 DCHECK_LE(offset + n, image_info.image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001755 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001756
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001757 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1758 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001759 const auto it = saved_hashcode_map_.find(obj);
1760 dst->SetLockWord(it != saved_hashcode_map_.end() ?
1761 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001762 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001763}
1764
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001765// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001766class FixupVisitor {
1767 public:
1768 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1769 }
1770
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001771 // Ignore class roots since we don't have a way to map them to the destination. These are handled
1772 // with other logic.
1773 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1774 const {}
1775 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1776
1777
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001778 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001779 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -07001780 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001781 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1782 // image.
1783 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001784 offset,
1785 image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001786 }
1787
1788 // java.lang.ref.Reference visitor.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001789 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001790 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001791 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001792 mirror::Reference::ReferentOffset(),
1793 image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001794 }
1795
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001796 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001797 ImageWriter* const image_writer_;
1798 mirror::Object* const copy_;
1799};
1800
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001801class FixupClassVisitor FINAL : public FixupVisitor {
1802 public:
1803 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1804 }
1805
Mathieu Chartierc7853442015-03-27 14:35:38 -07001806 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001807 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001808 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001809 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001810 }
1811
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001812 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1813 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001814 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001815 LOG(FATAL) << "Reference not expected here.";
1816 }
1817};
1818
Vladimir Marko05792b92015-08-03 11:56:49 +01001819uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
1820 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001821 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001822 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001823 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1824 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001825 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01001826 return relocation.offset;
1827}
1828
1829template <typename T>
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001830T* ImageWriter::NativeLocationInImage(T* obj) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001831 if (obj == nullptr || IsInBootImage(obj)) {
1832 return obj;
1833 } else {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001834 auto it = native_object_relocations_.find(obj);
1835 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1836 << Runtime::Current()->GetHeap()->DumpSpaces();
1837 const NativeObjectRelocation& relocation = it->second;
1838 ImageInfo& image_info = GetImageInfo(relocation.oat_filename);
1839 return reinterpret_cast<T*>(image_info.image_begin_ + relocation.offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001840 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001841}
1842
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001843template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001844T* ImageWriter::NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) {
1845 if (obj == nullptr || IsInBootImage(obj)) {
1846 return obj;
1847 } else {
1848 const char* oat_filename = GetOatFilenameForDexCache(dex_cache);
1849 ImageInfo& image_info = GetImageInfo(oat_filename);
1850 return reinterpret_cast<T*>(image_info.image_->Begin() + NativeOffsetInImage(obj));
1851 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001852}
1853
1854class NativeLocationVisitor {
1855 public:
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001856 explicit NativeLocationVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001857
1858 template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001859 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001860 return image_writer_->NativeLocationInImage(ptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001861 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001862
1863 private:
1864 ImageWriter* const image_writer_;
1865};
1866
1867void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001868 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001869 FixupClassVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001870 static_cast<mirror::Object*>(orig)->VisitReferences(visitor, visitor);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001871
1872 // Remove the clinitThreadId. This is required for image determinism.
1873 copy->SetClinitThreadId(static_cast<pid_t>(0));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001874}
1875
Ian Rogersef7d42f2014-01-06 12:55:46 -08001876void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001877 DCHECK(orig != nullptr);
1878 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07001879 if (kUseBakerOrBrooksReadBarrier) {
1880 orig->AssertReadBarrierPointer();
1881 if (kUseBrooksReadBarrier) {
1882 // Note the address 'copy' isn't the same as the image address of 'orig'.
1883 copy->SetReadBarrierPointer(GetImageAddress(orig));
1884 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
1885 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08001886 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001887 auto* klass = orig->GetClass();
1888 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001889 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07001890 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
1891 if (it != pointer_arrays_.end()) {
1892 // Should only need to fixup every pointer array exactly once.
1893 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
1894 pointer_arrays_.erase(it);
1895 return;
1896 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001897 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001898 if (orig->IsClass()) {
1899 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001900 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001901 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
1902 // Need to go update the ArtMethod.
1903 auto* dest = down_cast<mirror::AbstractMethod*>(copy);
1904 auto* src = down_cast<mirror::AbstractMethod*>(orig);
1905 ArtMethod* src_method = src->GetArtMethod();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001906 auto it = native_object_relocations_.find(src_method);
1907 CHECK(it != native_object_relocations_.end())
1908 << "Missing relocation for AbstractMethod.artMethod " << PrettyMethod(src_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001909 dest->SetArtMethod(
Jeff Haodcdc85b2015-12-04 14:06:18 -08001910 reinterpret_cast<ArtMethod*>(global_image_begin_ + it->second.offset));
Vladimir Marko05792b92015-08-03 11:56:49 +01001911 } else if (!klass->IsArrayClass()) {
1912 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1913 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
1914 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001915 } else if (klass->IsClassLoaderClass()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001916 mirror::ClassLoader* copy_loader = down_cast<mirror::ClassLoader*>(copy);
Vladimir Marko05792b92015-08-03 11:56:49 +01001917 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
1918 // ClassLoader.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001919 copy_loader->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07001920 // Also set allocator to null to be safe. The allocator is created when we create the class
1921 // table. We also never expect to unload things in the image since they are held live as
1922 // roots.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001923 copy_loader->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01001924 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001925 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001926 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001927 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001928 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001929}
1930
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001931
1932class ImageAddressVisitor {
1933 public:
1934 explicit ImageAddressVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
1935
1936 template <typename T>
1937 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
1938 return image_writer_->GetImageAddress(ptr);
1939 }
1940
1941 private:
1942 ImageWriter* const image_writer_;
1943};
1944
1945
Vladimir Marko05792b92015-08-03 11:56:49 +01001946void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
1947 mirror::DexCache* copy_dex_cache) {
1948 // Though the DexCache array fields are usually treated as native pointers, we set the full
1949 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
1950 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
1951 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
1952 GcRoot<mirror::String>* orig_strings = orig_dex_cache->GetStrings();
1953 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001954 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001955 NativeLocationInImage(orig_strings),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001956 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001957 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings, orig_dex_cache),
1958 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001959 }
1960 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
1961 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001962 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001963 NativeLocationInImage(orig_types),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001964 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001965 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types, orig_dex_cache),
1966 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001967 }
1968 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
1969 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001970 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001971 NativeLocationInImage(orig_methods),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001972 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001973 ArtMethod** copy_methods = NativeCopyLocation(orig_methods, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01001974 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
1975 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001976 // NativeLocationInImage also handles runtime methods since these have relocation info.
1977 ArtMethod* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01001978 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
1979 }
1980 }
1981 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
1982 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001983 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001984 NativeLocationInImage(orig_fields),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001985 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001986 ArtField** copy_fields = NativeCopyLocation(orig_fields, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01001987 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
1988 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, i, target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08001989 ArtField* copy = NativeLocationInImage(orig);
Vladimir Marko05792b92015-08-03 11:56:49 +01001990 mirror::DexCache::SetElementPtrSize(copy_fields, i, copy, target_ptr_size_);
1991 }
1992 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08001993
1994 // Remove the DexFile pointers. They will be fixed up when the runtime loads the oat file. Leaving
1995 // compiler pointers in here will make the output non-deterministic.
1996 copy_dex_cache->SetDexFile(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01001997}
1998
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001999const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
2000 DCHECK_LT(type, kOatAddressCount);
2001 // If we are compiling an app image, we need to use the stubs of the boot image.
2002 if (compile_app_image_) {
2003 // Use the current image pointers.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002004 const std::vector<gc::space::ImageSpace*>& image_spaces =
Jeff Haodcdc85b2015-12-04 14:06:18 -08002005 Runtime::Current()->GetHeap()->GetBootImageSpaces();
2006 DCHECK(!image_spaces.empty());
2007 const OatFile* oat_file = image_spaces[0]->GetOatFile();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002008 CHECK(oat_file != nullptr);
2009 const OatHeader& header = oat_file->GetOatHeader();
2010 switch (type) {
2011 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
2012 case kOatAddressQuickGenericJNITrampoline:
2013 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
2014 case kOatAddressInterpreterToInterpreterBridge:
2015 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
2016 case kOatAddressInterpreterToCompiledCodeBridge:
2017 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
2018 case kOatAddressJNIDlsymLookup:
2019 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
2020 case kOatAddressQuickIMTConflictTrampoline:
2021 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
2022 case kOatAddressQuickResolutionTrampoline:
2023 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
2024 case kOatAddressQuickToInterpreterBridge:
2025 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
2026 default:
2027 UNREACHABLE();
2028 }
2029 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002030 const ImageInfo& primary_image_info = GetImageInfo(0);
2031 return GetOatAddressForOffset(primary_image_info.oat_address_offsets_[type], primary_image_info);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002032}
2033
Jeff Haodcdc85b2015-12-04 14:06:18 -08002034const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method,
2035 const ImageInfo& image_info,
2036 bool* quick_is_interpreted) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002037 DCHECK(!method->IsResolutionMethod()) << PrettyMethod(method);
2038 DCHECK(!method->IsImtConflictMethod()) << PrettyMethod(method);
2039 DCHECK(!method->IsImtUnimplementedMethod()) << PrettyMethod(method);
Alex Light9139e002015-10-09 15:59:48 -07002040 DCHECK(method->IsInvokable()) << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002041 DCHECK(!IsInBootImage(method)) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002042
2043 // Use original code if it exists. Otherwise, set the code pointer to the resolution
2044 // trampoline.
2045
2046 // Quick entrypoint:
Jeff Haoc7d11882015-02-03 15:08:39 -08002047 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(
2048 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_));
Jeff Haodcdc85b2015-12-04 14:06:18 -08002049 const uint8_t* quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002050 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002051 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
2052 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002053 // We have code for a non-static or initialized method, just use the code.
2054 } else if (quick_code == nullptr && method->IsNative() &&
2055 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
2056 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002057 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002058 } else if (quick_code == nullptr && !method->IsNative()) {
2059 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002060 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002061 *quick_is_interpreted = true;
2062 } else {
2063 CHECK(!method->GetDeclaringClass()->IsInitialized());
2064 // We have code for a static method, but need to go through the resolution stub for class
2065 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002066 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
2067 }
2068 if (!IsInBootOatFile(quick_code)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002069 // DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002070 }
2071 return quick_code;
2072}
2073
Jeff Haodcdc85b2015-12-04 14:06:18 -08002074void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
2075 ArtMethod* copy,
2076 const ImageInfo& image_info) {
Vladimir Marko14632852015-08-17 12:07:23 +01002077 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002078
2079 copy->SetDeclaringClass(GetImageAddress(orig->GetDeclaringClassUnchecked()));
Vladimir Marko05792b92015-08-03 11:56:49 +01002080
2081 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002082 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods), target_ptr_size_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002083 GcRoot<mirror::Class>* orig_resolved_types = orig->GetDexCacheResolvedTypes(target_ptr_size_);
Mathieu Chartiere8bf1342016-02-17 18:02:40 -08002084 copy->SetDexCacheResolvedTypes(NativeLocationInImage(orig_resolved_types), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002085
Ian Rogers848871b2013-08-05 10:56:33 -07002086 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
2087 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07002088
Ian Rogers848871b2013-08-05 10:56:33 -07002089 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002090 Runtime* runtime = Runtime::Current();
2091 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002092 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002093 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002094 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
2095 orig == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002096 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002097 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002098 } else if (UNLIKELY(orig->IsRuntimeMethod())) {
2099 bool found_one = false;
2100 for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) {
2101 auto idx = static_cast<Runtime::CalleeSaveType>(i);
2102 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
2103 found_one = true;
2104 break;
2105 }
2106 }
2107 CHECK(found_one) << "Expected to find callee save method but got " << PrettyMethod(orig);
2108 CHECK(copy->IsRuntimeMethod());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002109 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002110 // We assume all methods have code. If they don't currently then we set them to the use the
2111 // resolution trampoline. Abstract methods never have code and so we need to make sure their
2112 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07002113 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002114 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002115 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002116 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002117 bool quick_is_interpreted;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002118 const uint8_t* quick_code = GetQuickCode(orig, image_info, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002119 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02002120
Sebastien Hertze1d07812014-05-21 15:44:09 +02002121 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07002122 if (orig->IsNative()) {
2123 // The native method's pointer is set to a stub to lookup via dlsym.
2124 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002125 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002126 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002127 }
2128 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002129 }
2130}
2131
Alex Lighta59dd802014-07-02 16:28:08 -07002132static OatHeader* GetOatHeaderFromElf(ElfFile* elf) {
Tong Shen62d1ca32014-09-03 17:24:56 -07002133 uint64_t data_sec_offset;
2134 bool has_data_sec = elf->GetSectionOffsetAndSize(".rodata", &data_sec_offset, nullptr);
2135 if (!has_data_sec) {
Alex Lighta59dd802014-07-02 16:28:08 -07002136 return nullptr;
2137 }
Tong Shen62d1ca32014-09-03 17:24:56 -07002138 return reinterpret_cast<OatHeader*>(elf->Begin() + data_sec_offset);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08002139}
2140
Vladimir Markof4da6752014-08-01 19:04:18 +01002141void ImageWriter::SetOatChecksumFromElfFile(File* elf_file) {
Alex Lighta59dd802014-07-02 16:28:08 -07002142 std::string error_msg;
Mathieu Chartiera808bac2015-11-05 16:33:15 -08002143 std::unique_ptr<ElfFile> elf(ElfFile::Open(elf_file,
2144 PROT_READ | PROT_WRITE,
2145 MAP_SHARED,
2146 &error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -07002147 if (elf.get() == nullptr) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002148 LOG(FATAL) << "Unable open oat file: " << error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07002149 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002150 }
Alex Lighta59dd802014-07-02 16:28:08 -07002151 OatHeader* oat_header = GetOatHeaderFromElf(elf.get());
2152 CHECK(oat_header != nullptr);
2153 CHECK(oat_header->IsValid());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002154
Jeff Haodcdc85b2015-12-04 14:06:18 -08002155 ImageInfo& image_info = GetImageInfo(oat_file_->GetLocation().c_str());
2156 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Alex Lighta59dd802014-07-02 16:28:08 -07002157 image_header->SetOatChecksum(oat_header->GetChecksum());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002158}
2159
Jeff Haodcdc85b2015-12-04 14:06:18 -08002160size_t ImageWriter::GetBinSizeSum(ImageWriter::ImageInfo& image_info, ImageWriter::Bin up_to) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002161 DCHECK_LE(up_to, kBinSize);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002162 return std::accumulate(&image_info.bin_slot_sizes_[0],
2163 &image_info.bin_slot_sizes_[up_to],
2164 /*init*/0);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002165}
2166
2167ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
2168 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07002169 static_assert(kBinBits == 3, "wrong number of bin bits");
2170 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002171 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
2172
2173 DCHECK_LT(GetBin(), kBinSize);
2174 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
2175}
2176
2177ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
2178 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
2179 DCHECK_EQ(index, GetIndex());
2180}
2181
2182ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
2183 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
2184}
2185
2186uint32_t ImageWriter::BinSlot::GetIndex() const {
2187 return lockword_ & ~kBinMask;
2188}
2189
Jeff Haodcdc85b2015-12-04 14:06:18 -08002190uint8_t* ImageWriter::GetOatFileBegin(const char* oat_filename) const {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002191 uintptr_t last_image_end = 0;
2192 for (const char* oat_fn : oat_filenames_) {
2193 const ImageInfo& image_info = GetConstImageInfo(oat_fn);
2194 DCHECK(image_info.image_begin_ != nullptr);
2195 uintptr_t this_end = reinterpret_cast<uintptr_t>(image_info.image_begin_) +
2196 image_info.image_size_;
2197 last_image_end = std::max(this_end, last_image_end);
2198 }
2199 const ImageInfo& image_info = GetConstImageInfo(oat_filename);
2200 return reinterpret_cast<uint8_t*>(last_image_end) + image_info.oat_offset_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002201}
2202
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002203ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
2204 switch (type) {
2205 case kNativeObjectRelocationTypeArtField:
2206 case kNativeObjectRelocationTypeArtFieldArray:
2207 return kBinArtField;
2208 case kNativeObjectRelocationTypeArtMethodClean:
2209 case kNativeObjectRelocationTypeArtMethodArrayClean:
2210 return kBinArtMethodClean;
2211 case kNativeObjectRelocationTypeArtMethodDirty:
2212 case kNativeObjectRelocationTypeArtMethodArrayDirty:
2213 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01002214 case kNativeObjectRelocationTypeDexCacheArray:
2215 return kBinDexCacheArray;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002216 }
2217 UNREACHABLE();
2218}
2219
Jeff Haodcdc85b2015-12-04 14:06:18 -08002220const char* ImageWriter::GetOatFilename(mirror::Object* obj) const {
2221 if (compile_app_image_) {
2222 return default_oat_filename_;
2223 } else {
2224 return GetOatFilenameForDexCache(obj->IsDexCache() ? obj->AsDexCache() :
2225 obj->IsClass() ? obj->AsClass()->GetDexCache() : obj->GetClass()->GetDexCache());
2226 }
2227}
2228
2229const char* ImageWriter::GetOatFilenameForDexCache(mirror::DexCache* dex_cache) const {
2230 if (compile_app_image_ || dex_cache == nullptr) {
2231 return default_oat_filename_;
2232 } else {
2233 auto it = dex_file_oat_filename_map_.find(dex_cache->GetDexFile());
2234 DCHECK(it != dex_file_oat_filename_map_.end()) << dex_cache->GetDexFile()->GetLocation();
2235 return it->second;
2236 }
2237}
2238
2239ImageWriter::ImageInfo& ImageWriter::GetImageInfo(const char* oat_filename) {
2240 auto it = image_info_map_.find(oat_filename);
2241 DCHECK(it != image_info_map_.end());
2242 return it->second;
2243}
2244
2245const ImageWriter::ImageInfo& ImageWriter::GetConstImageInfo(const char* oat_filename) const {
2246 auto it = image_info_map_.find(oat_filename);
2247 DCHECK(it != image_info_map_.end());
2248 return it->second;
2249}
2250
2251const ImageWriter::ImageInfo& ImageWriter::GetImageInfo(size_t index) const {
2252 DCHECK_LT(index, oat_filenames_.size());
2253 return GetConstImageInfo(oat_filenames_[index]);
2254}
2255
Vladimir Marko45724f92016-02-17 17:46:10 +00002256void ImageWriter::UpdateOatFile(File* oat_file, const char* oat_filename) {
2257 DCHECK(oat_file != nullptr);
Mathieu Chartier14567fd2016-01-28 20:33:36 -08002258 if (compile_app_image_) {
2259 CHECK_EQ(oat_filenames_.size(), 1u) << "App image should have no next image.";
2260 return;
2261 }
Vladimir Marko45724f92016-02-17 17:46:10 +00002262 ImageInfo& cur_image_info = GetImageInfo(oat_filename);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002263
2264 // Update the oat_offset of the next image info.
Vladimir Marko45724f92016-02-17 17:46:10 +00002265 auto it = std::find(oat_filenames_.begin(), oat_filenames_.end(), oat_filename);
2266 DCHECK(it != oat_filenames_.end());
2267
2268 it++;
2269 if (it != oat_filenames_.end()) {
2270 size_t oat_loaded_size = 0;
2271 size_t oat_data_offset = 0;
2272 ElfWriter::GetOatElfInformation(oat_file, &oat_loaded_size, &oat_data_offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002273 // There is a following one.
Vladimir Marko45724f92016-02-17 17:46:10 +00002274 ImageInfo& next_image_info = GetImageInfo(*it);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002275 next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
2276 }
2277}
2278
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002279ImageWriter::ImageWriter(
2280 const CompilerDriver& compiler_driver,
2281 uintptr_t image_begin,
2282 bool compile_pic,
2283 bool compile_app_image,
2284 ImageHeader::StorageMode image_storage_mode,
2285 const std::vector<const char*> oat_filenames,
2286 const std::unordered_map<const DexFile*, const char*>& dex_file_oat_filename_map)
2287 : compiler_driver_(compiler_driver),
2288 global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
2289 image_objects_offset_begin_(0),
2290 oat_file_(nullptr),
2291 compile_pic_(compile_pic),
2292 compile_app_image_(compile_app_image),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002293 target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())),
2294 image_method_array_(ImageHeader::kImageMethodsCount),
2295 dirty_methods_(0u),
2296 clean_methods_(0u),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002297 image_storage_mode_(image_storage_mode),
2298 dex_file_oat_filename_map_(dex_file_oat_filename_map),
2299 oat_filenames_(oat_filenames),
2300 default_oat_filename_(oat_filenames[0]) {
2301 CHECK_NE(image_begin, 0U);
2302 for (const char* oat_filename : oat_filenames) {
2303 image_info_map_.emplace(oat_filename, ImageInfo());
2304 }
2305 std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
Mathieu Chartier901e0702016-02-19 13:42:48 -08002306 CHECK_EQ(compile_app_image, !Runtime::Current()->GetHeap()->GetBootImageSpaces().empty())
2307 << "Compiling a boot image should occur iff there are no boot image spaces loaded";
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002308}
2309
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002310ImageWriter::ImageInfo::ImageInfo()
2311 : intern_table_(new InternTable),
2312 class_table_(new ClassTable) {}
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002313
Brian Carlstrom7940e442013-07-12 13:46:57 -07002314} // namespace art