blob: 31342978efac5181ca5ad6d3daaa09655817224c [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 {
79 if (!compile_app_image_) {
80 DCHECK(boot_image_space_ == nullptr);
81 return false;
82 }
83 const uint8_t* image_begin = boot_image_space_->Begin();
84 // Real image end including ArtMethods and ArtField sections.
85 const uint8_t* image_end = image_begin + boot_image_space_->GetImageHeader().GetImageSize();
86 return image_begin <= obj && obj < image_end;
87}
88
89bool ImageWriter::IsInBootOatFile(const void* ptr) const {
90 if (!compile_app_image_) {
91 DCHECK(boot_image_space_ == nullptr);
92 return false;
93 }
94 const ImageHeader& image_header = boot_image_space_->GetImageHeader();
95 return image_header.GetOatFileBegin() <= ptr && ptr < image_header.GetOatFileEnd();
96}
97
Andreas Gampedd9d0552015-03-09 12:57:41 -070098static void CheckNoDexObjectsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -070099 SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampedd9d0552015-03-09 12:57:41 -0700100 Class* klass = obj->GetClass();
101 CHECK_NE(PrettyClass(klass), "com.android.dex.Dex");
102}
103
104static void CheckNoDexObjects() {
105 ScopedObjectAccess soa(Thread::Current());
106 Runtime::Current()->GetHeap()->VisitObjects(CheckNoDexObjectsCallback, nullptr);
107}
108
Vladimir Markof4da6752014-08-01 19:04:18 +0100109bool ImageWriter::PrepareImageAddressSpace() {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800110 target_ptr_size_ = InstructionSetPointerSize(compiler_driver_.GetInstructionSet());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800111 gc::Heap* const heap = Runtime::Current()->GetHeap();
112 // Cache boot image space.
113 for (gc::space::ContinuousSpace* space : heap->GetContinuousSpaces()) {
114 if (space->IsImageSpace()) {
115 CHECK(compile_app_image_);
116 CHECK(boot_image_space_ == nullptr) << "Multiple image spaces";
117 boot_image_space_ = space->AsImageSpace();
118 }
119 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100120 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700121 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof4da6752014-08-01 19:04:18 +0100122 PruneNonImageClasses(); // Remove junk
123 ComputeLazyFieldsForImageClasses(); // Add useful information
Vladimir Markof4da6752014-08-01 19:04:18 +0100124 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100125 heap->CollectGarbage(false); // Remove garbage.
126
Andreas Gampedd9d0552015-03-09 12:57:41 -0700127 // Dex caches must not have their dex fields set in the image. These are memory buffers of mapped
128 // dex files.
129 //
130 // We may open them in the unstarted-runtime code for class metadata. Their fields should all be
131 // reset in PruneNonImageClasses and the objects reclaimed in the GC. Make sure that's actually
132 // true.
133 if (kIsDebugBuild) {
134 CheckNoDexObjects();
135 }
136
Vladimir Markof4da6752014-08-01 19:04:18 +0100137 if (kIsDebugBuild) {
138 ScopedObjectAccess soa(Thread::Current());
139 CheckNonImageClassesRemoved();
140 }
141
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700142 {
143 ScopedObjectAccess soa(Thread::Current());
144 CalculateNewObjectOffsets();
145 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100146
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700147 // This needs to happen after CalculateNewObjectOffsets since it relies on intern_table_bytes_ and
148 // bin size sums being calculated.
149 if (!AllocMemory()) {
150 return false;
151 }
152
Vladimir Markof4da6752014-08-01 19:04:18 +0100153 return true;
154}
155
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700156bool ImageWriter::Write(int image_fd,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800157 const std::vector<const char*>& image_filenames,
158 const std::vector<const char*>& oat_filenames) {
159 CHECK(!image_filenames.empty());
160 CHECK(!oat_filenames.empty());
161 CHECK_EQ(image_filenames.size(), oat_filenames.size());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700162
Jeff Haodcdc85b2015-12-04 14:06:18 -0800163 size_t oat_file_offset = 0;
164
165 for (size_t i = 0; i < oat_filenames.size(); ++i) {
166 const char* oat_filename = oat_filenames[i];
167 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename));
168 if (oat_file.get() == nullptr) {
169 PLOG(ERROR) << "Failed to open oat file " << oat_filename;
170 return false;
171 }
172 std::string error_msg;
173 oat_file_ = OatFile::OpenReadable(oat_file.get(), oat_filename, nullptr, &error_msg);
174 if (oat_file_ == nullptr) {
175 PLOG(ERROR) << "Failed to open writable oat file " << oat_filename;
176 oat_file->Erase();
177 return false;
178 }
179 Runtime::Current()->GetOatFileManager().RegisterOatFile(
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700180 std::unique_ptr<const OatFile>(oat_file_));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700181
Jeff Haodcdc85b2015-12-04 14:06:18 -0800182 const OatHeader& oat_header = oat_file_->GetOatHeader();
183 ImageInfo& image_info = GetImageInfo(oat_filename);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700184
Jeff Haodcdc85b2015-12-04 14:06:18 -0800185 size_t oat_loaded_size = 0;
186 size_t oat_data_offset = 0;
187 ElfWriter::GetOatElfInformation(oat_file.get(), &oat_loaded_size, &oat_data_offset);
188
189 DCHECK_EQ(image_info.oat_offset_, oat_file_offset);
190 oat_file_offset += oat_loaded_size;
191
192 if (i == 0) {
193 // Primary oat file, read the trampolines.
194 image_info.oat_address_offsets_[kOatAddressInterpreterToInterpreterBridge] =
195 oat_header.GetInterpreterToInterpreterBridgeOffset();
196 image_info.oat_address_offsets_[kOatAddressInterpreterToCompiledCodeBridge] =
197 oat_header.GetInterpreterToCompiledCodeBridgeOffset();
198 image_info.oat_address_offsets_[kOatAddressJNIDlsymLookup] =
199 oat_header.GetJniDlsymLookupOffset();
200 image_info.oat_address_offsets_[kOatAddressQuickGenericJNITrampoline] =
201 oat_header.GetQuickGenericJniTrampolineOffset();
202 image_info.oat_address_offsets_[kOatAddressQuickIMTConflictTrampoline] =
203 oat_header.GetQuickImtConflictTrampolineOffset();
204 image_info.oat_address_offsets_[kOatAddressQuickResolutionTrampoline] =
205 oat_header.GetQuickResolutionTrampolineOffset();
206 image_info.oat_address_offsets_[kOatAddressQuickToInterpreterBridge] =
207 oat_header.GetQuickToInterpreterBridgeOffset();
208 } else {
209 // Other oat files use the primary trampolines.
210 // TODO: Dummy values to protect usage? b/26317072
211 }
212
213
214 {
215 ScopedObjectAccess soa(Thread::Current());
216 CreateHeader(oat_loaded_size, oat_data_offset);
217 CopyAndFixupNativeData();
218 }
219
220 SetOatChecksumFromElfFile(oat_file.get());
221
222 if (oat_file->FlushCloseOrErase() != 0) {
223 LOG(ERROR) << "Failed to flush and close oat file " << oat_filename;
224 return false;
225 }
226 }
Alex Light53cb16b2014-06-12 11:26:29 -0700227
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700228 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700229 // TODO: heap validation can't handle these fix up passes.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800230 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700231 Runtime::Current()->GetHeap()->DisableObjectValidation();
232 CopyAndFixupObjects();
233 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700234
Jeff Haodcdc85b2015-12-04 14:06:18 -0800235 for (size_t i = 0; i < image_filenames.size(); ++i) {
236 const char* image_filename = image_filenames[i];
237 const char* oat_filename = oat_filenames[i];
238 ImageInfo& image_info = GetImageInfo(oat_filename);
239 std::unique_ptr<File> image_file;
240 if (image_fd != kInvalidImageFd) {
241 image_file.reset(new File(image_fd, image_filename, unix_file::kCheckSafeUsage));
242 } else {
243 image_file.reset(OS::CreateEmptyFile(image_filename));
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800244 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800245 if (image_file == nullptr) {
246 LOG(ERROR) << "Failed to open image file " << image_filename;
247 return false;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800248 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800249 if (fchmod(image_file->Fd(), 0644) != 0) {
250 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
251 image_file->Erase();
252 return EXIT_FAILURE;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800253 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800254
Jeff Haodcdc85b2015-12-04 14:06:18 -0800255 std::unique_ptr<char[]> compressed_data;
256 // Image data size excludes the bitmap and the header.
257 ImageHeader* const image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
258 const size_t image_data_size = image_header->GetImageSize() - sizeof(ImageHeader);
259 char* image_data = reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader);
260 size_t data_size;
261 const char* image_data_to_write;
Nicolas Geoffray83d4d722015-12-10 08:26:32 +0000262
Jeff Haodcdc85b2015-12-04 14:06:18 -0800263 CHECK_EQ(image_header->storage_mode_, image_storage_mode_);
264 switch (image_storage_mode_) {
265 case ImageHeader::kStorageModeLZ4: {
266 size_t compressed_max_size = LZ4_compressBound(image_data_size);
267 compressed_data.reset(new char[compressed_max_size]);
268 data_size = LZ4_compress(
269 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
270 &compressed_data[0],
271 image_data_size);
272 image_data_to_write = &compressed_data[0];
273 VLOG(compiler) << "Compressed from " << image_data_size << " to " << data_size;
274 break;
275 }
276 case ImageHeader::kStorageModeUncompressed: {
277 data_size = image_data_size;
278 image_data_to_write = image_data;
279 break;
280 }
281 default: {
282 LOG(FATAL) << "Unsupported";
283 UNREACHABLE();
284 }
285 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800286
Jeff Haodcdc85b2015-12-04 14:06:18 -0800287 // Write header first, as uncompressed.
288 image_header->data_size_ = data_size;
289 if (!image_file->WriteFully(image_info.image_->Begin(), sizeof(ImageHeader))) {
290 PLOG(ERROR) << "Failed to write image file header " << image_filename;
291 image_file->Erase();
292 return false;
293 }
294
295 // Write out the image + fields + methods.
296 const bool is_compressed = compressed_data != nullptr;
297 if (!image_file->WriteFully(image_data_to_write, data_size)) {
298 PLOG(ERROR) << "Failed to write image file data " << image_filename;
299 image_file->Erase();
300 return false;
301 }
302
303 // Write out the image bitmap at the page aligned start of the image end, also uncompressed for
304 // convenience.
305 const ImageSection& bitmap_section = image_header->GetImageSection(
306 ImageHeader::kSectionImageBitmap);
307 // Align up since data size may be unaligned if the image is compressed.
308 size_t bitmap_position_in_file = RoundUp(sizeof(ImageHeader) + data_size, kPageSize);
309 if (!is_compressed) {
310 CHECK_EQ(bitmap_position_in_file, bitmap_section.Offset());
311 }
312 if (!image_file->Write(reinterpret_cast<char*>(image_info.image_bitmap_->Begin()),
313 bitmap_section.Size(),
314 bitmap_position_in_file)) {
315 PLOG(ERROR) << "Failed to write image file " << image_filename;
316 image_file->Erase();
317 return false;
318 }
319 CHECK_EQ(bitmap_position_in_file + bitmap_section.Size(),
320 static_cast<size_t>(image_file->GetLength()));
321 if (image_file->FlushCloseOrErase() != 0) {
322 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
323 return false;
324 }
Andreas Gampe4303ba92014-11-06 01:00:46 -0800325 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700326 return true;
327}
328
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700329void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700330 DCHECK(object != nullptr);
331 DCHECK_NE(offset, 0U);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800332
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800333 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700334 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700335 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700336 DCHECK(IsImageOffsetAssigned(object));
337}
338
Mathieu Chartiere401d142015-04-22 13:56:20 -0700339void ImageWriter::UpdateImageOffset(mirror::Object* obj, uintptr_t offset) {
340 DCHECK(IsImageOffsetAssigned(obj)) << obj << " " << offset;
341 obj->SetLockWord(LockWord::FromForwardingAddress(offset), false);
342 DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0u);
343}
344
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800345void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700346 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800347 DCHECK_NE(image_objects_offset_begin_, 0u);
348
Jeff Haodcdc85b2015-12-04 14:06:18 -0800349 const char* oat_filename = GetOatFilename(object);
350 ImageInfo& image_info = GetImageInfo(oat_filename);
351 size_t bin_slot_offset = image_info.bin_slot_offsets_[bin_slot.GetBin()];
Vladimir Markocf36d492015-08-12 19:27:26 +0100352 size_t new_offset = bin_slot_offset + bin_slot.GetIndex();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800353 DCHECK_ALIGNED(new_offset, kObjectAlignment);
354
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700355 SetImageOffset(object, new_offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800356 DCHECK_LT(new_offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700357}
358
Ian Rogersef7d42f2014-01-06 12:55:46 -0800359bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800360 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700361 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700362 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700363}
364
Ian Rogersef7d42f2014-01-06 12:55:46 -0800365size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700366 DCHECK(object != nullptr);
367 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700368 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700369 size_t offset = lock_word.ForwardingAddress();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800370 const char* oat_filename = GetOatFilename(object);
371 const ImageInfo& image_info = GetConstImageInfo(oat_filename);
372 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700373 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700374}
375
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800376void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
377 DCHECK(object != nullptr);
378 DCHECK(!IsImageOffsetAssigned(object));
379 DCHECK(!IsImageBinSlotAssigned(object));
380
381 // Before we stomp over the lock word, save the hash code for later.
382 Monitor::Deflate(Thread::Current(), object);;
383 LockWord lw(object->GetLockWord(false));
384 switch (lw.GetState()) {
385 case LockWord::kFatLocked: {
386 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
387 break;
388 }
389 case LockWord::kThinLocked: {
390 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
391 break;
392 }
393 case LockWord::kUnlocked:
394 // No hash, don't need to save it.
395 break;
396 case LockWord::kHashCode:
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700397 DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
398 saved_hashcode_map_.emplace(object, lw.GetHashCode());
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800399 break;
400 default:
401 LOG(FATAL) << "Unreachable.";
402 UNREACHABLE();
403 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700404 object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700405 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800406 DCHECK(IsImageBinSlotAssigned(object));
407}
408
Vladimir Marko20f85592015-03-19 10:07:02 +0000409void ImageWriter::PrepareDexCacheArraySlots() {
Vladimir Markof60c7e22015-11-23 18:05:08 +0000410 // Prepare dex cache array starts based on the ordering specified in the CompilerDriver.
Vladimir Markof60c7e22015-11-23 18:05:08 +0000411 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
412 // when AssignImageBinSlot() assigns their indexes out or order.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800413 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
414 auto it = dex_file_oat_filename_map_.find(dex_file);
415 DCHECK(it != dex_file_oat_filename_map_.end()) << dex_file->GetLocation();
416 ImageInfo& image_info = GetImageInfo(it->second);
417 image_info.dex_cache_array_starts_.Put(dex_file, image_info.bin_slot_sizes_[kBinDexCacheArray]);
418 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
419 image_info.bin_slot_sizes_[kBinDexCacheArray] += layout.Size();
420 }
Vladimir Markof60c7e22015-11-23 18:05:08 +0000421
Vladimir Marko20f85592015-03-19 10:07:02 +0000422 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700423 Thread* const self = Thread::Current();
424 ReaderMutexLock mu(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800425 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700426 mirror::DexCache* dex_cache =
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800427 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800428 if (dex_cache == nullptr || IsInBootImage(dex_cache)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700429 continue;
430 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000431 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc7853442015-03-27 14:35:38 -0700432 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
Vladimir Marko20f85592015-03-19 10:07:02 +0000433 DCHECK(layout.Valid());
Jeff Haodcdc85b2015-12-04 14:06:18 -0800434 const char* oat_filename = GetOatFilenameForDexCache(dex_cache);
435 ImageInfo& image_info = GetImageInfo(oat_filename);
436 uint32_t start = image_info.dex_cache_array_starts_.Get(dex_file);
Vladimir Marko05792b92015-08-03 11:56:49 +0100437 DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800438 AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(),
439 start + layout.TypesOffset(),
440 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100441 DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800442 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(),
443 start + layout.MethodsOffset(),
444 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100445 DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800446 AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(),
447 start + layout.FieldsOffset(),
448 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100449 DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800450 AddDexCacheArrayRelocation(dex_cache->GetStrings(), start + layout.StringsOffset(), dex_cache);
Vladimir Marko20f85592015-03-19 10:07:02 +0000451 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000452}
453
Jeff Haodcdc85b2015-12-04 14:06:18 -0800454void ImageWriter::AddDexCacheArrayRelocation(void* array, size_t offset, DexCache* dex_cache) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100455 if (array != nullptr) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800456 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -0800457 const char* oat_filename = GetOatFilenameForDexCache(dex_cache);
458 native_object_relocations_.emplace(array,
459 NativeObjectRelocation { oat_filename, offset, kNativeObjectRelocationTypeDexCacheArray });
Vladimir Marko05792b92015-08-03 11:56:49 +0100460 }
461}
462
Mathieu Chartiere401d142015-04-22 13:56:20 -0700463void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) {
464 DCHECK(arr != nullptr);
465 if (kIsDebugBuild) {
466 for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800467 ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700468 if (method != nullptr && !method->IsRuntimeMethod()) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800469 mirror::Class* klass = method->GetDeclaringClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800470 CHECK(klass == nullptr || KeepClass(klass))
471 << PrettyClass(klass) << " should be a kept class";
Mathieu Chartiere401d142015-04-22 13:56:20 -0700472 }
473 }
474 }
475 // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
476 // ArtMethods.
477 pointer_arrays_.emplace(arr, kBinArtMethodClean);
478}
479
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800480void ImageWriter::AssignImageBinSlot(mirror::Object* object) {
481 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800482 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800483
484 // The magic happens here. We segregate objects into different bins based
485 // on how likely they are to get dirty at runtime.
486 //
487 // Likely-to-dirty objects get packed together into the same bin so that
488 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
489 // maximized.
490 //
491 // This means more pages will stay either clean or shared dirty (with zygote) and
492 // the app will use less of its own (private) memory.
493 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000494 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800495
496 if (kBinObjects) {
497 //
498 // Changing the bin of an object is purely a memory-use tuning.
499 // It has no change on runtime correctness.
500 //
501 // Memory analysis has determined that the following types of objects get dirtied
502 // the most:
503 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000504 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
505 // a fixed layout which helps improve generated code (using PC-relative addressing),
506 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
507 // Since these arrays are huge, most pages do not overlap other objects and it's not
508 // really important where they are for the clean/dirty separation. Due to their
Vladimir Marko05792b92015-08-03 11:56:49 +0100509 // special PC-relative addressing, we arbitrarily keep them at the end.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800510 // * Class'es which are verified [their clinit runs only at runtime]
511 // - classes in general [because their static fields get overwritten]
512 // - initialized classes with all-final statics are unlikely to be ever dirty,
513 // so bin them separately
514 // * Art Methods that are:
515 // - native [their native entry point is not looked up until runtime]
516 // - have declaring classes that aren't initialized
517 // [their interpreter/quick entry points are trampolines until the class
518 // becomes initialized]
519 //
520 // We also assume the following objects get dirtied either never or extremely rarely:
521 // * Strings (they are immutable)
522 // * Art methods that aren't native and have initialized declared classes
523 //
524 // We assume that "regular" bin objects are highly unlikely to become dirtied,
525 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
526 //
527 if (object->IsClass()) {
528 bin = kBinClassVerified;
529 mirror::Class* klass = object->AsClass();
530
Mathieu Chartiere401d142015-04-22 13:56:20 -0700531 // Add non-embedded vtable to the pointer array table if there is one.
532 auto* vtable = klass->GetVTable();
533 if (vtable != nullptr) {
534 AddMethodPointerArray(vtable);
535 }
536 auto* iftable = klass->GetIfTable();
537 if (iftable != nullptr) {
538 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
539 if (iftable->GetMethodArrayCount(i) > 0) {
540 AddMethodPointerArray(iftable->GetMethodArray(i));
541 }
542 }
543 }
544
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800545 if (klass->GetStatus() == Class::kStatusInitialized) {
546 bin = kBinClassInitialized;
547
548 // If the class's static fields are all final, put it into a separate bin
549 // since it's very likely it will stay clean.
550 uint32_t num_static_fields = klass->NumStaticFields();
551 if (num_static_fields == 0) {
552 bin = kBinClassInitializedFinalStatics;
553 } else {
554 // Maybe all the statics are final?
555 bool all_final = true;
556 for (uint32_t i = 0; i < num_static_fields; ++i) {
557 ArtField* field = klass->GetStaticField(i);
558 if (!field->IsFinal()) {
559 all_final = false;
560 break;
561 }
562 }
563
564 if (all_final) {
565 bin = kBinClassInitializedFinalStatics;
566 }
567 }
568 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800569 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
570 bin = kBinString; // Strings are almost always immutable (except for object header).
571 } // else bin = kBinRegular
572 }
573
Jeff Haodcdc85b2015-12-04 14:06:18 -0800574 const char* oat_filename = GetOatFilename(object);
575 ImageInfo& image_info = GetImageInfo(oat_filename);
576
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800577 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Jeff Haodcdc85b2015-12-04 14:06:18 -0800578 current_offset = image_info.bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
579 // Move the current bin size up to accommodate the object we just assigned a bin slot.
580 image_info.bin_slot_sizes_[bin] += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800581
582 BinSlot new_bin_slot(bin, current_offset);
583 SetImageBinSlot(object, new_bin_slot);
584
Jeff Haodcdc85b2015-12-04 14:06:18 -0800585 ++image_info.bin_slot_count_[bin];
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800586
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800587 // Grow the image closer to the end by the object we just assigned.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800588 image_info.image_end_ += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800589}
590
Mathieu Chartiere401d142015-04-22 13:56:20 -0700591bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
592 if (m->IsNative()) {
593 return true;
594 }
595 mirror::Class* declaring_class = m->GetDeclaringClass();
596 // Initialized is highly unlikely to dirty since there's no entry points to mutate.
597 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
598}
599
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800600bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
601 DCHECK(object != nullptr);
602
603 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
604 // If it's in some other state, then we haven't yet assigned an image bin slot.
605 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
606 return false;
607 } else if (kIsDebugBuild) {
608 LockWord lock_word = object->GetLockWord(false);
609 size_t offset = lock_word.ForwardingAddress();
610 BinSlot bin_slot(offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800611 const char* oat_filename = GetOatFilename(object);
612 const ImageInfo& image_info = GetConstImageInfo(oat_filename);
613 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()])
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800614 << "bin slot offset should not exceed the size of that bin";
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800615 }
616 return true;
617}
618
619ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
620 DCHECK(object != nullptr);
621 DCHECK(IsImageBinSlotAssigned(object));
622
623 LockWord lock_word = object->GetLockWord(false);
624 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
625 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
626
627 BinSlot bin_slot(static_cast<uint32_t>(offset));
Jeff Haodcdc85b2015-12-04 14:06:18 -0800628 const char* oat_filename = GetOatFilename(object);
629 const ImageInfo& image_info = GetConstImageInfo(oat_filename);
630 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()]);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800631
632 return bin_slot;
633}
634
Brian Carlstrom7940e442013-07-12 13:46:57 -0700635bool ImageWriter::AllocMemory() {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800636 for (const char* oat_filename : oat_filenames_) {
637 ImageInfo& image_info = GetImageInfo(oat_filename);
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800638 ImageSection unused_sections[ImageHeader::kSectionCount];
639 const size_t length = RoundUp(
640 image_info.CreateImageSections(target_ptr_size_, unused_sections),
641 kPageSize);
642
Jeff Haodcdc85b2015-12-04 14:06:18 -0800643 std::string error_msg;
644 image_info.image_.reset(MemMap::MapAnonymous("image writer image",
645 nullptr,
646 length,
647 PROT_READ | PROT_WRITE,
648 false,
649 false,
650 &error_msg));
651 if (UNLIKELY(image_info.image_.get() == nullptr)) {
652 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
653 return false;
654 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700655
Jeff Haodcdc85b2015-12-04 14:06:18 -0800656 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
657 CHECK_LE(image_info.image_end_, length);
658 image_info.image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
659 "image bitmap", image_info.image_->Begin(), RoundUp(image_info.image_end_, kPageSize)));
660 if (image_info.image_bitmap_.get() == nullptr) {
661 LOG(ERROR) << "Failed to allocate memory for image bitmap";
662 return false;
663 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700664 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700665 return true;
666}
667
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700668class ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
669 public:
670 bool Visit(Class* c) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
671 StackHandleScope<1> hs(Thread::Current());
672 mirror::Class::ComputeName(hs.NewHandle(c));
673 return true;
674 }
675};
676
Brian Carlstrom7940e442013-07-12 13:46:57 -0700677void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700678 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700679 ComputeLazyFieldsForClassesVisitor visitor;
680 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700681}
682
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800683static bool IsBootClassLoaderClass(mirror::Class* klass) SHARED_REQUIRES(Locks::mutator_lock_) {
684 return klass->GetClassLoader() == nullptr;
685}
686
687bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
688 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
689}
690
691bool ImageWriter::ContainsBootClassLoaderNonImageClass(mirror::Class* klass) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800692 bool early_exit = false;
693 std::unordered_set<mirror::Class*> visited;
694 return ContainsBootClassLoaderNonImageClassInternal(klass, &early_exit, &visited);
695}
696
697bool ImageWriter::ContainsBootClassLoaderNonImageClassInternal(
698 mirror::Class* klass,
699 bool* early_exit,
700 std::unordered_set<mirror::Class*>* visited) {
701 DCHECK(early_exit != nullptr);
702 DCHECK(visited != nullptr);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700703 if (klass == nullptr) {
704 return false;
705 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800706 auto found = prune_class_memo_.find(klass);
707 if (found != prune_class_memo_.end()) {
708 // Already computed, return the found value.
709 return found->second;
710 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800711 // Circular dependencies, return false but do not store the result in the memoization table.
712 if (visited->find(klass) != visited->end()) {
713 *early_exit = true;
714 return false;
715 }
716 visited->emplace(klass);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800717 bool result = IsBootClassLoaderNonImageClass(klass);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800718 bool my_early_exit = false; // Only for ourselves, ignore caller.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800719 if (!result) {
720 // Check interfaces since these wont be visited through VisitReferences.)
721 mirror::IfTable* if_table = klass->GetIfTable();
722 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800723 result = result || ContainsBootClassLoaderNonImageClassInternal(
724 if_table->GetInterface(i),
725 &my_early_exit,
726 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800727 }
728 }
729 // Check static fields and their classes.
730 size_t num_static_fields = klass->NumReferenceStaticFields();
731 if (num_static_fields != 0 && klass->IsResolved()) {
732 // Presumably GC can happen when we are cross compiling, it should not cause performance
733 // problems to do pointer size logic.
734 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
735 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
736 for (size_t i = 0u; i < num_static_fields; ++i) {
737 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
738 if (ref != nullptr) {
739 if (ref->IsClass()) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800740 result = result ||
741 ContainsBootClassLoaderNonImageClassInternal(
742 ref->AsClass(),
743 &my_early_exit,
744 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800745 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800746 result = result ||
747 ContainsBootClassLoaderNonImageClassInternal(
748 ref->GetClass(),
749 &my_early_exit,
750 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800751 }
752 field_offset = MemberOffset(field_offset.Uint32Value() +
753 sizeof(mirror::HeapReference<mirror::Object>));
754 }
755 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800756 result = result ||
757 ContainsBootClassLoaderNonImageClassInternal(
758 klass->GetSuperClass(),
759 &my_early_exit,
760 visited);
761 // Erase the element we stored earlier since we are exiting the function.
762 auto it = visited->find(klass);
763 DCHECK(it != visited->end());
764 visited->erase(it);
765 // Only store result if it is true or none of the calls early exited due to circular
766 // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
767 // a child call and we can remember the result.
768 if (result == true || !my_early_exit || visited->empty()) {
769 prune_class_memo_[klass] = result;
770 }
771 *early_exit |= my_early_exit;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800772 return result;
773}
774
775bool ImageWriter::KeepClass(Class* klass) {
776 if (klass == nullptr) {
777 return false;
778 }
779 if (compile_app_image_) {
780 // For app images, we need to prune boot loader classes that are not in the boot image since
781 // these may have already been loaded when the app image is loaded.
782 return !ContainsBootClassLoaderNonImageClass(klass);
783 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700784 std::string temp;
785 return compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700786}
787
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700788class NonImageClassesVisitor : public ClassVisitor {
789 public:
790 explicit NonImageClassesVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
791
792 bool Visit(Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800793 if (!image_writer_->KeepClass(klass)) {
794 classes_to_prune_.insert(klass);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700795 }
796 return true;
797 }
798
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800799 std::unordered_set<mirror::Class*> classes_to_prune_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700800 ImageWriter* const image_writer_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700801};
802
803void ImageWriter::PruneNonImageClasses() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700804 Runtime* runtime = Runtime::Current();
805 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700806 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700807
808 // Make a list of classes we would like to prune.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700809 NonImageClassesVisitor visitor(this);
810 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700811
812 // Remove the undesired classes from the class roots.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800813 for (mirror::Class* klass : visitor.classes_to_prune_) {
814 std::string temp;
815 const char* name = klass->GetDescriptor(&temp);
816 VLOG(compiler) << "Pruning class " << name;
817 if (!compile_app_image_) {
818 DCHECK(IsBootClassLoaderClass(klass));
819 }
820 bool result = class_linker->RemoveClass(name, klass->GetClassLoader());
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800821 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700822 }
823
824 // Clear references to removed classes from the DexCaches.
Vladimir Marko05792b92015-08-03 11:56:49 +0100825 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700826
827 ScopedAssertNoThreadSuspension sa(self, __FUNCTION__);
828 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); // For ClassInClassTable
829 ReaderMutexLock mu2(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800830 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
831 mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700832 if (dex_cache == nullptr) {
833 continue;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700834 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700835 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
836 Class* klass = dex_cache->GetResolvedType(i);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800837 if (klass != nullptr && !KeepClass(klass)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700838 dex_cache->SetResolvedType(i, nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700839 }
840 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100841 ArtMethod** resolved_methods = dex_cache->GetResolvedMethods();
842 for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) {
843 ArtMethod* method =
844 mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700845 if (method != nullptr) {
846 auto* declaring_class = method->GetDeclaringClass();
847 // Miranda methods may be held live by a class which was not an image class but have a
848 // declaring class which is an image class. Set it to the resolution method to be safe and
849 // prevent dangling pointers.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800850 if (method->IsMiranda() || !KeepClass(declaring_class)) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100851 mirror::DexCache::SetElementPtrSize(resolved_methods,
852 i,
853 resolution_method,
854 target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700855 } else {
856 // Check that the class is still in the classes table.
857 DCHECK(class_linker->ClassInClassTable(declaring_class)) << "Class "
858 << PrettyClass(declaring_class) << " not in class linker table";
859 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700860 }
861 }
862 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700863 ArtField* field = dex_cache->GetResolvedField(i, target_ptr_size_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800864 if (field != nullptr && !KeepClass(field->GetDeclaringClass())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700865 dex_cache->SetResolvedField(i, nullptr, target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700866 }
867 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700868 // Clean the dex field. It might have been populated during the initialization phase, but
869 // contains data only valid during a real run.
870 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700871 }
Andreas Gampe8ac75952015-06-02 21:01:45 -0700872
873 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
874 class_linker->DropFindArrayClassCache();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800875
876 // Clear to save RAM.
877 prune_class_memo_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700878}
879
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800880void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700881 if (compiler_driver_.GetImageClasses() != nullptr) {
882 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700883 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700884 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700885}
886
887void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
888 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800889 if (obj->IsClass() && !image_writer->IsInBootImage(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700890 Class* klass = obj->AsClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800891 if (!image_writer->KeepClass(klass)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700892 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700893 std::string temp;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800894 CHECK(image_writer->KeepClass(klass)) << klass->GetDescriptor(&temp)
895 << " " << PrettyDescriptor(klass);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700896 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700897 }
898}
899
900void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700901 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700902 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700903 for (const std::string& image_class : *image_classes) {
904 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700905 }
906}
907
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800908void ImageWriter::CalculateObjectBinSlots(Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700909 DCHECK(obj != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700910 // if it is a string, we want to intern it if its not interned.
911 if (obj->GetClass()->IsStringClass()) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -0800912 const char* oat_filename = GetOatFilename(obj);
913 ImageInfo& image_info = GetImageInfo(oat_filename);
914
Brian Carlstrom7940e442013-07-12 13:46:57 -0700915 // we must be an interned string that was forward referenced and already assigned
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800916 if (IsImageBinSlotAssigned(obj)) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -0800917 DCHECK_EQ(obj, image_info.intern_table_->InternStrongImageString(obj->AsString()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700918 return;
919 }
Mathieu Chartier14c3bf92015-07-13 14:35:43 -0700920 // InternImageString allows us to intern while holding the heap bitmap lock. This is safe since
921 // we are guaranteed to not have GC during image writing.
Mathieu Chartierea0831f2015-12-29 13:17:37 -0800922 mirror::String* const interned = image_info.intern_table_->InternStrongImageString(
Mathieu Chartier14c3bf92015-07-13 14:35:43 -0700923 obj->AsString());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700924 if (obj != interned) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800925 if (!IsImageBinSlotAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700926 // interned obj is after us, allocate its location early
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800927 AssignImageBinSlot(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700928 }
929 // point those looking for this object to the interned version.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800930 SetImageBinSlot(obj, GetImageBinSlot(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700931 return;
932 }
933 // else (obj == interned), nothing to do but fall through to the normal case
934 }
935
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800936 AssignImageBinSlot(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700937}
938
Jeff Haodcdc85b2015-12-04 14:06:18 -0800939ObjectArray<Object>* ImageWriter::CreateImageRoots(const char* oat_filename) const {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700940 Runtime* runtime = Runtime::Current();
941 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700942 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700943 StackHandleScope<3> hs(self);
944 Handle<Class> object_array_class(hs.NewHandle(
945 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700946
Jeff Haodcdc85b2015-12-04 14:06:18 -0800947 std::unordered_set<const DexFile*> image_dex_files;
948 for (auto& pair : dex_file_oat_filename_map_) {
949 const DexFile* image_dex_file = pair.first;
950 const char* image_oat_filename = pair.second;
951 if (strcmp(oat_filename, image_oat_filename) == 0) {
952 image_dex_files.insert(image_dex_file);
953 }
954 }
955
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700956 // build an Object[] of all the DexCaches used in the source_space_.
957 // Since we can't hold the dex lock when allocating the dex_caches
958 // ObjectArray, we lock the dex lock twice, first to get the number
959 // of dex caches first and then lock it again to copy the dex
960 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800961 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700962 {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700963 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800964 // Count number of dex caches not in the boot image.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800965 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
966 mirror::DexCache* dex_cache =
967 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -0800968 const DexFile* dex_file = dex_cache->GetDexFile();
969 if (!IsInBootImage(dex_cache)) {
970 dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
971 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800972 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700973 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700974 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800975 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700976 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
977 {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700978 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800979 size_t non_image_dex_caches = 0;
980 // Re-count number of non image dex caches.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800981 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
982 mirror::DexCache* dex_cache =
983 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -0800984 const DexFile* dex_file = dex_cache->GetDexFile();
985 if (!IsInBootImage(dex_cache)) {
986 non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
987 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800988 }
989 CHECK_EQ(dex_cache_count, non_image_dex_caches)
990 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700991 size_t i = 0;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800992 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
993 mirror::DexCache* dex_cache =
994 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -0800995 const DexFile* dex_file = dex_cache->GetDexFile();
996 if (!IsInBootImage(dex_cache) && image_dex_files.find(dex_file) != image_dex_files.end()) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800997 dex_caches->Set<false>(i, dex_cache);
998 ++i;
999 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001000 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001001 }
1002
1003 // build an Object[] of the roots needed to restore the runtime
Mathieu Chartiere401d142015-04-22 13:56:20 -07001004 auto image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001005 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001006 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001007 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001008 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001009 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001010 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001011 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001012}
1013
Mathieu Chartier590fee92013-09-13 13:46:47 -07001014// Walk instance fields of the given Class. Separate function to allow recursion on the super
1015// class.
1016void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
1017 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001018 StackHandleScope<1> hs(Thread::Current());
1019 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1020 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001021 if (super != nullptr) {
1022 WalkInstanceFields(obj, super);
1023 }
1024 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001025 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Marko76649e82014-11-10 18:32:59 +00001026 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001027 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001028 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001029 if (value != nullptr) {
1030 WalkFieldsInOrder(value);
1031 }
Vladimir Marko76649e82014-11-10 18:32:59 +00001032 field_offset = MemberOffset(field_offset.Uint32Value() +
1033 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001034 }
1035}
1036
1037// For an unvisited object, visit it then all its children found via fields.
1038void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001039 if (IsInBootImage(obj)) {
1040 // Object is in the image, don't need to fix it up.
1041 return;
1042 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001043 // Use our own visitor routine (instead of GC visitor) to get better locality between
1044 // an object and its fields
1045 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001046 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001047 StackHandleScope<2> hs(Thread::Current());
1048 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
1049 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001050 // visit the object itself.
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001051 CalculateObjectBinSlots(h_obj.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001052 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001053 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001054 if (h_obj->IsClass()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001055 size_t num_reference_static_fields = klass->NumReferenceStaticFields();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001056 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001057 for (size_t i = 0; i < num_reference_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001058 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001059 if (value != nullptr) {
1060 WalkFieldsInOrder(value);
1061 }
Vladimir Marko76649e82014-11-10 18:32:59 +00001062 field_offset = MemberOffset(field_offset.Uint32Value() +
1063 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001064 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001065 // Visit and assign offsets for fields and field arrays.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001066 auto* as_klass = h_obj->AsClass();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001067 mirror::DexCache* dex_cache = as_klass->GetDexCache();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001068 LengthPrefixedArray<ArtField>* fields[] = {
1069 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
1070 };
Jeff Haodcdc85b2015-12-04 14:06:18 -08001071 const char* oat_file = GetOatFilenameForDexCache(dex_cache);
1072 ImageInfo& image_info = GetImageInfo(oat_file);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001073 {
1074 // Note: This table is only accessed from the image writer, so the lock is technically
1075 // unnecessary.
1076 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1077 // Insert in the class table for this iamge.
1078 image_info.class_table_->Insert(as_klass);
1079 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001080 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1081 // Total array length including header.
1082 if (cur_fields != nullptr) {
1083 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
1084 // Forward the entire array at once.
1085 auto it = native_object_relocations_.find(cur_fields);
1086 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
1087 << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001088 size_t& offset = image_info.bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001089 DCHECK(!IsInBootImage(cur_fields));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001090 native_object_relocations_.emplace(cur_fields,
1091 NativeObjectRelocation {oat_file, offset, kNativeObjectRelocationTypeArtFieldArray });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001092 offset += header_size;
1093 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +01001094 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001095 // Need to forward arrays separate of fields.
1096 ArtField* field = &cur_fields->At(i);
1097 auto it2 = native_object_relocations_.find(field);
1098 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
1099 << " already assigned " << PrettyField(field) << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001100 DCHECK(!IsInBootImage(field));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001101 native_object_relocations_.emplace(field,
1102 NativeObjectRelocation {oat_file, offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001103 offset += sizeof(ArtField);
1104 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001105 }
1106 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001107 // Visit and assign offsets for methods.
Alex Lighte64300b2015-12-15 15:02:47 -08001108 size_t num_methods = as_klass->NumMethods();
1109 if (num_methods != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001110 bool any_dirty = false;
Alex Lighte64300b2015-12-15 15:02:47 -08001111 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1112 if (WillMethodBeDirty(&m)) {
1113 any_dirty = true;
1114 break;
1115 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001116 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001117 NativeObjectRelocationType type = any_dirty
1118 ? kNativeObjectRelocationTypeArtMethodDirty
1119 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001120 Bin bin_type = BinTypeForNativeRelocationType(type);
1121 // Forward the entire array at once, but header first.
Alex Lighte64300b2015-12-15 15:02:47 -08001122 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1123 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01001124 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1125 method_size,
1126 method_alignment);
Alex Lighte64300b2015-12-15 15:02:47 -08001127 LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001128 auto it = native_object_relocations_.find(array);
Alex Lighte64300b2015-12-15 15:02:47 -08001129 CHECK(it == native_object_relocations_.end())
1130 << "Method array " << array << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001131 size_t& offset = image_info.bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001132 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001133 native_object_relocations_.emplace(array,
1134 NativeObjectRelocation {
1135 oat_file,
1136 offset,
1137 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty
1138 : kNativeObjectRelocationTypeArtMethodArrayClean });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001139 offset += header_size;
Alex Lighte64300b2015-12-15 15:02:47 -08001140 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001141 AssignMethodOffset(&m, type, oat_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001142 }
Alex Lighte64300b2015-12-15 15:02:47 -08001143 (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001144 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001145 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001146 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001147 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001148 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001149 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001150 mirror::Object* value = obj_array->Get(i);
1151 if (value != nullptr) {
1152 WalkFieldsInOrder(value);
1153 }
1154 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001155 } else if (h_obj->IsClassLoader()) {
1156 // Register the class loader if it has a class table.
1157 // The fake boot class loader should not get registered and we should end up with only one
1158 // class loader.
1159 mirror::ClassLoader* class_loader = h_obj->AsClassLoader();
1160 if (class_loader->GetClassTable() != nullptr) {
1161 class_loaders_.insert(class_loader);
1162 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001163 }
1164 }
1165}
1166
Jeff Haodcdc85b2015-12-04 14:06:18 -08001167void ImageWriter::AssignMethodOffset(ArtMethod* method,
1168 NativeObjectRelocationType type,
1169 const char* oat_filename) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001170 DCHECK(!IsInBootImage(method));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001171 auto it = native_object_relocations_.find(method);
1172 CHECK(it == native_object_relocations_.end()) << "Method " << method << " already assigned "
Mathieu Chartiere401d142015-04-22 13:56:20 -07001173 << PrettyMethod(method);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001174 ImageInfo& image_info = GetImageInfo(oat_filename);
1175 size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
1176 native_object_relocations_.emplace(method, NativeObjectRelocation { oat_filename, offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001177 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001178}
1179
Mathieu Chartier590fee92013-09-13 13:46:47 -07001180void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
1181 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1182 DCHECK(writer != nullptr);
1183 writer->WalkFieldsInOrder(obj);
1184}
1185
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001186void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
1187 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1188 DCHECK(writer != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001189 if (!writer->IsInBootImage(obj)) {
1190 writer->UnbinObjectsIntoOffset(obj);
1191 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001192}
1193
1194void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001195 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001196 CHECK(obj != nullptr);
1197
1198 // We know the bin slot, and the total bin sizes for all objects by now,
1199 // so calculate the object's final image offset.
1200
1201 DCHECK(IsImageBinSlotAssigned(obj));
1202 BinSlot bin_slot = GetImageBinSlot(obj);
1203 // Change the lockword from a bin slot into an offset
1204 AssignImageOffset(obj, bin_slot);
1205}
1206
Vladimir Markof4da6752014-08-01 19:04:18 +01001207void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001208 Thread* const self = Thread::Current();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001209 StackHandleScopeCollection handles(self);
1210 std::vector<Handle<ObjectArray<Object>>> image_roots;
1211 for (const char* oat_filename : oat_filenames_) {
1212 std::string image_filename = oat_filename;
1213 image_roots.push_back(handles.NewHandle(CreateImageRoots(image_filename.c_str())));
1214 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001215
Mathieu Chartiere401d142015-04-22 13:56:20 -07001216 auto* runtime = Runtime::Current();
1217 auto* heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001218
Mathieu Chartier31e89252013-08-28 11:29:12 -07001219 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001220 // know where image_roots is going to end up
Jeff Haodcdc85b2015-12-04 14:06:18 -08001221 image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001222
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001223 // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
1224 heap->VisitObjects(WalkFieldsCallback, this);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001225 // Write the image runtime methods.
1226 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1227 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1228 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
1229 image_methods_[ImageHeader::kCalleeSaveMethod] = runtime->GetCalleeSaveMethod(Runtime::kSaveAll);
1230 image_methods_[ImageHeader::kRefsOnlySaveMethod] =
1231 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly);
1232 image_methods_[ImageHeader::kRefsAndArgsSaveMethod] =
1233 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001234
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001235 // Add room for fake length prefixed array for holding the image methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001236 const auto image_method_type = kNativeObjectRelocationTypeArtMethodArrayClean;
1237 auto it = native_object_relocations_.find(&image_method_array_);
1238 CHECK(it == native_object_relocations_.end());
Jeff Haodcdc85b2015-12-04 14:06:18 -08001239 ImageInfo& default_image_info = GetImageInfo(default_oat_filename_);
1240 size_t& offset =
1241 default_image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(image_method_type)];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001242 if (!compile_app_image_) {
1243 native_object_relocations_.emplace(&image_method_array_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001244 NativeObjectRelocation { default_oat_filename_, offset, image_method_type });
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001245 }
Vladimir Marko14632852015-08-17 12:07:23 +01001246 size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001247 const size_t array_size = LengthPrefixedArray<ArtMethod>::ComputeSize(
Vladimir Marko14632852015-08-17 12:07:23 +01001248 0, ArtMethod::Size(target_ptr_size_), method_alignment);
Vladimir Markocf36d492015-08-12 19:27:26 +01001249 CHECK_ALIGNED_PARAM(array_size, method_alignment);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001250 offset += array_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001251 for (auto* m : image_methods_) {
1252 CHECK(m != nullptr);
1253 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001254 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1255 if (!IsInBootImage(m)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001256 AssignMethodOffset(m, kNativeObjectRelocationTypeArtMethodClean, default_oat_filename_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001257 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001258 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001259 // Calculate size of the dex cache arrays slot and prepare offsets.
1260 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001261
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001262 // Calculate the sizes of the intern tables and class tables.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001263 for (const char* oat_filename : oat_filenames_) {
1264 ImageInfo& image_info = GetImageInfo(oat_filename);
1265 // Calculate how big the intern table will be after being serialized.
1266 InternTable* const intern_table = image_info.intern_table_.get();
1267 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
1268 image_info.intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001269 // Calculate the size of the class table.
1270 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
1271 image_info.class_table_bytes_ += image_info.class_table_->WriteToMemory(nullptr);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001272 }
1273
Vladimir Markocf36d492015-08-12 19:27:26 +01001274 // Calculate bin slot offsets.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001275 for (const char* oat_filename : oat_filenames_) {
1276 ImageInfo& image_info = GetImageInfo(oat_filename);
1277 size_t bin_offset = image_objects_offset_begin_;
1278 for (size_t i = 0; i != kBinSize; ++i) {
1279 image_info.bin_slot_offsets_[i] = bin_offset;
1280 bin_offset += image_info.bin_slot_sizes_[i];
1281 if (i == kBinArtField) {
1282 static_assert(kBinArtField + 1 == kBinArtMethodClean, "Methods follow fields.");
1283 static_assert(alignof(ArtField) == 4u, "ArtField alignment is 4.");
1284 DCHECK_ALIGNED(bin_offset, 4u);
1285 DCHECK(method_alignment == 4u || method_alignment == 8u);
1286 bin_offset = RoundUp(bin_offset, method_alignment);
1287 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001288 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001289 // NOTE: There may be additional padding between the bin slots and the intern table.
1290 DCHECK_EQ(image_info.image_end_,
1291 GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_);
Vladimir Marko20f85592015-03-19 10:07:02 +00001292 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001293
Jeff Haodcdc85b2015-12-04 14:06:18 -08001294 // Calculate image offsets.
1295 size_t image_offset = 0;
1296 for (const char* oat_filename : oat_filenames_) {
1297 ImageInfo& image_info = GetImageInfo(oat_filename);
1298 image_info.image_begin_ = global_image_begin_ + image_offset;
1299 image_info.image_offset_ = image_offset;
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001300 ImageSection unused_sections[ImageHeader::kSectionCount];
1301 image_info.image_size_ = RoundUp(
1302 image_info.CreateImageSections(target_ptr_size_, unused_sections),
1303 kPageSize);
1304 // There should be no gaps until the next image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001305 image_offset += image_info.image_size_;
1306 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001307
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001308 // Transform each object's bin slot into an offset which will be used to do the final copy.
1309 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001310
Jeff Haodcdc85b2015-12-04 14:06:18 -08001311 // DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001312
Jeff Haodcdc85b2015-12-04 14:06:18 -08001313 size_t i = 0;
1314 for (const char* oat_filename : oat_filenames_) {
1315 ImageInfo& image_info = GetImageInfo(oat_filename);
1316 image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
1317 i++;
1318 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001319
Mathieu Chartiere401d142015-04-22 13:56:20 -07001320 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001321 for (auto& pair : native_object_relocations_) {
1322 NativeObjectRelocation& relocation = pair.second;
1323 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001324 ImageInfo& image_info = GetImageInfo(relocation.oat_filename);
1325 relocation.offset += image_info.bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001326 }
1327
Jeff Haodcdc85b2015-12-04 14:06:18 -08001328 // Note that image_info.image_end_ is left at end of used mirror object section.
Vladimir Markof4da6752014-08-01 19:04:18 +01001329}
1330
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001331size_t ImageWriter::ImageInfo::CreateImageSections(size_t target_ptr_size,
1332 ImageSection* out_sections) const {
1333 DCHECK(out_sections != nullptr);
1334 // Objects section
1335 auto* objects_section = &out_sections[ImageHeader::kSectionObjects];
1336 *objects_section = ImageSection(0u, image_end_);
1337 size_t cur_pos = objects_section->End();
1338 // Add field section.
1339 auto* field_section = &out_sections[ImageHeader::kSectionArtFields];
1340 *field_section = ImageSection(cur_pos, bin_slot_sizes_[kBinArtField]);
1341 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
1342 cur_pos = field_section->End();
1343 // Round up to the alignment the required by the method section.
1344 cur_pos = RoundUp(cur_pos, ArtMethod::Alignment(target_ptr_size));
1345 // Add method section.
1346 auto* methods_section = &out_sections[ImageHeader::kSectionArtMethods];
1347 *methods_section = ImageSection(cur_pos,
1348 bin_slot_sizes_[kBinArtMethodClean] +
1349 bin_slot_sizes_[kBinArtMethodDirty]);
1350 CHECK_EQ(bin_slot_offsets_[kBinArtMethodClean], methods_section->Offset());
1351 cur_pos = methods_section->End();
1352 // Add dex cache arrays section.
1353 auto* dex_cache_arrays_section = &out_sections[ImageHeader::kSectionDexCacheArrays];
1354 *dex_cache_arrays_section = ImageSection(cur_pos, bin_slot_sizes_[kBinDexCacheArray]);
1355 CHECK_EQ(bin_slot_offsets_[kBinDexCacheArray], dex_cache_arrays_section->Offset());
1356 cur_pos = dex_cache_arrays_section->End();
1357 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
1358 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1359 // Calculate the size of the interned strings.
1360 auto* interned_strings_section = &out_sections[ImageHeader::kSectionInternedStrings];
1361 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1362 cur_pos = interned_strings_section->End();
1363 // Round up to the alignment the class table expects. See HashSet::WriteToMemory.
1364 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1365 // Calculate the size of the class table section.
1366 auto* class_table_section = &out_sections[ImageHeader::kSectionClassTable];
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001367 *class_table_section = ImageSection(cur_pos, class_table_bytes_);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001368 cur_pos = class_table_section->End();
1369 // Image end goes right before the start of the image bitmap.
1370 return cur_pos;
1371}
1372
Vladimir Markof4da6752014-08-01 19:04:18 +01001373void ImageWriter::CreateHeader(size_t oat_loaded_size, size_t oat_data_offset) {
1374 CHECK_NE(0U, oat_loaded_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001375 const char* oat_filename = oat_file_->GetLocation().c_str();
1376 ImageInfo& image_info = GetImageInfo(oat_filename);
1377 const uint8_t* oat_file_begin = GetOatFileBegin(oat_filename);
Ian Rogers13735952014-10-08 12:43:28 -07001378 const uint8_t* oat_file_end = oat_file_begin + oat_loaded_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001379 image_info.oat_data_begin_ = const_cast<uint8_t*>(oat_file_begin) + oat_data_offset;
1380 const uint8_t* oat_data_end = image_info.oat_data_begin_ + oat_file_->Size();
1381 image_info.oat_size_ = oat_file_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001382
1383 // Create the image sections.
1384 ImageSection sections[ImageHeader::kSectionCount];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001385 const size_t image_end = image_info.CreateImageSections(target_ptr_size_, sections);
1386
Mathieu Chartiere401d142015-04-22 13:56:20 -07001387 // Finally bitmap section.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001388 const size_t bitmap_bytes = image_info.image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001389 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001390 *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001391 if (VLOG_IS_ON(compiler)) {
1392 LOG(INFO) << "Creating header for " << oat_filename;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001393 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001394 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001395 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1396 ++idx;
1397 }
1398 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001399 LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
1400 LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
1401 << " Image offset=" << image_info.image_offset_ << std::dec;
1402 LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
1403 << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
1404 << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
1405 << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001406 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001407
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001408 // Create the header, leave 0 for data size since we will fill this in as we are writing the
1409 // image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001410 new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_),
1411 image_end,
1412 sections,
1413 image_info.image_roots_address_,
1414 oat_file_->GetOatHeader().GetChecksum(),
1415 PointerToLowMemUInt32(oat_file_begin),
1416 PointerToLowMemUInt32(image_info.oat_data_begin_),
1417 PointerToLowMemUInt32(oat_data_end),
1418 PointerToLowMemUInt32(oat_file_end),
1419 target_ptr_size_,
1420 compile_pic_,
1421 image_storage_mode_,
1422 /*data_size*/0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001423}
1424
1425ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001426 auto it = native_object_relocations_.find(method);
1427 CHECK(it != native_object_relocations_.end()) << PrettyMethod(method) << " @ " << method;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001428 const char* oat_filename = GetOatFilename(method->GetDexCache());
1429 ImageInfo& image_info = GetImageInfo(oat_filename);
1430 CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects";
1431 return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001432}
1433
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001434class FixupRootVisitor : public RootVisitor {
1435 public:
1436 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1437 }
1438
1439 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001440 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001441 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001442 *roots[i] = image_writer_->GetImageAddress(*roots[i]);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001443 }
1444 }
1445
1446 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1447 const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001448 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001449 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001450 roots[i]->Assign(image_writer_->GetImageAddress(roots[i]->AsMirrorPtr()));
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001451 }
1452 }
1453
1454 private:
1455 ImageWriter* const image_writer_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001456};
1457
Mathieu Chartierc7853442015-03-27 14:35:38 -07001458void ImageWriter::CopyAndFixupNativeData() {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001459 const char* oat_filename = oat_file_->GetLocation().c_str();
1460 ImageInfo& image_info = GetImageInfo(oat_filename);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001461 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001462 for (auto& pair : native_object_relocations_) {
1463 NativeObjectRelocation& relocation = pair.second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001464 // Only work with fields and methods that are in the current oat file.
1465 if (strcmp(relocation.oat_filename, oat_filename) != 0) {
1466 continue;
1467 }
1468 auto* dest = image_info.image_->Begin() + relocation.offset;
1469 DCHECK_GE(dest, image_info.image_->Begin() + image_info.image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001470 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001471 switch (relocation.type) {
1472 case kNativeObjectRelocationTypeArtField: {
1473 memcpy(dest, pair.first, sizeof(ArtField));
1474 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
1475 GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass()));
1476 break;
1477 }
1478 case kNativeObjectRelocationTypeArtMethodClean:
1479 case kNativeObjectRelocationTypeArtMethodDirty: {
1480 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001481 reinterpret_cast<ArtMethod*>(dest),
1482 image_info);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001483 break;
1484 }
1485 // For arrays, copy just the header since the elements will get copied by their corresponding
1486 // relocations.
1487 case kNativeObjectRelocationTypeArtFieldArray: {
1488 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1489 break;
1490 }
1491 case kNativeObjectRelocationTypeArtMethodArrayClean:
1492 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markocf36d492015-08-12 19:27:26 +01001493 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(
1494 0,
Vladimir Marko14632852015-08-17 12:07:23 +01001495 ArtMethod::Size(target_ptr_size_),
1496 ArtMethod::Alignment(target_ptr_size_)));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001497 break;
Vladimir Marko05792b92015-08-03 11:56:49 +01001498 case kNativeObjectRelocationTypeDexCacheArray:
1499 // Nothing to copy here, everything is done in FixupDexCache().
1500 break;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001501 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001502 }
1503 }
1504 // Fixup the image method roots.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001505 auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001506 const ImageSection& methods_section = image_header->GetMethodsSection();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001507 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001508 ArtMethod* method = image_methods_[i];
1509 CHECK(method != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001510 // Only place runtime methods in the image of the default oat file.
1511 if (method->IsRuntimeMethod() && strcmp(default_oat_filename_, oat_filename) != 0) {
1512 continue;
1513 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001514 if (!IsInBootImage(method)) {
1515 auto it = native_object_relocations_.find(method);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001516 CHECK(it != native_object_relocations_.end()) << "No forwarding for " << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001517 NativeObjectRelocation& relocation = it->second;
1518 CHECK(methods_section.Contains(relocation.offset)) << relocation.offset << " not in "
1519 << methods_section;
1520 CHECK(relocation.IsArtMethodRelocation()) << relocation.type;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001521 method = reinterpret_cast<ArtMethod*>(global_image_begin_ + it->second.offset);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001522 }
1523 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001524 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001525 FixupRootVisitor root_visitor(this);
1526
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001527 // Write the intern table into the image.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001528 if (image_info.intern_table_bytes_ > 0) {
1529 const ImageSection& intern_table_section = image_header->GetImageSection(
1530 ImageHeader::kSectionInternedStrings);
1531 InternTable* const intern_table = image_info.intern_table_.get();
1532 uint8_t* const intern_table_memory_ptr =
1533 image_info.image_->Begin() + intern_table_section.Offset();
1534 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
1535 CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
1536 // Fixup the pointers in the newly written intern table to contain image addresses.
1537 InternTable temp_intern_table;
1538 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1539 // the VisitRoots() will update the memory directly rather than the copies.
1540 // This also relies on visit roots not doing any verification which could fail after we update
1541 // the roots to be the image addresses.
1542 temp_intern_table.AddTableFromMemory(intern_table_memory_ptr);
1543 CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
1544 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
1545 }
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001546 // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
1547 // class loaders. Writing multiple class tables into the image is currently unsupported.
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001548 if (image_info.class_table_bytes_ > 0u) {
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001549 const ImageSection& class_table_section = image_header->GetImageSection(
1550 ImageHeader::kSectionClassTable);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001551 uint8_t* const class_table_memory_ptr =
1552 image_info.image_->Begin() + class_table_section.Offset();
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001553 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001554
1555 ClassTable* table = image_info.class_table_.get();
1556 CHECK(table != nullptr);
1557 const size_t class_table_bytes = table->WriteToMemory(class_table_memory_ptr);
1558 CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
1559 // Fixup the pointers in the newly written class table to contain image addresses. See
1560 // above comment for intern tables.
1561 ClassTable temp_class_table;
1562 temp_class_table.ReadFromMemory(class_table_memory_ptr);
1563 CHECK_EQ(temp_class_table.NumZygoteClasses(), table->NumNonZygoteClasses() +
1564 table->NumZygoteClasses());
1565 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(&root_visitor,
1566 RootInfo(kRootUnknown));
1567 temp_class_table.VisitRoots(buffered_visitor);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001568 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001569}
1570
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001571void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001572 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001573 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1574 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001575 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001576 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07001577 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
1578 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001579 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001580 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001581}
1582
Mathieu Chartier590fee92013-09-13 13:46:47 -07001583void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001584 DCHECK(obj != nullptr);
1585 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001586 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1587}
1588
Mathieu Chartiere401d142015-04-22 13:56:20 -07001589void ImageWriter::FixupPointerArray(mirror::Object* dst, mirror::PointerArray* arr,
1590 mirror::Class* klass, Bin array_type) {
1591 CHECK(klass->IsArrayClass());
1592 CHECK(arr->IsIntArray() || arr->IsLongArray()) << PrettyClass(klass) << " " << arr;
1593 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001594 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001595 dst->SetClass(GetImageAddress(arr->GetClass()));
1596 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001597 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001598 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
1599 if (elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001600 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01001601 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001602 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001603 auto* method = reinterpret_cast<ArtMethod*>(elem);
1604 LOG(FATAL) << "No relocation entry for ArtMethod " << PrettyMethod(method) << " @ "
1605 << method << " idx=" << i << "/" << num_elements << " with declaring class "
1606 << PrettyClass(method->GetDeclaringClass());
1607 } else {
1608 CHECK_EQ(array_type, kBinArtField);
1609 auto* field = reinterpret_cast<ArtField*>(elem);
1610 LOG(FATAL) << "No relocation entry for ArtField " << PrettyField(field) << " @ "
1611 << field << " idx=" << i << "/" << num_elements << " with declaring class "
1612 << PrettyClass(field->GetDeclaringClass());
1613 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001614 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001615 } else {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001616 ImageInfo& image_info = GetImageInfo(it->second.oat_filename);
1617 elem = image_info.image_begin_ + it->second.offset;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001618 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001619 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001620 dest_array->SetElementPtrSize<false, true>(i, elem, target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001621 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001622}
1623
1624void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001625 if (IsInBootImage(obj)) {
1626 return;
1627 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001628 size_t offset = GetImageOffset(obj);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001629 const char* oat_filename = GetOatFilename(obj);
1630 ImageInfo& image_info = GetImageInfo(oat_filename);
1631 auto* dst = reinterpret_cast<Object*>(image_info.image_->Begin() + offset);
1632 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001633 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001634
Jeff Haodcdc85b2015-12-04 14:06:18 -08001635 image_info.image_bitmap_->Set(dst); // Mark the obj as live.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001636
1637 const size_t n = obj->SizeOf();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001638 DCHECK_LE(offset + n, image_info.image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001639 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001640
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001641 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1642 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001643 const auto it = saved_hashcode_map_.find(obj);
1644 dst->SetLockWord(it != saved_hashcode_map_.end() ?
1645 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001646 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001647}
1648
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001649// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001650class FixupVisitor {
1651 public:
1652 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1653 }
1654
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001655 // Ignore class roots since we don't have a way to map them to the destination. These are handled
1656 // with other logic.
1657 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1658 const {}
1659 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1660
1661
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001662 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001663 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -07001664 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001665 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1666 // image.
1667 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001668 offset,
1669 image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001670 }
1671
1672 // java.lang.ref.Reference visitor.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001673 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001674 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001675 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001676 mirror::Reference::ReferentOffset(),
1677 image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001678 }
1679
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001680 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001681 ImageWriter* const image_writer_;
1682 mirror::Object* const copy_;
1683};
1684
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001685class FixupClassVisitor FINAL : public FixupVisitor {
1686 public:
1687 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1688 }
1689
Mathieu Chartierc7853442015-03-27 14:35:38 -07001690 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001691 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001692 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001693 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001694 }
1695
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001696 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1697 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001698 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001699 LOG(FATAL) << "Reference not expected here.";
1700 }
1701};
1702
Vladimir Marko05792b92015-08-03 11:56:49 +01001703uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
1704 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001705 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001706 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001707 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1708 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001709 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01001710 return relocation.offset;
1711}
1712
1713template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001714T* ImageWriter::NativeLocationInImage(T* obj, const char* oat_filename) {
1715 if (obj == nullptr || IsInBootImage(obj)) {
1716 return obj;
1717 } else {
1718 ImageInfo& image_info = GetImageInfo(oat_filename);
1719 return reinterpret_cast<T*>(image_info.image_begin_ + NativeOffsetInImage(obj));
1720 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001721}
1722
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001723template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001724T* ImageWriter::NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) {
1725 if (obj == nullptr || IsInBootImage(obj)) {
1726 return obj;
1727 } else {
1728 const char* oat_filename = GetOatFilenameForDexCache(dex_cache);
1729 ImageInfo& image_info = GetImageInfo(oat_filename);
1730 return reinterpret_cast<T*>(image_info.image_->Begin() + NativeOffsetInImage(obj));
1731 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001732}
1733
1734class NativeLocationVisitor {
1735 public:
Jeff Haodcdc85b2015-12-04 14:06:18 -08001736 explicit NativeLocationVisitor(ImageWriter* image_writer, const char* oat_filename)
1737 : image_writer_(image_writer), oat_filename_(oat_filename) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001738
1739 template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001740 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
1741 return image_writer_->NativeLocationInImage(ptr, oat_filename_);
1742 }
1743
1744 ArtMethod* operator()(ArtMethod* method) const SHARED_REQUIRES(Locks::mutator_lock_) {
1745 const char* oat_filename = method->IsRuntimeMethod() ? image_writer_->GetDefaultOatFilename() :
1746 image_writer_->GetOatFilenameForDexCache(method->GetDexCache());
1747 return image_writer_->NativeLocationInImage(method, oat_filename);
1748 }
1749
1750 ArtField* operator()(ArtField* field) const SHARED_REQUIRES(Locks::mutator_lock_) {
1751 const char* oat_filename = image_writer_->GetOatFilenameForDexCache(field->GetDexCache());
1752 return image_writer_->NativeLocationInImage(field, oat_filename);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001753 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001754
1755 private:
1756 ImageWriter* const image_writer_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001757 const char* oat_filename_;
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001758};
1759
1760void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001761 const char* oat_filename = GetOatFilename(orig);
1762 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this, oat_filename));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001763 FixupClassVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001764 static_cast<mirror::Object*>(orig)->VisitReferences(visitor, visitor);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001765}
1766
Ian Rogersef7d42f2014-01-06 12:55:46 -08001767void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001768 DCHECK(orig != nullptr);
1769 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07001770 if (kUseBakerOrBrooksReadBarrier) {
1771 orig->AssertReadBarrierPointer();
1772 if (kUseBrooksReadBarrier) {
1773 // Note the address 'copy' isn't the same as the image address of 'orig'.
1774 copy->SetReadBarrierPointer(GetImageAddress(orig));
1775 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
1776 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08001777 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001778 auto* klass = orig->GetClass();
1779 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001780 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07001781 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
1782 if (it != pointer_arrays_.end()) {
1783 // Should only need to fixup every pointer array exactly once.
1784 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
1785 pointer_arrays_.erase(it);
1786 return;
1787 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001788 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001789 if (orig->IsClass()) {
1790 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001791 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001792 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
1793 // Need to go update the ArtMethod.
1794 auto* dest = down_cast<mirror::AbstractMethod*>(copy);
1795 auto* src = down_cast<mirror::AbstractMethod*>(orig);
1796 ArtMethod* src_method = src->GetArtMethod();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001797 auto it = native_object_relocations_.find(src_method);
1798 CHECK(it != native_object_relocations_.end())
1799 << "Missing relocation for AbstractMethod.artMethod " << PrettyMethod(src_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001800 dest->SetArtMethod(
Jeff Haodcdc85b2015-12-04 14:06:18 -08001801 reinterpret_cast<ArtMethod*>(global_image_begin_ + it->second.offset));
Vladimir Marko05792b92015-08-03 11:56:49 +01001802 } else if (!klass->IsArrayClass()) {
1803 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1804 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
1805 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001806 } else if (klass->IsClassLoaderClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001807 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
1808 // ClassLoader.
1809 down_cast<mirror::ClassLoader*>(copy)->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07001810 // Also set allocator to null to be safe. The allocator is created when we create the class
1811 // table. We also never expect to unload things in the image since they are held live as
1812 // roots.
1813 down_cast<mirror::ClassLoader*>(copy)->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01001814 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001815 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001816 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001817 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001818 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001819}
1820
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001821
1822class ImageAddressVisitor {
1823 public:
1824 explicit ImageAddressVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
1825
1826 template <typename T>
1827 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
1828 return image_writer_->GetImageAddress(ptr);
1829 }
1830
1831 private:
1832 ImageWriter* const image_writer_;
1833};
1834
1835
Vladimir Marko05792b92015-08-03 11:56:49 +01001836void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
1837 mirror::DexCache* copy_dex_cache) {
1838 // Though the DexCache array fields are usually treated as native pointers, we set the full
1839 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
1840 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
1841 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
Jeff Haodcdc85b2015-12-04 14:06:18 -08001842 const char* oat_filename = GetOatFilenameForDexCache(orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01001843 GcRoot<mirror::String>* orig_strings = orig_dex_cache->GetStrings();
1844 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001845 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001846 NativeLocationInImage(orig_strings, oat_filename),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001847 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001848 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings, orig_dex_cache),
1849 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001850 }
1851 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
1852 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001853 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001854 NativeLocationInImage(orig_types, oat_filename),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001855 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001856 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types, orig_dex_cache),
1857 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001858 }
1859 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
1860 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001861 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001862 NativeLocationInImage(orig_methods, oat_filename),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001863 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001864 ArtMethod** copy_methods = NativeCopyLocation(orig_methods, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01001865 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
1866 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001867 const char* method_oat_filename;
1868 if (orig == nullptr || orig->IsRuntimeMethod()) {
1869 method_oat_filename = default_oat_filename_;
1870 } else {
1871 method_oat_filename = GetOatFilenameForDexCache(orig->GetDexCache());
1872 }
1873 ArtMethod* copy = NativeLocationInImage(orig, method_oat_filename);
Vladimir Marko05792b92015-08-03 11:56:49 +01001874 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
1875 }
1876 }
1877 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
1878 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001879 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001880 NativeLocationInImage(orig_fields, oat_filename),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001881 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001882 ArtField** copy_fields = NativeCopyLocation(orig_fields, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01001883 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
1884 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, i, target_ptr_size_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001885 const char* field_oat_filename =
1886 orig == nullptr ? default_oat_filename_ : GetOatFilenameForDexCache(orig->GetDexCache());
1887 ArtField* copy = NativeLocationInImage(orig, field_oat_filename);
Vladimir Marko05792b92015-08-03 11:56:49 +01001888 mirror::DexCache::SetElementPtrSize(copy_fields, i, copy, target_ptr_size_);
1889 }
1890 }
1891}
1892
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001893const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
1894 DCHECK_LT(type, kOatAddressCount);
1895 // If we are compiling an app image, we need to use the stubs of the boot image.
1896 if (compile_app_image_) {
1897 // Use the current image pointers.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001898 std::vector<gc::space::ImageSpace*> image_spaces =
1899 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1900 DCHECK(!image_spaces.empty());
1901 const OatFile* oat_file = image_spaces[0]->GetOatFile();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001902 CHECK(oat_file != nullptr);
1903 const OatHeader& header = oat_file->GetOatHeader();
1904 switch (type) {
1905 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
1906 case kOatAddressQuickGenericJNITrampoline:
1907 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
1908 case kOatAddressInterpreterToInterpreterBridge:
1909 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
1910 case kOatAddressInterpreterToCompiledCodeBridge:
1911 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
1912 case kOatAddressJNIDlsymLookup:
1913 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
1914 case kOatAddressQuickIMTConflictTrampoline:
1915 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
1916 case kOatAddressQuickResolutionTrampoline:
1917 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
1918 case kOatAddressQuickToInterpreterBridge:
1919 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
1920 default:
1921 UNREACHABLE();
1922 }
1923 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001924 const ImageInfo& primary_image_info = GetImageInfo(0);
1925 return GetOatAddressForOffset(primary_image_info.oat_address_offsets_[type], primary_image_info);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001926}
1927
Jeff Haodcdc85b2015-12-04 14:06:18 -08001928const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method,
1929 const ImageInfo& image_info,
1930 bool* quick_is_interpreted) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001931 DCHECK(!method->IsResolutionMethod()) << PrettyMethod(method);
1932 DCHECK(!method->IsImtConflictMethod()) << PrettyMethod(method);
1933 DCHECK(!method->IsImtUnimplementedMethod()) << PrettyMethod(method);
Alex Light9139e002015-10-09 15:59:48 -07001934 DCHECK(method->IsInvokable()) << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001935 DCHECK(!IsInBootImage(method)) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001936
1937 // Use original code if it exists. Otherwise, set the code pointer to the resolution
1938 // trampoline.
1939
1940 // Quick entrypoint:
Jeff Haoc7d11882015-02-03 15:08:39 -08001941 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(
1942 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001943 const uint8_t* quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001944 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001945 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
1946 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001947 // We have code for a non-static or initialized method, just use the code.
1948 } else if (quick_code == nullptr && method->IsNative() &&
1949 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
1950 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001951 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001952 } else if (quick_code == nullptr && !method->IsNative()) {
1953 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001954 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001955 *quick_is_interpreted = true;
1956 } else {
1957 CHECK(!method->GetDeclaringClass()->IsInitialized());
1958 // We have code for a static method, but need to go through the resolution stub for class
1959 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001960 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
1961 }
1962 if (!IsInBootOatFile(quick_code)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001963 // DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001964 }
1965 return quick_code;
1966}
1967
Jeff Haodcdc85b2015-12-04 14:06:18 -08001968void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
1969 ArtMethod* copy,
1970 const ImageInfo& image_info) {
Vladimir Marko14632852015-08-17 12:07:23 +01001971 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001972
1973 copy->SetDeclaringClass(GetImageAddress(orig->GetDeclaringClassUnchecked()));
Vladimir Marko05792b92015-08-03 11:56:49 +01001974
Jeff Haodcdc85b2015-12-04 14:06:18 -08001975 const char* oat_filename;
1976 if (orig->IsRuntimeMethod()) {
1977 oat_filename = default_oat_filename_;
1978 } else {
1979 auto it = dex_file_oat_filename_map_.find(orig->GetDexFile());
1980 DCHECK(it != dex_file_oat_filename_map_.end()) << orig->GetDexFile()->GetLocation();
1981 oat_filename = it->second;
1982 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001983 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001984 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods, oat_filename),
1985 target_ptr_size_);
Vladimir Marko05792b92015-08-03 11:56:49 +01001986 GcRoot<mirror::Class>* orig_resolved_types = orig->GetDexCacheResolvedTypes(target_ptr_size_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001987 copy->SetDexCacheResolvedTypes(NativeLocationInImage(orig_resolved_types, oat_filename),
1988 target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001989
Ian Rogers848871b2013-08-05 10:56:33 -07001990 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
1991 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07001992
Ian Rogers848871b2013-08-05 10:56:33 -07001993 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001994 Runtime* runtime = Runtime::Current();
1995 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001996 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001997 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07001998 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
1999 orig == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002000 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002001 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002002 } else if (UNLIKELY(orig->IsRuntimeMethod())) {
2003 bool found_one = false;
2004 for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) {
2005 auto idx = static_cast<Runtime::CalleeSaveType>(i);
2006 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
2007 found_one = true;
2008 break;
2009 }
2010 }
2011 CHECK(found_one) << "Expected to find callee save method but got " << PrettyMethod(orig);
2012 CHECK(copy->IsRuntimeMethod());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002013 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002014 // We assume all methods have code. If they don't currently then we set them to the use the
2015 // resolution trampoline. Abstract methods never have code and so we need to make sure their
2016 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07002017 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002018 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002019 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002020 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002021 bool quick_is_interpreted;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002022 const uint8_t* quick_code = GetQuickCode(orig, image_info, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002023 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02002024
Sebastien Hertze1d07812014-05-21 15:44:09 +02002025 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07002026 if (orig->IsNative()) {
2027 // The native method's pointer is set to a stub to lookup via dlsym.
2028 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002029 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002030 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002031 }
2032 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002033 }
2034}
2035
Alex Lighta59dd802014-07-02 16:28:08 -07002036static OatHeader* GetOatHeaderFromElf(ElfFile* elf) {
Tong Shen62d1ca32014-09-03 17:24:56 -07002037 uint64_t data_sec_offset;
2038 bool has_data_sec = elf->GetSectionOffsetAndSize(".rodata", &data_sec_offset, nullptr);
2039 if (!has_data_sec) {
Alex Lighta59dd802014-07-02 16:28:08 -07002040 return nullptr;
2041 }
Tong Shen62d1ca32014-09-03 17:24:56 -07002042 return reinterpret_cast<OatHeader*>(elf->Begin() + data_sec_offset);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08002043}
2044
Vladimir Markof4da6752014-08-01 19:04:18 +01002045void ImageWriter::SetOatChecksumFromElfFile(File* elf_file) {
Alex Lighta59dd802014-07-02 16:28:08 -07002046 std::string error_msg;
Mathieu Chartiera808bac2015-11-05 16:33:15 -08002047 std::unique_ptr<ElfFile> elf(ElfFile::Open(elf_file,
2048 PROT_READ | PROT_WRITE,
2049 MAP_SHARED,
2050 &error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -07002051 if (elf.get() == nullptr) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002052 LOG(FATAL) << "Unable open oat file: " << error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07002053 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002054 }
Alex Lighta59dd802014-07-02 16:28:08 -07002055 OatHeader* oat_header = GetOatHeaderFromElf(elf.get());
2056 CHECK(oat_header != nullptr);
2057 CHECK(oat_header->IsValid());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002058
Jeff Haodcdc85b2015-12-04 14:06:18 -08002059 ImageInfo& image_info = GetImageInfo(oat_file_->GetLocation().c_str());
2060 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Alex Lighta59dd802014-07-02 16:28:08 -07002061 image_header->SetOatChecksum(oat_header->GetChecksum());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002062}
2063
Jeff Haodcdc85b2015-12-04 14:06:18 -08002064size_t ImageWriter::GetBinSizeSum(ImageWriter::ImageInfo& image_info, ImageWriter::Bin up_to) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002065 DCHECK_LE(up_to, kBinSize);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002066 return std::accumulate(&image_info.bin_slot_sizes_[0],
2067 &image_info.bin_slot_sizes_[up_to],
2068 /*init*/0);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002069}
2070
2071ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
2072 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07002073 static_assert(kBinBits == 3, "wrong number of bin bits");
2074 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002075 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
2076
2077 DCHECK_LT(GetBin(), kBinSize);
2078 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
2079}
2080
2081ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
2082 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
2083 DCHECK_EQ(index, GetIndex());
2084}
2085
2086ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
2087 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
2088}
2089
2090uint32_t ImageWriter::BinSlot::GetIndex() const {
2091 return lockword_ & ~kBinMask;
2092}
2093
Jeff Haodcdc85b2015-12-04 14:06:18 -08002094uint8_t* ImageWriter::GetOatFileBegin(const char* oat_filename) const {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002095 uintptr_t last_image_end = 0;
2096 for (const char* oat_fn : oat_filenames_) {
2097 const ImageInfo& image_info = GetConstImageInfo(oat_fn);
2098 DCHECK(image_info.image_begin_ != nullptr);
2099 uintptr_t this_end = reinterpret_cast<uintptr_t>(image_info.image_begin_) +
2100 image_info.image_size_;
2101 last_image_end = std::max(this_end, last_image_end);
2102 }
2103 const ImageInfo& image_info = GetConstImageInfo(oat_filename);
2104 return reinterpret_cast<uint8_t*>(last_image_end) + image_info.oat_offset_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002105}
2106
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002107ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
2108 switch (type) {
2109 case kNativeObjectRelocationTypeArtField:
2110 case kNativeObjectRelocationTypeArtFieldArray:
2111 return kBinArtField;
2112 case kNativeObjectRelocationTypeArtMethodClean:
2113 case kNativeObjectRelocationTypeArtMethodArrayClean:
2114 return kBinArtMethodClean;
2115 case kNativeObjectRelocationTypeArtMethodDirty:
2116 case kNativeObjectRelocationTypeArtMethodArrayDirty:
2117 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01002118 case kNativeObjectRelocationTypeDexCacheArray:
2119 return kBinDexCacheArray;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002120 }
2121 UNREACHABLE();
2122}
2123
Jeff Haodcdc85b2015-12-04 14:06:18 -08002124const char* ImageWriter::GetOatFilename(mirror::Object* obj) const {
2125 if (compile_app_image_) {
2126 return default_oat_filename_;
2127 } else {
2128 return GetOatFilenameForDexCache(obj->IsDexCache() ? obj->AsDexCache() :
2129 obj->IsClass() ? obj->AsClass()->GetDexCache() : obj->GetClass()->GetDexCache());
2130 }
2131}
2132
2133const char* ImageWriter::GetOatFilenameForDexCache(mirror::DexCache* dex_cache) const {
2134 if (compile_app_image_ || dex_cache == nullptr) {
2135 return default_oat_filename_;
2136 } else {
2137 auto it = dex_file_oat_filename_map_.find(dex_cache->GetDexFile());
2138 DCHECK(it != dex_file_oat_filename_map_.end()) << dex_cache->GetDexFile()->GetLocation();
2139 return it->second;
2140 }
2141}
2142
2143ImageWriter::ImageInfo& ImageWriter::GetImageInfo(const char* oat_filename) {
2144 auto it = image_info_map_.find(oat_filename);
2145 DCHECK(it != image_info_map_.end());
2146 return it->second;
2147}
2148
2149const ImageWriter::ImageInfo& ImageWriter::GetConstImageInfo(const char* oat_filename) const {
2150 auto it = image_info_map_.find(oat_filename);
2151 DCHECK(it != image_info_map_.end());
2152 return it->second;
2153}
2154
2155const ImageWriter::ImageInfo& ImageWriter::GetImageInfo(size_t index) const {
2156 DCHECK_LT(index, oat_filenames_.size());
2157 return GetConstImageInfo(oat_filenames_[index]);
2158}
2159
2160void ImageWriter::UpdateOatFile(const char* oat_filename) {
2161 std::unique_ptr<File> oat_file(OS::OpenFileForReading(oat_filename));
2162 DCHECK(oat_file != nullptr);
2163 size_t oat_loaded_size = 0;
2164 size_t oat_data_offset = 0;
2165 ElfWriter::GetOatElfInformation(oat_file.get(), &oat_loaded_size, &oat_data_offset);
2166
2167 ImageInfo& cur_image_info = GetImageInfo(oat_filename);
2168
2169 // Update the oat_offset of the next image info.
2170 auto it = std::find(oat_filenames_.begin(), oat_filenames_.end(), oat_filename);
2171 DCHECK(it != oat_filenames_.end());
2172
2173 it++;
2174 if (it != oat_filenames_.end()) {
2175 // There is a following one.
2176 ImageInfo& next_image_info = GetImageInfo(*it);
2177 next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
2178 }
2179}
2180
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002181ImageWriter::ImageWriter(
2182 const CompilerDriver& compiler_driver,
2183 uintptr_t image_begin,
2184 bool compile_pic,
2185 bool compile_app_image,
2186 ImageHeader::StorageMode image_storage_mode,
2187 const std::vector<const char*> oat_filenames,
2188 const std::unordered_map<const DexFile*, const char*>& dex_file_oat_filename_map)
2189 : compiler_driver_(compiler_driver),
2190 global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
2191 image_objects_offset_begin_(0),
2192 oat_file_(nullptr),
2193 compile_pic_(compile_pic),
2194 compile_app_image_(compile_app_image),
2195 boot_image_space_(nullptr),
2196 target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())),
2197 image_method_array_(ImageHeader::kImageMethodsCount),
2198 dirty_methods_(0u),
2199 clean_methods_(0u),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002200 image_storage_mode_(image_storage_mode),
2201 dex_file_oat_filename_map_(dex_file_oat_filename_map),
2202 oat_filenames_(oat_filenames),
2203 default_oat_filename_(oat_filenames[0]) {
2204 CHECK_NE(image_begin, 0U);
2205 for (const char* oat_filename : oat_filenames) {
2206 image_info_map_.emplace(oat_filename, ImageInfo());
2207 }
2208 std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
2209}
2210
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002211ImageWriter::ImageInfo::ImageInfo()
2212 : intern_table_(new InternTable),
2213 class_table_(new ClassTable) {}
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002214
Brian Carlstrom7940e442013-07-12 13:46:57 -07002215} // namespace art