blob: 2985ca94225bebe20edc83dece9f243e6cd7ea9f [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 Chartier54d220e2015-07-30 16:20:06 -07001073 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1074 // Total array length including header.
1075 if (cur_fields != nullptr) {
1076 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
1077 // Forward the entire array at once.
1078 auto it = native_object_relocations_.find(cur_fields);
1079 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
1080 << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001081 size_t& offset = image_info.bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001082 DCHECK(!IsInBootImage(cur_fields));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001083 native_object_relocations_.emplace(cur_fields,
1084 NativeObjectRelocation {oat_file, offset, kNativeObjectRelocationTypeArtFieldArray });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001085 offset += header_size;
1086 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +01001087 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001088 // Need to forward arrays separate of fields.
1089 ArtField* field = &cur_fields->At(i);
1090 auto it2 = native_object_relocations_.find(field);
1091 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
1092 << " already assigned " << PrettyField(field) << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001093 DCHECK(!IsInBootImage(field));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001094 native_object_relocations_.emplace(field,
1095 NativeObjectRelocation {oat_file, offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001096 offset += sizeof(ArtField);
1097 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001098 }
1099 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001100 // Visit and assign offsets for methods.
Alex Lighte64300b2015-12-15 15:02:47 -08001101 size_t num_methods = as_klass->NumMethods();
1102 if (num_methods != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001103 bool any_dirty = false;
Alex Lighte64300b2015-12-15 15:02:47 -08001104 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1105 if (WillMethodBeDirty(&m)) {
1106 any_dirty = true;
1107 break;
1108 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001109 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001110 NativeObjectRelocationType type = any_dirty
1111 ? kNativeObjectRelocationTypeArtMethodDirty
1112 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001113 Bin bin_type = BinTypeForNativeRelocationType(type);
1114 // Forward the entire array at once, but header first.
Alex Lighte64300b2015-12-15 15:02:47 -08001115 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1116 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01001117 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1118 method_size,
1119 method_alignment);
Alex Lighte64300b2015-12-15 15:02:47 -08001120 LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001121 auto it = native_object_relocations_.find(array);
Alex Lighte64300b2015-12-15 15:02:47 -08001122 CHECK(it == native_object_relocations_.end())
1123 << "Method array " << array << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001124 size_t& offset = image_info.bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001125 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001126 native_object_relocations_.emplace(array,
1127 NativeObjectRelocation {
1128 oat_file,
1129 offset,
1130 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty
1131 : kNativeObjectRelocationTypeArtMethodArrayClean });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001132 offset += header_size;
Alex Lighte64300b2015-12-15 15:02:47 -08001133 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001134 AssignMethodOffset(&m, type, oat_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001135 }
Alex Lighte64300b2015-12-15 15:02:47 -08001136 (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001137 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001138 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001139 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001140 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001141 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001142 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001143 mirror::Object* value = obj_array->Get(i);
1144 if (value != nullptr) {
1145 WalkFieldsInOrder(value);
1146 }
1147 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001148 } else if (h_obj->IsClassLoader()) {
1149 // Register the class loader if it has a class table.
1150 // The fake boot class loader should not get registered and we should end up with only one
1151 // class loader.
1152 mirror::ClassLoader* class_loader = h_obj->AsClassLoader();
1153 if (class_loader->GetClassTable() != nullptr) {
1154 class_loaders_.insert(class_loader);
1155 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001156 }
1157 }
1158}
1159
Jeff Haodcdc85b2015-12-04 14:06:18 -08001160void ImageWriter::AssignMethodOffset(ArtMethod* method,
1161 NativeObjectRelocationType type,
1162 const char* oat_filename) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001163 DCHECK(!IsInBootImage(method));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001164 auto it = native_object_relocations_.find(method);
1165 CHECK(it == native_object_relocations_.end()) << "Method " << method << " already assigned "
Mathieu Chartiere401d142015-04-22 13:56:20 -07001166 << PrettyMethod(method);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001167 ImageInfo& image_info = GetImageInfo(oat_filename);
1168 size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
1169 native_object_relocations_.emplace(method, NativeObjectRelocation { oat_filename, offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001170 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001171}
1172
Mathieu Chartier590fee92013-09-13 13:46:47 -07001173void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
1174 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1175 DCHECK(writer != nullptr);
1176 writer->WalkFieldsInOrder(obj);
1177}
1178
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001179void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
1180 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1181 DCHECK(writer != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001182 if (!writer->IsInBootImage(obj)) {
1183 writer->UnbinObjectsIntoOffset(obj);
1184 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001185}
1186
1187void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001188 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001189 CHECK(obj != nullptr);
1190
1191 // We know the bin slot, and the total bin sizes for all objects by now,
1192 // so calculate the object's final image offset.
1193
1194 DCHECK(IsImageBinSlotAssigned(obj));
1195 BinSlot bin_slot = GetImageBinSlot(obj);
1196 // Change the lockword from a bin slot into an offset
1197 AssignImageOffset(obj, bin_slot);
1198}
1199
Vladimir Markof4da6752014-08-01 19:04:18 +01001200void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001201 Thread* const self = Thread::Current();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001202 StackHandleScopeCollection handles(self);
1203 std::vector<Handle<ObjectArray<Object>>> image_roots;
1204 for (const char* oat_filename : oat_filenames_) {
1205 std::string image_filename = oat_filename;
1206 image_roots.push_back(handles.NewHandle(CreateImageRoots(image_filename.c_str())));
1207 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001208
Mathieu Chartiere401d142015-04-22 13:56:20 -07001209 auto* runtime = Runtime::Current();
1210 auto* heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001211
Mathieu Chartier31e89252013-08-28 11:29:12 -07001212 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001213 // know where image_roots is going to end up
Jeff Haodcdc85b2015-12-04 14:06:18 -08001214 image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001215
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001216 // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
1217 heap->VisitObjects(WalkFieldsCallback, this);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001218 // Write the image runtime methods.
1219 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1220 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1221 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
1222 image_methods_[ImageHeader::kCalleeSaveMethod] = runtime->GetCalleeSaveMethod(Runtime::kSaveAll);
1223 image_methods_[ImageHeader::kRefsOnlySaveMethod] =
1224 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly);
1225 image_methods_[ImageHeader::kRefsAndArgsSaveMethod] =
1226 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001227
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001228 // Add room for fake length prefixed array for holding the image methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001229 const auto image_method_type = kNativeObjectRelocationTypeArtMethodArrayClean;
1230 auto it = native_object_relocations_.find(&image_method_array_);
1231 CHECK(it == native_object_relocations_.end());
Jeff Haodcdc85b2015-12-04 14:06:18 -08001232 ImageInfo& default_image_info = GetImageInfo(default_oat_filename_);
1233 size_t& offset =
1234 default_image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(image_method_type)];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001235 if (!compile_app_image_) {
1236 native_object_relocations_.emplace(&image_method_array_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001237 NativeObjectRelocation { default_oat_filename_, offset, image_method_type });
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001238 }
Vladimir Marko14632852015-08-17 12:07:23 +01001239 size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001240 const size_t array_size = LengthPrefixedArray<ArtMethod>::ComputeSize(
Vladimir Marko14632852015-08-17 12:07:23 +01001241 0, ArtMethod::Size(target_ptr_size_), method_alignment);
Vladimir Markocf36d492015-08-12 19:27:26 +01001242 CHECK_ALIGNED_PARAM(array_size, method_alignment);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001243 offset += array_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001244 for (auto* m : image_methods_) {
1245 CHECK(m != nullptr);
1246 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001247 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1248 if (!IsInBootImage(m)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001249 AssignMethodOffset(m, kNativeObjectRelocationTypeArtMethodClean, default_oat_filename_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001250 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001251 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001252 // Calculate size of the dex cache arrays slot and prepare offsets.
1253 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001254
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001255 // Calculate the sizes of the intern tables.
1256 for (const char* oat_filename : oat_filenames_) {
1257 ImageInfo& image_info = GetImageInfo(oat_filename);
1258 // Calculate how big the intern table will be after being serialized.
1259 InternTable* const intern_table = image_info.intern_table_.get();
1260 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
1261 image_info.intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
1262 }
1263
Vladimir Markocf36d492015-08-12 19:27:26 +01001264 // Calculate bin slot offsets.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001265 for (const char* oat_filename : oat_filenames_) {
1266 ImageInfo& image_info = GetImageInfo(oat_filename);
1267 size_t bin_offset = image_objects_offset_begin_;
1268 for (size_t i = 0; i != kBinSize; ++i) {
1269 image_info.bin_slot_offsets_[i] = bin_offset;
1270 bin_offset += image_info.bin_slot_sizes_[i];
1271 if (i == kBinArtField) {
1272 static_assert(kBinArtField + 1 == kBinArtMethodClean, "Methods follow fields.");
1273 static_assert(alignof(ArtField) == 4u, "ArtField alignment is 4.");
1274 DCHECK_ALIGNED(bin_offset, 4u);
1275 DCHECK(method_alignment == 4u || method_alignment == 8u);
1276 bin_offset = RoundUp(bin_offset, method_alignment);
1277 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001278 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001279 // NOTE: There may be additional padding between the bin slots and the intern table.
1280 DCHECK_EQ(image_info.image_end_,
1281 GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_);
Vladimir Marko20f85592015-03-19 10:07:02 +00001282 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001283
Jeff Haodcdc85b2015-12-04 14:06:18 -08001284 // Calculate image offsets.
1285 size_t image_offset = 0;
1286 for (const char* oat_filename : oat_filenames_) {
1287 ImageInfo& image_info = GetImageInfo(oat_filename);
1288 image_info.image_begin_ = global_image_begin_ + image_offset;
1289 image_info.image_offset_ = image_offset;
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001290 ImageSection unused_sections[ImageHeader::kSectionCount];
1291 image_info.image_size_ = RoundUp(
1292 image_info.CreateImageSections(target_ptr_size_, unused_sections),
1293 kPageSize);
1294 // There should be no gaps until the next image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001295 image_offset += image_info.image_size_;
1296 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001297
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001298 // Transform each object's bin slot into an offset which will be used to do the final copy.
1299 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001300
Jeff Haodcdc85b2015-12-04 14:06:18 -08001301 // DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001302
Jeff Haodcdc85b2015-12-04 14:06:18 -08001303 size_t i = 0;
1304 for (const char* oat_filename : oat_filenames_) {
1305 ImageInfo& image_info = GetImageInfo(oat_filename);
1306 image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
1307 i++;
1308 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001309
Mathieu Chartiere401d142015-04-22 13:56:20 -07001310 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001311 for (auto& pair : native_object_relocations_) {
1312 NativeObjectRelocation& relocation = pair.second;
1313 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001314 ImageInfo& image_info = GetImageInfo(relocation.oat_filename);
1315 relocation.offset += image_info.bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001316 }
1317
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001318 /* TODO: Reenable the class table. b/26317072
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001319 // Write out the class table.
1320 ClassLinker* class_linker = runtime->GetClassLinker();
1321 if (boot_image_space_ == nullptr) {
1322 // Compiling the boot image, add null class loader.
1323 class_loaders_.insert(nullptr);
1324 }
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001325 // class_loaders_ usually will not be empty, but may be empty if we attempt to create an image
1326 // with no classes.
1327 if (class_loaders_.size() == 1u) {
1328 // Only write the class table if we have exactly one class loader. There may be cases where
1329 // there are multiple class loaders if a class path is passed to dex2oat.
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001330 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1331 for (mirror::ClassLoader* loader : class_loaders_) {
1332 ClassTable* table = class_linker->ClassTableForClassLoader(loader);
1333 CHECK(table != nullptr);
1334 class_table_bytes_ += table->WriteToMemory(nullptr);
1335 }
1336 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001337 */
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001338
Jeff Haodcdc85b2015-12-04 14:06:18 -08001339 // Note that image_info.image_end_ is left at end of used mirror object section.
Vladimir Markof4da6752014-08-01 19:04:18 +01001340}
1341
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001342size_t ImageWriter::ImageInfo::CreateImageSections(size_t target_ptr_size,
1343 ImageSection* out_sections) const {
1344 DCHECK(out_sections != nullptr);
1345 // Objects section
1346 auto* objects_section = &out_sections[ImageHeader::kSectionObjects];
1347 *objects_section = ImageSection(0u, image_end_);
1348 size_t cur_pos = objects_section->End();
1349 // Add field section.
1350 auto* field_section = &out_sections[ImageHeader::kSectionArtFields];
1351 *field_section = ImageSection(cur_pos, bin_slot_sizes_[kBinArtField]);
1352 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
1353 cur_pos = field_section->End();
1354 // Round up to the alignment the required by the method section.
1355 cur_pos = RoundUp(cur_pos, ArtMethod::Alignment(target_ptr_size));
1356 // Add method section.
1357 auto* methods_section = &out_sections[ImageHeader::kSectionArtMethods];
1358 *methods_section = ImageSection(cur_pos,
1359 bin_slot_sizes_[kBinArtMethodClean] +
1360 bin_slot_sizes_[kBinArtMethodDirty]);
1361 CHECK_EQ(bin_slot_offsets_[kBinArtMethodClean], methods_section->Offset());
1362 cur_pos = methods_section->End();
1363 // Add dex cache arrays section.
1364 auto* dex_cache_arrays_section = &out_sections[ImageHeader::kSectionDexCacheArrays];
1365 *dex_cache_arrays_section = ImageSection(cur_pos, bin_slot_sizes_[kBinDexCacheArray]);
1366 CHECK_EQ(bin_slot_offsets_[kBinDexCacheArray], dex_cache_arrays_section->Offset());
1367 cur_pos = dex_cache_arrays_section->End();
1368 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
1369 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1370 // Calculate the size of the interned strings.
1371 auto* interned_strings_section = &out_sections[ImageHeader::kSectionInternedStrings];
1372 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1373 cur_pos = interned_strings_section->End();
1374 // Round up to the alignment the class table expects. See HashSet::WriteToMemory.
1375 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1376 // Calculate the size of the class table section.
1377 auto* class_table_section = &out_sections[ImageHeader::kSectionClassTable];
1378 // TODO: class_table_bytes_
1379 *class_table_section = ImageSection(cur_pos, 0u);
1380 cur_pos = class_table_section->End();
1381 // Image end goes right before the start of the image bitmap.
1382 return cur_pos;
1383}
1384
Vladimir Markof4da6752014-08-01 19:04:18 +01001385void ImageWriter::CreateHeader(size_t oat_loaded_size, size_t oat_data_offset) {
1386 CHECK_NE(0U, oat_loaded_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001387 const char* oat_filename = oat_file_->GetLocation().c_str();
1388 ImageInfo& image_info = GetImageInfo(oat_filename);
1389 const uint8_t* oat_file_begin = GetOatFileBegin(oat_filename);
Ian Rogers13735952014-10-08 12:43:28 -07001390 const uint8_t* oat_file_end = oat_file_begin + oat_loaded_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001391 image_info.oat_data_begin_ = const_cast<uint8_t*>(oat_file_begin) + oat_data_offset;
1392 const uint8_t* oat_data_end = image_info.oat_data_begin_ + oat_file_->Size();
1393 image_info.oat_size_ = oat_file_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001394
1395 // Create the image sections.
1396 ImageSection sections[ImageHeader::kSectionCount];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001397 const size_t image_end = image_info.CreateImageSections(target_ptr_size_, sections);
1398
Mathieu Chartiere401d142015-04-22 13:56:20 -07001399 // Finally bitmap section.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001400 const size_t bitmap_bytes = image_info.image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001401 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001402 *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001403 if (VLOG_IS_ON(compiler)) {
1404 LOG(INFO) << "Creating header for " << oat_filename;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001405 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001406 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001407 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1408 ++idx;
1409 }
1410 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001411 LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
1412 LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
1413 << " Image offset=" << image_info.image_offset_ << std::dec;
1414 LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
1415 << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
1416 << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
1417 << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001418 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001419
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001420 // Create the header, leave 0 for data size since we will fill this in as we are writing the
1421 // image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001422 new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_),
1423 image_end,
1424 sections,
1425 image_info.image_roots_address_,
1426 oat_file_->GetOatHeader().GetChecksum(),
1427 PointerToLowMemUInt32(oat_file_begin),
1428 PointerToLowMemUInt32(image_info.oat_data_begin_),
1429 PointerToLowMemUInt32(oat_data_end),
1430 PointerToLowMemUInt32(oat_file_end),
1431 target_ptr_size_,
1432 compile_pic_,
1433 image_storage_mode_,
1434 /*data_size*/0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001435}
1436
1437ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001438 auto it = native_object_relocations_.find(method);
1439 CHECK(it != native_object_relocations_.end()) << PrettyMethod(method) << " @ " << method;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001440 const char* oat_filename = GetOatFilename(method->GetDexCache());
1441 ImageInfo& image_info = GetImageInfo(oat_filename);
1442 CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects";
1443 return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001444}
1445
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001446class FixupRootVisitor : public RootVisitor {
1447 public:
1448 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1449 }
1450
1451 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001452 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001453 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001454 *roots[i] = image_writer_->GetImageAddress(*roots[i]);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001455 }
1456 }
1457
1458 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1459 const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001460 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001461 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001462 roots[i]->Assign(image_writer_->GetImageAddress(roots[i]->AsMirrorPtr()));
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001463 }
1464 }
1465
1466 private:
1467 ImageWriter* const image_writer_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001468};
1469
Mathieu Chartierc7853442015-03-27 14:35:38 -07001470void ImageWriter::CopyAndFixupNativeData() {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001471 const char* oat_filename = oat_file_->GetLocation().c_str();
1472 ImageInfo& image_info = GetImageInfo(oat_filename);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001473 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001474 for (auto& pair : native_object_relocations_) {
1475 NativeObjectRelocation& relocation = pair.second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001476 // Only work with fields and methods that are in the current oat file.
1477 if (strcmp(relocation.oat_filename, oat_filename) != 0) {
1478 continue;
1479 }
1480 auto* dest = image_info.image_->Begin() + relocation.offset;
1481 DCHECK_GE(dest, image_info.image_->Begin() + image_info.image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001482 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001483 switch (relocation.type) {
1484 case kNativeObjectRelocationTypeArtField: {
1485 memcpy(dest, pair.first, sizeof(ArtField));
1486 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
1487 GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass()));
1488 break;
1489 }
1490 case kNativeObjectRelocationTypeArtMethodClean:
1491 case kNativeObjectRelocationTypeArtMethodDirty: {
1492 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001493 reinterpret_cast<ArtMethod*>(dest),
1494 image_info);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001495 break;
1496 }
1497 // For arrays, copy just the header since the elements will get copied by their corresponding
1498 // relocations.
1499 case kNativeObjectRelocationTypeArtFieldArray: {
1500 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1501 break;
1502 }
1503 case kNativeObjectRelocationTypeArtMethodArrayClean:
1504 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markocf36d492015-08-12 19:27:26 +01001505 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(
1506 0,
Vladimir Marko14632852015-08-17 12:07:23 +01001507 ArtMethod::Size(target_ptr_size_),
1508 ArtMethod::Alignment(target_ptr_size_)));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001509 break;
Vladimir Marko05792b92015-08-03 11:56:49 +01001510 case kNativeObjectRelocationTypeDexCacheArray:
1511 // Nothing to copy here, everything is done in FixupDexCache().
1512 break;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001513 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001514 }
1515 }
1516 // Fixup the image method roots.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001517 auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001518 const ImageSection& methods_section = image_header->GetMethodsSection();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001519 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001520 ArtMethod* method = image_methods_[i];
1521 CHECK(method != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001522 // Only place runtime methods in the image of the default oat file.
1523 if (method->IsRuntimeMethod() && strcmp(default_oat_filename_, oat_filename) != 0) {
1524 continue;
1525 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001526 if (!IsInBootImage(method)) {
1527 auto it = native_object_relocations_.find(method);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001528 CHECK(it != native_object_relocations_.end()) << "No forwarding for " << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001529 NativeObjectRelocation& relocation = it->second;
1530 CHECK(methods_section.Contains(relocation.offset)) << relocation.offset << " not in "
1531 << methods_section;
1532 CHECK(relocation.IsArtMethodRelocation()) << relocation.type;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001533 method = reinterpret_cast<ArtMethod*>(global_image_begin_ + it->second.offset);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001534 }
1535 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001536 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001537 FixupRootVisitor root_visitor(this);
1538
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001539 // Write the intern table into the image.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001540 if (image_info.intern_table_bytes_ > 0) {
1541 const ImageSection& intern_table_section = image_header->GetImageSection(
1542 ImageHeader::kSectionInternedStrings);
1543 InternTable* const intern_table = image_info.intern_table_.get();
1544 uint8_t* const intern_table_memory_ptr =
1545 image_info.image_->Begin() + intern_table_section.Offset();
1546 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
1547 CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
1548 // Fixup the pointers in the newly written intern table to contain image addresses.
1549 InternTable temp_intern_table;
1550 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1551 // the VisitRoots() will update the memory directly rather than the copies.
1552 // This also relies on visit roots not doing any verification which could fail after we update
1553 // the roots to be the image addresses.
1554 temp_intern_table.AddTableFromMemory(intern_table_memory_ptr);
1555 CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
1556 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
1557 }
1558 /* TODO: Reenable the class table writing.
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001559 // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
1560 // class loaders. Writing multiple class tables into the image is currently unsupported.
1561 if (class_table_bytes_ > 0u) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001562 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001563 const ImageSection& class_table_section = image_header->GetImageSection(
1564 ImageHeader::kSectionClassTable);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001565 uint8_t* const class_table_memory_ptr =
1566 image_info.image_->Begin() + class_table_section.Offset();
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001567 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1568 size_t class_table_bytes = 0;
1569 for (mirror::ClassLoader* loader : class_loaders_) {
1570 ClassTable* table = class_linker->ClassTableForClassLoader(loader);
1571 CHECK(table != nullptr);
1572 uint8_t* memory_ptr = class_table_memory_ptr + class_table_bytes;
1573 class_table_bytes += table->WriteToMemory(memory_ptr);
1574 // Fixup the pointers in the newly written class table to contain image addresses. See
1575 // above comment for intern tables.
1576 ClassTable temp_class_table;
1577 temp_class_table.ReadFromMemory(memory_ptr);
1578 CHECK_EQ(temp_class_table.NumZygoteClasses(), table->NumNonZygoteClasses() +
1579 table->NumZygoteClasses());
1580 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(&root_visitor,
1581 RootInfo(kRootUnknown));
1582 temp_class_table.VisitRoots(buffered_visitor);
1583 }
1584 CHECK_EQ(class_table_bytes, class_table_bytes_);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001585 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001586 */
Mathieu Chartierc7853442015-03-27 14:35:38 -07001587}
1588
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001589void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001590 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001591 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1592 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001593 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001594 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07001595 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
1596 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001597 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001598 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001599}
1600
Mathieu Chartier590fee92013-09-13 13:46:47 -07001601void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001602 DCHECK(obj != nullptr);
1603 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001604 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1605}
1606
Mathieu Chartiere401d142015-04-22 13:56:20 -07001607void ImageWriter::FixupPointerArray(mirror::Object* dst, mirror::PointerArray* arr,
1608 mirror::Class* klass, Bin array_type) {
1609 CHECK(klass->IsArrayClass());
1610 CHECK(arr->IsIntArray() || arr->IsLongArray()) << PrettyClass(klass) << " " << arr;
1611 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001612 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001613 dst->SetClass(GetImageAddress(arr->GetClass()));
1614 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001615 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001616 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
1617 if (elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001618 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01001619 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001620 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001621 auto* method = reinterpret_cast<ArtMethod*>(elem);
1622 LOG(FATAL) << "No relocation entry for ArtMethod " << PrettyMethod(method) << " @ "
1623 << method << " idx=" << i << "/" << num_elements << " with declaring class "
1624 << PrettyClass(method->GetDeclaringClass());
1625 } else {
1626 CHECK_EQ(array_type, kBinArtField);
1627 auto* field = reinterpret_cast<ArtField*>(elem);
1628 LOG(FATAL) << "No relocation entry for ArtField " << PrettyField(field) << " @ "
1629 << field << " idx=" << i << "/" << num_elements << " with declaring class "
1630 << PrettyClass(field->GetDeclaringClass());
1631 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001632 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001633 } else {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001634 ImageInfo& image_info = GetImageInfo(it->second.oat_filename);
1635 elem = image_info.image_begin_ + it->second.offset;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001636 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001637 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001638 dest_array->SetElementPtrSize<false, true>(i, elem, target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001639 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001640}
1641
1642void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001643 if (IsInBootImage(obj)) {
1644 return;
1645 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001646 size_t offset = GetImageOffset(obj);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001647 const char* oat_filename = GetOatFilename(obj);
1648 ImageInfo& image_info = GetImageInfo(oat_filename);
1649 auto* dst = reinterpret_cast<Object*>(image_info.image_->Begin() + offset);
1650 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001651 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001652
Jeff Haodcdc85b2015-12-04 14:06:18 -08001653 image_info.image_bitmap_->Set(dst); // Mark the obj as live.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001654
1655 const size_t n = obj->SizeOf();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001656 DCHECK_LE(offset + n, image_info.image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001657 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001658
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001659 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1660 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001661 const auto it = saved_hashcode_map_.find(obj);
1662 dst->SetLockWord(it != saved_hashcode_map_.end() ?
1663 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001664 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001665}
1666
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001667// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001668class FixupVisitor {
1669 public:
1670 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1671 }
1672
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001673 // Ignore class roots since we don't have a way to map them to the destination. These are handled
1674 // with other logic.
1675 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1676 const {}
1677 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1678
1679
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001680 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001681 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -07001682 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001683 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1684 // image.
1685 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001686 offset,
1687 image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001688 }
1689
1690 // java.lang.ref.Reference visitor.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001691 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001692 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001693 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001694 mirror::Reference::ReferentOffset(),
1695 image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001696 }
1697
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001698 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001699 ImageWriter* const image_writer_;
1700 mirror::Object* const copy_;
1701};
1702
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001703class FixupClassVisitor FINAL : public FixupVisitor {
1704 public:
1705 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1706 }
1707
Mathieu Chartierc7853442015-03-27 14:35:38 -07001708 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001709 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001710 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001711 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001712 }
1713
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001714 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1715 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001716 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001717 LOG(FATAL) << "Reference not expected here.";
1718 }
1719};
1720
Vladimir Marko05792b92015-08-03 11:56:49 +01001721uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
1722 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001723 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001724 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001725 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1726 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001727 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01001728 return relocation.offset;
1729}
1730
1731template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001732T* ImageWriter::NativeLocationInImage(T* obj, const char* oat_filename) {
1733 if (obj == nullptr || IsInBootImage(obj)) {
1734 return obj;
1735 } else {
1736 ImageInfo& image_info = GetImageInfo(oat_filename);
1737 return reinterpret_cast<T*>(image_info.image_begin_ + NativeOffsetInImage(obj));
1738 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001739}
1740
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001741template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001742T* ImageWriter::NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) {
1743 if (obj == nullptr || IsInBootImage(obj)) {
1744 return obj;
1745 } else {
1746 const char* oat_filename = GetOatFilenameForDexCache(dex_cache);
1747 ImageInfo& image_info = GetImageInfo(oat_filename);
1748 return reinterpret_cast<T*>(image_info.image_->Begin() + NativeOffsetInImage(obj));
1749 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001750}
1751
1752class NativeLocationVisitor {
1753 public:
Jeff Haodcdc85b2015-12-04 14:06:18 -08001754 explicit NativeLocationVisitor(ImageWriter* image_writer, const char* oat_filename)
1755 : image_writer_(image_writer), oat_filename_(oat_filename) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001756
1757 template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001758 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
1759 return image_writer_->NativeLocationInImage(ptr, oat_filename_);
1760 }
1761
1762 ArtMethod* operator()(ArtMethod* method) const SHARED_REQUIRES(Locks::mutator_lock_) {
1763 const char* oat_filename = method->IsRuntimeMethod() ? image_writer_->GetDefaultOatFilename() :
1764 image_writer_->GetOatFilenameForDexCache(method->GetDexCache());
1765 return image_writer_->NativeLocationInImage(method, oat_filename);
1766 }
1767
1768 ArtField* operator()(ArtField* field) const SHARED_REQUIRES(Locks::mutator_lock_) {
1769 const char* oat_filename = image_writer_->GetOatFilenameForDexCache(field->GetDexCache());
1770 return image_writer_->NativeLocationInImage(field, oat_filename);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001771 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001772
1773 private:
1774 ImageWriter* const image_writer_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001775 const char* oat_filename_;
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001776};
1777
1778void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001779 const char* oat_filename = GetOatFilename(orig);
1780 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this, oat_filename));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001781 FixupClassVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001782 static_cast<mirror::Object*>(orig)->VisitReferences(visitor, visitor);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001783}
1784
Ian Rogersef7d42f2014-01-06 12:55:46 -08001785void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001786 DCHECK(orig != nullptr);
1787 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07001788 if (kUseBakerOrBrooksReadBarrier) {
1789 orig->AssertReadBarrierPointer();
1790 if (kUseBrooksReadBarrier) {
1791 // Note the address 'copy' isn't the same as the image address of 'orig'.
1792 copy->SetReadBarrierPointer(GetImageAddress(orig));
1793 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
1794 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08001795 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001796 auto* klass = orig->GetClass();
1797 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001798 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07001799 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
1800 if (it != pointer_arrays_.end()) {
1801 // Should only need to fixup every pointer array exactly once.
1802 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
1803 pointer_arrays_.erase(it);
1804 return;
1805 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001806 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001807 if (orig->IsClass()) {
1808 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001809 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001810 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
1811 // Need to go update the ArtMethod.
1812 auto* dest = down_cast<mirror::AbstractMethod*>(copy);
1813 auto* src = down_cast<mirror::AbstractMethod*>(orig);
1814 ArtMethod* src_method = src->GetArtMethod();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001815 auto it = native_object_relocations_.find(src_method);
1816 CHECK(it != native_object_relocations_.end())
1817 << "Missing relocation for AbstractMethod.artMethod " << PrettyMethod(src_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001818 dest->SetArtMethod(
Jeff Haodcdc85b2015-12-04 14:06:18 -08001819 reinterpret_cast<ArtMethod*>(global_image_begin_ + it->second.offset));
Vladimir Marko05792b92015-08-03 11:56:49 +01001820 } else if (!klass->IsArrayClass()) {
1821 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1822 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
1823 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001824 } else if (klass->IsClassLoaderClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001825 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
1826 // ClassLoader.
1827 down_cast<mirror::ClassLoader*>(copy)->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07001828 // Also set allocator to null to be safe. The allocator is created when we create the class
1829 // table. We also never expect to unload things in the image since they are held live as
1830 // roots.
1831 down_cast<mirror::ClassLoader*>(copy)->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01001832 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001833 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001834 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001835 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001836 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001837}
1838
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001839
1840class ImageAddressVisitor {
1841 public:
1842 explicit ImageAddressVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
1843
1844 template <typename T>
1845 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
1846 return image_writer_->GetImageAddress(ptr);
1847 }
1848
1849 private:
1850 ImageWriter* const image_writer_;
1851};
1852
1853
Vladimir Marko05792b92015-08-03 11:56:49 +01001854void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
1855 mirror::DexCache* copy_dex_cache) {
1856 // Though the DexCache array fields are usually treated as native pointers, we set the full
1857 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
1858 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
1859 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
Jeff Haodcdc85b2015-12-04 14:06:18 -08001860 const char* oat_filename = GetOatFilenameForDexCache(orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01001861 GcRoot<mirror::String>* orig_strings = orig_dex_cache->GetStrings();
1862 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001863 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001864 NativeLocationInImage(orig_strings, oat_filename),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001865 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001866 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings, orig_dex_cache),
1867 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001868 }
1869 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
1870 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001871 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001872 NativeLocationInImage(orig_types, oat_filename),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001873 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001874 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types, orig_dex_cache),
1875 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001876 }
1877 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
1878 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001879 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001880 NativeLocationInImage(orig_methods, oat_filename),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001881 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001882 ArtMethod** copy_methods = NativeCopyLocation(orig_methods, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01001883 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
1884 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001885 const char* method_oat_filename;
1886 if (orig == nullptr || orig->IsRuntimeMethod()) {
1887 method_oat_filename = default_oat_filename_;
1888 } else {
1889 method_oat_filename = GetOatFilenameForDexCache(orig->GetDexCache());
1890 }
1891 ArtMethod* copy = NativeLocationInImage(orig, method_oat_filename);
Vladimir Marko05792b92015-08-03 11:56:49 +01001892 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
1893 }
1894 }
1895 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
1896 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001897 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001898 NativeLocationInImage(orig_fields, oat_filename),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001899 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001900 ArtField** copy_fields = NativeCopyLocation(orig_fields, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01001901 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
1902 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, i, target_ptr_size_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001903 const char* field_oat_filename =
1904 orig == nullptr ? default_oat_filename_ : GetOatFilenameForDexCache(orig->GetDexCache());
1905 ArtField* copy = NativeLocationInImage(orig, field_oat_filename);
Vladimir Marko05792b92015-08-03 11:56:49 +01001906 mirror::DexCache::SetElementPtrSize(copy_fields, i, copy, target_ptr_size_);
1907 }
1908 }
1909}
1910
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001911const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
1912 DCHECK_LT(type, kOatAddressCount);
1913 // If we are compiling an app image, we need to use the stubs of the boot image.
1914 if (compile_app_image_) {
1915 // Use the current image pointers.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001916 std::vector<gc::space::ImageSpace*> image_spaces =
1917 Runtime::Current()->GetHeap()->GetBootImageSpaces();
1918 DCHECK(!image_spaces.empty());
1919 const OatFile* oat_file = image_spaces[0]->GetOatFile();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001920 CHECK(oat_file != nullptr);
1921 const OatHeader& header = oat_file->GetOatHeader();
1922 switch (type) {
1923 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
1924 case kOatAddressQuickGenericJNITrampoline:
1925 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
1926 case kOatAddressInterpreterToInterpreterBridge:
1927 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
1928 case kOatAddressInterpreterToCompiledCodeBridge:
1929 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
1930 case kOatAddressJNIDlsymLookup:
1931 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
1932 case kOatAddressQuickIMTConflictTrampoline:
1933 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
1934 case kOatAddressQuickResolutionTrampoline:
1935 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
1936 case kOatAddressQuickToInterpreterBridge:
1937 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
1938 default:
1939 UNREACHABLE();
1940 }
1941 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001942 const ImageInfo& primary_image_info = GetImageInfo(0);
1943 return GetOatAddressForOffset(primary_image_info.oat_address_offsets_[type], primary_image_info);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001944}
1945
Jeff Haodcdc85b2015-12-04 14:06:18 -08001946const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method,
1947 const ImageInfo& image_info,
1948 bool* quick_is_interpreted) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001949 DCHECK(!method->IsResolutionMethod()) << PrettyMethod(method);
1950 DCHECK(!method->IsImtConflictMethod()) << PrettyMethod(method);
1951 DCHECK(!method->IsImtUnimplementedMethod()) << PrettyMethod(method);
Alex Light9139e002015-10-09 15:59:48 -07001952 DCHECK(method->IsInvokable()) << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001953 DCHECK(!IsInBootImage(method)) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001954
1955 // Use original code if it exists. Otherwise, set the code pointer to the resolution
1956 // trampoline.
1957
1958 // Quick entrypoint:
Jeff Haoc7d11882015-02-03 15:08:39 -08001959 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(
1960 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001961 const uint8_t* quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001962 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001963 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
1964 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001965 // We have code for a non-static or initialized method, just use the code.
1966 } else if (quick_code == nullptr && method->IsNative() &&
1967 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
1968 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001969 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001970 } else if (quick_code == nullptr && !method->IsNative()) {
1971 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001972 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001973 *quick_is_interpreted = true;
1974 } else {
1975 CHECK(!method->GetDeclaringClass()->IsInitialized());
1976 // We have code for a static method, but need to go through the resolution stub for class
1977 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001978 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
1979 }
1980 if (!IsInBootOatFile(quick_code)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001981 // DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001982 }
1983 return quick_code;
1984}
1985
Jeff Haodcdc85b2015-12-04 14:06:18 -08001986void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
1987 ArtMethod* copy,
1988 const ImageInfo& image_info) {
Vladimir Marko14632852015-08-17 12:07:23 +01001989 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001990
1991 copy->SetDeclaringClass(GetImageAddress(orig->GetDeclaringClassUnchecked()));
Vladimir Marko05792b92015-08-03 11:56:49 +01001992
Jeff Haodcdc85b2015-12-04 14:06:18 -08001993 const char* oat_filename;
1994 if (orig->IsRuntimeMethod()) {
1995 oat_filename = default_oat_filename_;
1996 } else {
1997 auto it = dex_file_oat_filename_map_.find(orig->GetDexFile());
1998 DCHECK(it != dex_file_oat_filename_map_.end()) << orig->GetDexFile()->GetLocation();
1999 oat_filename = it->second;
2000 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002001 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002002 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods, oat_filename),
2003 target_ptr_size_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002004 GcRoot<mirror::Class>* orig_resolved_types = orig->GetDexCacheResolvedTypes(target_ptr_size_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002005 copy->SetDexCacheResolvedTypes(NativeLocationInImage(orig_resolved_types, oat_filename),
2006 target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002007
Ian Rogers848871b2013-08-05 10:56:33 -07002008 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
2009 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07002010
Ian Rogers848871b2013-08-05 10:56:33 -07002011 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002012 Runtime* runtime = Runtime::Current();
2013 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002014 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002015 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002016 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
2017 orig == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002018 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002019 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002020 } else if (UNLIKELY(orig->IsRuntimeMethod())) {
2021 bool found_one = false;
2022 for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) {
2023 auto idx = static_cast<Runtime::CalleeSaveType>(i);
2024 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
2025 found_one = true;
2026 break;
2027 }
2028 }
2029 CHECK(found_one) << "Expected to find callee save method but got " << PrettyMethod(orig);
2030 CHECK(copy->IsRuntimeMethod());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002031 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002032 // We assume all methods have code. If they don't currently then we set them to the use the
2033 // resolution trampoline. Abstract methods never have code and so we need to make sure their
2034 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07002035 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002036 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002037 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002038 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002039 bool quick_is_interpreted;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002040 const uint8_t* quick_code = GetQuickCode(orig, image_info, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002041 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02002042
Sebastien Hertze1d07812014-05-21 15:44:09 +02002043 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07002044 if (orig->IsNative()) {
2045 // The native method's pointer is set to a stub to lookup via dlsym.
2046 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002047 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002048 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002049 }
2050 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002051 }
2052}
2053
Alex Lighta59dd802014-07-02 16:28:08 -07002054static OatHeader* GetOatHeaderFromElf(ElfFile* elf) {
Tong Shen62d1ca32014-09-03 17:24:56 -07002055 uint64_t data_sec_offset;
2056 bool has_data_sec = elf->GetSectionOffsetAndSize(".rodata", &data_sec_offset, nullptr);
2057 if (!has_data_sec) {
Alex Lighta59dd802014-07-02 16:28:08 -07002058 return nullptr;
2059 }
Tong Shen62d1ca32014-09-03 17:24:56 -07002060 return reinterpret_cast<OatHeader*>(elf->Begin() + data_sec_offset);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08002061}
2062
Vladimir Markof4da6752014-08-01 19:04:18 +01002063void ImageWriter::SetOatChecksumFromElfFile(File* elf_file) {
Alex Lighta59dd802014-07-02 16:28:08 -07002064 std::string error_msg;
Mathieu Chartiera808bac2015-11-05 16:33:15 -08002065 std::unique_ptr<ElfFile> elf(ElfFile::Open(elf_file,
2066 PROT_READ | PROT_WRITE,
2067 MAP_SHARED,
2068 &error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -07002069 if (elf.get() == nullptr) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002070 LOG(FATAL) << "Unable open oat file: " << error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07002071 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002072 }
Alex Lighta59dd802014-07-02 16:28:08 -07002073 OatHeader* oat_header = GetOatHeaderFromElf(elf.get());
2074 CHECK(oat_header != nullptr);
2075 CHECK(oat_header->IsValid());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002076
Jeff Haodcdc85b2015-12-04 14:06:18 -08002077 ImageInfo& image_info = GetImageInfo(oat_file_->GetLocation().c_str());
2078 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Alex Lighta59dd802014-07-02 16:28:08 -07002079 image_header->SetOatChecksum(oat_header->GetChecksum());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002080}
2081
Jeff Haodcdc85b2015-12-04 14:06:18 -08002082size_t ImageWriter::GetBinSizeSum(ImageWriter::ImageInfo& image_info, ImageWriter::Bin up_to) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002083 DCHECK_LE(up_to, kBinSize);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002084 return std::accumulate(&image_info.bin_slot_sizes_[0],
2085 &image_info.bin_slot_sizes_[up_to],
2086 /*init*/0);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002087}
2088
2089ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
2090 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07002091 static_assert(kBinBits == 3, "wrong number of bin bits");
2092 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002093 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
2094
2095 DCHECK_LT(GetBin(), kBinSize);
2096 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
2097}
2098
2099ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
2100 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
2101 DCHECK_EQ(index, GetIndex());
2102}
2103
2104ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
2105 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
2106}
2107
2108uint32_t ImageWriter::BinSlot::GetIndex() const {
2109 return lockword_ & ~kBinMask;
2110}
2111
Jeff Haodcdc85b2015-12-04 14:06:18 -08002112uint8_t* ImageWriter::GetOatFileBegin(const char* oat_filename) const {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002113 uintptr_t last_image_end = 0;
2114 for (const char* oat_fn : oat_filenames_) {
2115 const ImageInfo& image_info = GetConstImageInfo(oat_fn);
2116 DCHECK(image_info.image_begin_ != nullptr);
2117 uintptr_t this_end = reinterpret_cast<uintptr_t>(image_info.image_begin_) +
2118 image_info.image_size_;
2119 last_image_end = std::max(this_end, last_image_end);
2120 }
2121 const ImageInfo& image_info = GetConstImageInfo(oat_filename);
2122 return reinterpret_cast<uint8_t*>(last_image_end) + image_info.oat_offset_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002123}
2124
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002125ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
2126 switch (type) {
2127 case kNativeObjectRelocationTypeArtField:
2128 case kNativeObjectRelocationTypeArtFieldArray:
2129 return kBinArtField;
2130 case kNativeObjectRelocationTypeArtMethodClean:
2131 case kNativeObjectRelocationTypeArtMethodArrayClean:
2132 return kBinArtMethodClean;
2133 case kNativeObjectRelocationTypeArtMethodDirty:
2134 case kNativeObjectRelocationTypeArtMethodArrayDirty:
2135 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01002136 case kNativeObjectRelocationTypeDexCacheArray:
2137 return kBinDexCacheArray;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002138 }
2139 UNREACHABLE();
2140}
2141
Jeff Haodcdc85b2015-12-04 14:06:18 -08002142const char* ImageWriter::GetOatFilename(mirror::Object* obj) const {
2143 if (compile_app_image_) {
2144 return default_oat_filename_;
2145 } else {
2146 return GetOatFilenameForDexCache(obj->IsDexCache() ? obj->AsDexCache() :
2147 obj->IsClass() ? obj->AsClass()->GetDexCache() : obj->GetClass()->GetDexCache());
2148 }
2149}
2150
2151const char* ImageWriter::GetOatFilenameForDexCache(mirror::DexCache* dex_cache) const {
2152 if (compile_app_image_ || dex_cache == nullptr) {
2153 return default_oat_filename_;
2154 } else {
2155 auto it = dex_file_oat_filename_map_.find(dex_cache->GetDexFile());
2156 DCHECK(it != dex_file_oat_filename_map_.end()) << dex_cache->GetDexFile()->GetLocation();
2157 return it->second;
2158 }
2159}
2160
2161ImageWriter::ImageInfo& ImageWriter::GetImageInfo(const char* oat_filename) {
2162 auto it = image_info_map_.find(oat_filename);
2163 DCHECK(it != image_info_map_.end());
2164 return it->second;
2165}
2166
2167const ImageWriter::ImageInfo& ImageWriter::GetConstImageInfo(const char* oat_filename) const {
2168 auto it = image_info_map_.find(oat_filename);
2169 DCHECK(it != image_info_map_.end());
2170 return it->second;
2171}
2172
2173const ImageWriter::ImageInfo& ImageWriter::GetImageInfo(size_t index) const {
2174 DCHECK_LT(index, oat_filenames_.size());
2175 return GetConstImageInfo(oat_filenames_[index]);
2176}
2177
2178void ImageWriter::UpdateOatFile(const char* oat_filename) {
2179 std::unique_ptr<File> oat_file(OS::OpenFileForReading(oat_filename));
2180 DCHECK(oat_file != nullptr);
2181 size_t oat_loaded_size = 0;
2182 size_t oat_data_offset = 0;
2183 ElfWriter::GetOatElfInformation(oat_file.get(), &oat_loaded_size, &oat_data_offset);
2184
2185 ImageInfo& cur_image_info = GetImageInfo(oat_filename);
2186
2187 // Update the oat_offset of the next image info.
2188 auto it = std::find(oat_filenames_.begin(), oat_filenames_.end(), oat_filename);
2189 DCHECK(it != oat_filenames_.end());
2190
2191 it++;
2192 if (it != oat_filenames_.end()) {
2193 // There is a following one.
2194 ImageInfo& next_image_info = GetImageInfo(*it);
2195 next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
2196 }
2197}
2198
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002199ImageWriter::ImageWriter(
2200 const CompilerDriver& compiler_driver,
2201 uintptr_t image_begin,
2202 bool compile_pic,
2203 bool compile_app_image,
2204 ImageHeader::StorageMode image_storage_mode,
2205 const std::vector<const char*> oat_filenames,
2206 const std::unordered_map<const DexFile*, const char*>& dex_file_oat_filename_map)
2207 : compiler_driver_(compiler_driver),
2208 global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
2209 image_objects_offset_begin_(0),
2210 oat_file_(nullptr),
2211 compile_pic_(compile_pic),
2212 compile_app_image_(compile_app_image),
2213 boot_image_space_(nullptr),
2214 target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())),
2215 image_method_array_(ImageHeader::kImageMethodsCount),
2216 dirty_methods_(0u),
2217 clean_methods_(0u),
2218 class_table_bytes_(0u),
2219 image_storage_mode_(image_storage_mode),
2220 dex_file_oat_filename_map_(dex_file_oat_filename_map),
2221 oat_filenames_(oat_filenames),
2222 default_oat_filename_(oat_filenames[0]) {
2223 CHECK_NE(image_begin, 0U);
2224 for (const char* oat_filename : oat_filenames) {
2225 image_info_map_.emplace(oat_filename, ImageInfo());
2226 }
2227 std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
2228}
2229
2230ImageWriter::ImageInfo::ImageInfo() : intern_table_(new InternTable) {}
2231
Brian Carlstrom7940e442013-07-12 13:46:57 -07002232} // namespace art