blob: 17d0f61a3488970c5b15d8dc27d53a7933408197 [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);
638 const size_t length = RoundUp(image_objects_offset_begin_ +
639 GetBinSizeSum(image_info) +
640 intern_table_bytes_ +
641 class_table_bytes_,
642 kPageSize);
643 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()) {
912 // we must be an interned string that was forward referenced and already assigned
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800913 if (IsImageBinSlotAssigned(obj)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700914 DCHECK_EQ(obj, obj->AsString()->Intern());
915 return;
916 }
Mathieu Chartier14c3bf92015-07-13 14:35:43 -0700917 // InternImageString allows us to intern while holding the heap bitmap lock. This is safe since
918 // we are guaranteed to not have GC during image writing.
Mathieu Chartier90ef3db2015-08-04 15:19:41 -0700919 mirror::String* const interned = Runtime::Current()->GetInternTable()->InternStrongImageString(
Mathieu Chartier14c3bf92015-07-13 14:35:43 -0700920 obj->AsString());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700921 if (obj != interned) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800922 if (!IsImageBinSlotAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700923 // interned obj is after us, allocate its location early
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800924 AssignImageBinSlot(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700925 }
926 // point those looking for this object to the interned version.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800927 SetImageBinSlot(obj, GetImageBinSlot(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700928 return;
929 }
930 // else (obj == interned), nothing to do but fall through to the normal case
931 }
932
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800933 AssignImageBinSlot(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700934}
935
Jeff Haodcdc85b2015-12-04 14:06:18 -0800936ObjectArray<Object>* ImageWriter::CreateImageRoots(const char* oat_filename) const {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700937 Runtime* runtime = Runtime::Current();
938 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700939 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700940 StackHandleScope<3> hs(self);
941 Handle<Class> object_array_class(hs.NewHandle(
942 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700943
Jeff Haodcdc85b2015-12-04 14:06:18 -0800944 std::unordered_set<const DexFile*> image_dex_files;
945 for (auto& pair : dex_file_oat_filename_map_) {
946 const DexFile* image_dex_file = pair.first;
947 const char* image_oat_filename = pair.second;
948 if (strcmp(oat_filename, image_oat_filename) == 0) {
949 image_dex_files.insert(image_dex_file);
950 }
951 }
952
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700953 // build an Object[] of all the DexCaches used in the source_space_.
954 // Since we can't hold the dex lock when allocating the dex_caches
955 // ObjectArray, we lock the dex lock twice, first to get the number
956 // of dex caches first and then lock it again to copy the dex
957 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800958 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700959 {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700960 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800961 // Count number of dex caches not in the boot image.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800962 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
963 mirror::DexCache* dex_cache =
964 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -0800965 const DexFile* dex_file = dex_cache->GetDexFile();
966 if (!IsInBootImage(dex_cache)) {
967 dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
968 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800969 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700970 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700971 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800972 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700973 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
974 {
Mathieu Chartierc7853442015-03-27 14:35:38 -0700975 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800976 size_t non_image_dex_caches = 0;
977 // Re-count number of non image dex caches.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800978 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
979 mirror::DexCache* dex_cache =
980 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -0800981 const DexFile* dex_file = dex_cache->GetDexFile();
982 if (!IsInBootImage(dex_cache)) {
983 non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
984 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800985 }
986 CHECK_EQ(dex_cache_count, non_image_dex_caches)
987 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700988 size_t i = 0;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800989 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
990 mirror::DexCache* dex_cache =
991 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -0800992 const DexFile* dex_file = dex_cache->GetDexFile();
993 if (!IsInBootImage(dex_cache) && image_dex_files.find(dex_file) != image_dex_files.end()) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800994 dex_caches->Set<false>(i, dex_cache);
995 ++i;
996 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700997 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700998 }
999
1000 // build an Object[] of the roots needed to restore the runtime
Mathieu Chartiere401d142015-04-22 13:56:20 -07001001 auto image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001002 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001003 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001004 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001005 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001006 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001007 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001008 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001009}
1010
Mathieu Chartier590fee92013-09-13 13:46:47 -07001011// Walk instance fields of the given Class. Separate function to allow recursion on the super
1012// class.
1013void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
1014 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001015 StackHandleScope<1> hs(Thread::Current());
1016 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1017 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001018 if (super != nullptr) {
1019 WalkInstanceFields(obj, super);
1020 }
1021 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001022 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Marko76649e82014-11-10 18:32:59 +00001023 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001024 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001025 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001026 if (value != nullptr) {
1027 WalkFieldsInOrder(value);
1028 }
Vladimir Marko76649e82014-11-10 18:32:59 +00001029 field_offset = MemberOffset(field_offset.Uint32Value() +
1030 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001031 }
1032}
1033
1034// For an unvisited object, visit it then all its children found via fields.
1035void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001036 if (IsInBootImage(obj)) {
1037 // Object is in the image, don't need to fix it up.
1038 return;
1039 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001040 // Use our own visitor routine (instead of GC visitor) to get better locality between
1041 // an object and its fields
1042 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001043 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001044 StackHandleScope<2> hs(Thread::Current());
1045 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
1046 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001047 // visit the object itself.
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001048 CalculateObjectBinSlots(h_obj.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001049 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001050 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001051 if (h_obj->IsClass()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001052 size_t num_reference_static_fields = klass->NumReferenceStaticFields();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001053 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001054 for (size_t i = 0; i < num_reference_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001055 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001056 if (value != nullptr) {
1057 WalkFieldsInOrder(value);
1058 }
Vladimir Marko76649e82014-11-10 18:32:59 +00001059 field_offset = MemberOffset(field_offset.Uint32Value() +
1060 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001061 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001062 // Visit and assign offsets for fields and field arrays.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001063 auto* as_klass = h_obj->AsClass();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001064 mirror::DexCache* dex_cache = as_klass->GetDexCache();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001065 LengthPrefixedArray<ArtField>* fields[] = {
1066 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
1067 };
Jeff Haodcdc85b2015-12-04 14:06:18 -08001068 const char* oat_file = GetOatFilenameForDexCache(dex_cache);
1069 ImageInfo& image_info = GetImageInfo(oat_file);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001070 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1071 // Total array length including header.
1072 if (cur_fields != nullptr) {
1073 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
1074 // Forward the entire array at once.
1075 auto it = native_object_relocations_.find(cur_fields);
1076 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
1077 << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001078 size_t& offset = image_info.bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001079 DCHECK(!IsInBootImage(cur_fields));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001080 native_object_relocations_.emplace(cur_fields,
1081 NativeObjectRelocation {oat_file, offset, kNativeObjectRelocationTypeArtFieldArray });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001082 offset += header_size;
1083 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +01001084 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001085 // Need to forward arrays separate of fields.
1086 ArtField* field = &cur_fields->At(i);
1087 auto it2 = native_object_relocations_.find(field);
1088 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
1089 << " already assigned " << PrettyField(field) << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001090 DCHECK(!IsInBootImage(field));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001091 native_object_relocations_.emplace(field,
1092 NativeObjectRelocation {oat_file, offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001093 offset += sizeof(ArtField);
1094 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001095 }
1096 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001097 // Visit and assign offsets for methods.
Alex Lighte64300b2015-12-15 15:02:47 -08001098 size_t num_methods = as_klass->NumMethods();
1099 if (num_methods != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001100 bool any_dirty = false;
Alex Lighte64300b2015-12-15 15:02:47 -08001101 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1102 if (WillMethodBeDirty(&m)) {
1103 any_dirty = true;
1104 break;
1105 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001106 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001107 NativeObjectRelocationType type = any_dirty
1108 ? kNativeObjectRelocationTypeArtMethodDirty
1109 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001110 Bin bin_type = BinTypeForNativeRelocationType(type);
1111 // Forward the entire array at once, but header first.
Alex Lighte64300b2015-12-15 15:02:47 -08001112 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1113 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01001114 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1115 method_size,
1116 method_alignment);
Alex Lighte64300b2015-12-15 15:02:47 -08001117 LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001118 auto it = native_object_relocations_.find(array);
Alex Lighte64300b2015-12-15 15:02:47 -08001119 CHECK(it == native_object_relocations_.end())
1120 << "Method array " << array << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001121 size_t& offset = image_info.bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001122 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001123 native_object_relocations_.emplace(array,
1124 NativeObjectRelocation {
1125 oat_file,
1126 offset,
1127 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty
1128 : kNativeObjectRelocationTypeArtMethodArrayClean });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001129 offset += header_size;
Alex Lighte64300b2015-12-15 15:02:47 -08001130 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001131 AssignMethodOffset(&m, type, oat_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001132 }
Alex Lighte64300b2015-12-15 15:02:47 -08001133 (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001134 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001135 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001136 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001137 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001138 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001139 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001140 mirror::Object* value = obj_array->Get(i);
1141 if (value != nullptr) {
1142 WalkFieldsInOrder(value);
1143 }
1144 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001145 } else if (h_obj->IsClassLoader()) {
1146 // Register the class loader if it has a class table.
1147 // The fake boot class loader should not get registered and we should end up with only one
1148 // class loader.
1149 mirror::ClassLoader* class_loader = h_obj->AsClassLoader();
1150 if (class_loader->GetClassTable() != nullptr) {
1151 class_loaders_.insert(class_loader);
1152 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001153 }
1154 }
1155}
1156
Jeff Haodcdc85b2015-12-04 14:06:18 -08001157void ImageWriter::AssignMethodOffset(ArtMethod* method,
1158 NativeObjectRelocationType type,
1159 const char* oat_filename) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001160 DCHECK(!IsInBootImage(method));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001161 auto it = native_object_relocations_.find(method);
1162 CHECK(it == native_object_relocations_.end()) << "Method " << method << " already assigned "
Mathieu Chartiere401d142015-04-22 13:56:20 -07001163 << PrettyMethod(method);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001164 ImageInfo& image_info = GetImageInfo(oat_filename);
1165 size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
1166 native_object_relocations_.emplace(method, NativeObjectRelocation { oat_filename, offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001167 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001168}
1169
Mathieu Chartier590fee92013-09-13 13:46:47 -07001170void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
1171 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1172 DCHECK(writer != nullptr);
1173 writer->WalkFieldsInOrder(obj);
1174}
1175
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001176void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
1177 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1178 DCHECK(writer != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001179 if (!writer->IsInBootImage(obj)) {
1180 writer->UnbinObjectsIntoOffset(obj);
1181 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001182}
1183
1184void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001185 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001186 CHECK(obj != nullptr);
1187
1188 // We know the bin slot, and the total bin sizes for all objects by now,
1189 // so calculate the object's final image offset.
1190
1191 DCHECK(IsImageBinSlotAssigned(obj));
1192 BinSlot bin_slot = GetImageBinSlot(obj);
1193 // Change the lockword from a bin slot into an offset
1194 AssignImageOffset(obj, bin_slot);
1195}
1196
Vladimir Markof4da6752014-08-01 19:04:18 +01001197void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001198 Thread* const self = Thread::Current();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001199 StackHandleScopeCollection handles(self);
1200 std::vector<Handle<ObjectArray<Object>>> image_roots;
1201 for (const char* oat_filename : oat_filenames_) {
1202 std::string image_filename = oat_filename;
1203 image_roots.push_back(handles.NewHandle(CreateImageRoots(image_filename.c_str())));
1204 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001205
Mathieu Chartiere401d142015-04-22 13:56:20 -07001206 auto* runtime = Runtime::Current();
1207 auto* heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001208
Mathieu Chartier31e89252013-08-28 11:29:12 -07001209 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001210 // know where image_roots is going to end up
Jeff Haodcdc85b2015-12-04 14:06:18 -08001211 image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001212
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001213 // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
1214 heap->VisitObjects(WalkFieldsCallback, this);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001215 // Write the image runtime methods.
1216 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1217 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1218 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
1219 image_methods_[ImageHeader::kCalleeSaveMethod] = runtime->GetCalleeSaveMethod(Runtime::kSaveAll);
1220 image_methods_[ImageHeader::kRefsOnlySaveMethod] =
1221 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly);
1222 image_methods_[ImageHeader::kRefsAndArgsSaveMethod] =
1223 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001224
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001225 // Add room for fake length prefixed array for holding the image methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001226 const auto image_method_type = kNativeObjectRelocationTypeArtMethodArrayClean;
1227 auto it = native_object_relocations_.find(&image_method_array_);
1228 CHECK(it == native_object_relocations_.end());
Jeff Haodcdc85b2015-12-04 14:06:18 -08001229 ImageInfo& default_image_info = GetImageInfo(default_oat_filename_);
1230 size_t& offset =
1231 default_image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(image_method_type)];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001232 if (!compile_app_image_) {
1233 native_object_relocations_.emplace(&image_method_array_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001234 NativeObjectRelocation { default_oat_filename_, offset, image_method_type });
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001235 }
Vladimir Marko14632852015-08-17 12:07:23 +01001236 size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001237 const size_t array_size = LengthPrefixedArray<ArtMethod>::ComputeSize(
Vladimir Marko14632852015-08-17 12:07:23 +01001238 0, ArtMethod::Size(target_ptr_size_), method_alignment);
Vladimir Markocf36d492015-08-12 19:27:26 +01001239 CHECK_ALIGNED_PARAM(array_size, method_alignment);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001240 offset += array_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001241 for (auto* m : image_methods_) {
1242 CHECK(m != nullptr);
1243 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001244 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1245 if (!IsInBootImage(m)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001246 AssignMethodOffset(m, kNativeObjectRelocationTypeArtMethodClean, default_oat_filename_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001247 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001248 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001249 // Calculate size of the dex cache arrays slot and prepare offsets.
1250 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001251
Vladimir Markocf36d492015-08-12 19:27:26 +01001252 // Calculate bin slot offsets.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001253 for (const char* oat_filename : oat_filenames_) {
1254 ImageInfo& image_info = GetImageInfo(oat_filename);
1255 size_t bin_offset = image_objects_offset_begin_;
1256 for (size_t i = 0; i != kBinSize; ++i) {
1257 image_info.bin_slot_offsets_[i] = bin_offset;
1258 bin_offset += image_info.bin_slot_sizes_[i];
1259 if (i == kBinArtField) {
1260 static_assert(kBinArtField + 1 == kBinArtMethodClean, "Methods follow fields.");
1261 static_assert(alignof(ArtField) == 4u, "ArtField alignment is 4.");
1262 DCHECK_ALIGNED(bin_offset, 4u);
1263 DCHECK(method_alignment == 4u || method_alignment == 8u);
1264 bin_offset = RoundUp(bin_offset, method_alignment);
1265 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001266 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001267 // NOTE: There may be additional padding between the bin slots and the intern table.
1268 DCHECK_EQ(image_info.image_end_,
1269 GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_);
Vladimir Marko20f85592015-03-19 10:07:02 +00001270 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001271
Jeff Haodcdc85b2015-12-04 14:06:18 -08001272 // Calculate image offsets.
1273 size_t image_offset = 0;
1274 for (const char* oat_filename : oat_filenames_) {
1275 ImageInfo& image_info = GetImageInfo(oat_filename);
1276 image_info.image_begin_ = global_image_begin_ + image_offset;
1277 image_info.image_offset_ = image_offset;
1278 size_t native_sections_size = image_info.bin_slot_sizes_[kBinArtField] +
1279 image_info.bin_slot_sizes_[kBinArtMethodDirty] +
1280 image_info.bin_slot_sizes_[kBinArtMethodClean] +
1281 image_info.bin_slot_sizes_[kBinDexCacheArray] +
1282 intern_table_bytes_ +
1283 class_table_bytes_;
1284 size_t image_objects = RoundUp(image_info.image_end_, kPageSize);
1285 size_t bitmap_size =
1286 RoundUp(gc::accounting::ContinuousSpaceBitmap::ComputeBitmapSize(image_objects), kPageSize);
1287 size_t heap_size = gc::accounting::ContinuousSpaceBitmap::ComputeHeapSize(bitmap_size);
1288 size_t max = std::max(heap_size, image_info.image_end_ + native_sections_size + bitmap_size);
1289 image_info.image_size_ = RoundUp(max, kPageSize);
1290 image_offset += image_info.image_size_;
1291 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001292
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001293 // Transform each object's bin slot into an offset which will be used to do the final copy.
1294 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001295
Jeff Haodcdc85b2015-12-04 14:06:18 -08001296 // DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001297
Jeff Haodcdc85b2015-12-04 14:06:18 -08001298 size_t i = 0;
1299 for (const char* oat_filename : oat_filenames_) {
1300 ImageInfo& image_info = GetImageInfo(oat_filename);
1301 image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
1302 i++;
1303 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001304
Mathieu Chartiere401d142015-04-22 13:56:20 -07001305 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001306 for (auto& pair : native_object_relocations_) {
1307 NativeObjectRelocation& relocation = pair.second;
1308 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001309 ImageInfo& image_info = GetImageInfo(relocation.oat_filename);
1310 relocation.offset += image_info.bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001311 }
1312
Jeff Haodcdc85b2015-12-04 14:06:18 -08001313 /* TODO: Reenable the intern table and class table. b/26317072
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001314 // Calculate how big the intern table will be after being serialized.
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001315 InternTable* const intern_table = runtime->GetInternTable();
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001316 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
1317 intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
1318
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
1342void ImageWriter::CreateHeader(size_t oat_loaded_size, size_t oat_data_offset) {
1343 CHECK_NE(0U, oat_loaded_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001344 const char* oat_filename = oat_file_->GetLocation().c_str();
1345 ImageInfo& image_info = GetImageInfo(oat_filename);
1346 const uint8_t* oat_file_begin = GetOatFileBegin(oat_filename);
Ian Rogers13735952014-10-08 12:43:28 -07001347 const uint8_t* oat_file_end = oat_file_begin + oat_loaded_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001348 image_info.oat_data_begin_ = const_cast<uint8_t*>(oat_file_begin) + oat_data_offset;
1349 const uint8_t* oat_data_end = image_info.oat_data_begin_ + oat_file_->Size();
1350 image_info.oat_size_ = oat_file_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001351
1352 // Create the image sections.
1353 ImageSection sections[ImageHeader::kSectionCount];
1354 // Objects section
1355 auto* objects_section = &sections[ImageHeader::kSectionObjects];
Jeff Haodcdc85b2015-12-04 14:06:18 -08001356 *objects_section = ImageSection(0u, image_info.image_end_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001357 size_t cur_pos = objects_section->End();
1358 // Add field section.
1359 auto* field_section = &sections[ImageHeader::kSectionArtFields];
Jeff Haodcdc85b2015-12-04 14:06:18 -08001360 *field_section = ImageSection(cur_pos, image_info.bin_slot_sizes_[kBinArtField]);
1361 CHECK_EQ(image_info.bin_slot_offsets_[kBinArtField], field_section->Offset());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001362 cur_pos = field_section->End();
Vladimir Markocf36d492015-08-12 19:27:26 +01001363 // Round up to the alignment the required by the method section.
Vladimir Marko14632852015-08-17 12:07:23 +01001364 cur_pos = RoundUp(cur_pos, ArtMethod::Alignment(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07001365 // Add method section.
1366 auto* methods_section = &sections[ImageHeader::kSectionArtMethods];
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001367 *methods_section = ImageSection(cur_pos,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001368 image_info.bin_slot_sizes_[kBinArtMethodClean] +
1369 image_info.bin_slot_sizes_[kBinArtMethodDirty]);
1370 CHECK_EQ(image_info.bin_slot_offsets_[kBinArtMethodClean], methods_section->Offset());
Mathieu Chartiere401d142015-04-22 13:56:20 -07001371 cur_pos = methods_section->End();
Vladimir Marko05792b92015-08-03 11:56:49 +01001372 // Add dex cache arrays section.
1373 auto* dex_cache_arrays_section = &sections[ImageHeader::kSectionDexCacheArrays];
Jeff Haodcdc85b2015-12-04 14:06:18 -08001374 *dex_cache_arrays_section = ImageSection(cur_pos, image_info.bin_slot_sizes_[kBinDexCacheArray]);
1375 CHECK_EQ(image_info.bin_slot_offsets_[kBinDexCacheArray], dex_cache_arrays_section->Offset());
Vladimir Marko05792b92015-08-03 11:56:49 +01001376 cur_pos = dex_cache_arrays_section->End();
Nicolas Geoffray7bf2b4f2015-07-08 10:11:59 +00001377 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
1378 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001379 // Calculate the size of the interned strings.
1380 auto* interned_strings_section = &sections[ImageHeader::kSectionInternedStrings];
1381 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1382 cur_pos = interned_strings_section->End();
Alex Lighte050c8f2015-12-16 15:52:51 -08001383 // Round up to the alignment the class table expects. See HashSet::WriteToMemory.
1384 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001385 // Calculate the size of the class table section.
1386 auto* class_table_section = &sections[ImageHeader::kSectionClassTable];
1387 *class_table_section = ImageSection(cur_pos, class_table_bytes_);
1388 cur_pos = class_table_section->End();
1389 // Image end goes right before the start of the image bitmap.
1390 const size_t image_end = static_cast<uint32_t>(cur_pos);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001391 // Finally bitmap section.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001392 const size_t bitmap_bytes = image_info.image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001393 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
1394 *bitmap_section = ImageSection(RoundUp(cur_pos, kPageSize), RoundUp(bitmap_bytes, kPageSize));
1395 cur_pos = bitmap_section->End();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001396 if (VLOG_IS_ON(compiler)) {
1397 LOG(INFO) << "Creating header for " << oat_filename;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001398 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001399 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001400 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1401 ++idx;
1402 }
1403 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001404 LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
1405 LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
1406 << " Image offset=" << image_info.image_offset_ << std::dec;
1407 LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
1408 << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
1409 << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
1410 << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001411 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001412
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001413 // Create the header, leave 0 for data size since we will fill this in as we are writing the
1414 // image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001415 new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_),
1416 image_end,
1417 sections,
1418 image_info.image_roots_address_,
1419 oat_file_->GetOatHeader().GetChecksum(),
1420 PointerToLowMemUInt32(oat_file_begin),
1421 PointerToLowMemUInt32(image_info.oat_data_begin_),
1422 PointerToLowMemUInt32(oat_data_end),
1423 PointerToLowMemUInt32(oat_file_end),
1424 target_ptr_size_,
1425 compile_pic_,
1426 image_storage_mode_,
1427 /*data_size*/0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001428}
1429
1430ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001431 auto it = native_object_relocations_.find(method);
1432 CHECK(it != native_object_relocations_.end()) << PrettyMethod(method) << " @ " << method;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001433 const char* oat_filename = GetOatFilename(method->GetDexCache());
1434 ImageInfo& image_info = GetImageInfo(oat_filename);
1435 CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects";
1436 return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001437}
1438
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001439class FixupRootVisitor : public RootVisitor {
1440 public:
1441 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1442 }
1443
1444 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001445 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001446 for (size_t i = 0; i < count; ++i) {
1447 *roots[i] = ImageAddress(*roots[i]);
1448 }
1449 }
1450
1451 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1452 const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001453 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001454 for (size_t i = 0; i < count; ++i) {
1455 roots[i]->Assign(ImageAddress(roots[i]->AsMirrorPtr()));
1456 }
1457 }
1458
1459 private:
1460 ImageWriter* const image_writer_;
1461
Mathieu Chartier90443472015-07-16 20:32:27 -07001462 mirror::Object* ImageAddress(mirror::Object* obj) SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001463 const size_t offset = image_writer_->GetImageOffset(obj);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001464 auto* const dest = reinterpret_cast<Object*>(image_writer_->global_image_begin_ + offset);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001465 VLOG(compiler) << "Update root from " << obj << " to " << dest;
1466 return dest;
1467 }
1468};
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
Jeff Haodcdc85b2015-12-04 14:06:18 -08001539 /* TODO: Reenable the intern table and class table
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001540 // Write the intern table into the image.
1541 const ImageSection& intern_table_section = image_header->GetImageSection(
1542 ImageHeader::kSectionInternedStrings);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001543 Runtime* const runtime = Runtime::Current();
1544 InternTable* const intern_table = runtime->GetInternTable();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001545 uint8_t* const intern_table_memory_ptr =
1546 image_info.image_->Begin() + intern_table_section.Offset();
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001547 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
1548 CHECK_EQ(intern_table_bytes, intern_table_bytes_);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001549 // Fixup the pointers in the newly written intern table to contain image addresses.
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001550 InternTable temp_intern_table;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001551 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1552 // the VisitRoots() will update the memory directly rather than the copies.
1553 // This also relies on visit roots not doing any verification which could fail after we update
1554 // the roots to be the image addresses.
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001555 temp_intern_table.ReadFromMemory(intern_table_memory_ptr);
1556 CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
1557 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
1558
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 {
2113 // DCHECK_GT(intern_table_bytes_, 0u); TODO: Reenable intern table and class table.
2114 uintptr_t last_image_end = 0;
2115 for (const char* oat_fn : oat_filenames_) {
2116 const ImageInfo& image_info = GetConstImageInfo(oat_fn);
2117 DCHECK(image_info.image_begin_ != nullptr);
2118 uintptr_t this_end = reinterpret_cast<uintptr_t>(image_info.image_begin_) +
2119 image_info.image_size_;
2120 last_image_end = std::max(this_end, last_image_end);
2121 }
2122 const ImageInfo& image_info = GetConstImageInfo(oat_filename);
2123 return reinterpret_cast<uint8_t*>(last_image_end) + image_info.oat_offset_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002124}
2125
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002126ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
2127 switch (type) {
2128 case kNativeObjectRelocationTypeArtField:
2129 case kNativeObjectRelocationTypeArtFieldArray:
2130 return kBinArtField;
2131 case kNativeObjectRelocationTypeArtMethodClean:
2132 case kNativeObjectRelocationTypeArtMethodArrayClean:
2133 return kBinArtMethodClean;
2134 case kNativeObjectRelocationTypeArtMethodDirty:
2135 case kNativeObjectRelocationTypeArtMethodArrayDirty:
2136 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01002137 case kNativeObjectRelocationTypeDexCacheArray:
2138 return kBinDexCacheArray;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002139 }
2140 UNREACHABLE();
2141}
2142
Jeff Haodcdc85b2015-12-04 14:06:18 -08002143const char* ImageWriter::GetOatFilename(mirror::Object* obj) const {
2144 if (compile_app_image_) {
2145 return default_oat_filename_;
2146 } else {
2147 return GetOatFilenameForDexCache(obj->IsDexCache() ? obj->AsDexCache() :
2148 obj->IsClass() ? obj->AsClass()->GetDexCache() : obj->GetClass()->GetDexCache());
2149 }
2150}
2151
2152const char* ImageWriter::GetOatFilenameForDexCache(mirror::DexCache* dex_cache) const {
2153 if (compile_app_image_ || dex_cache == nullptr) {
2154 return default_oat_filename_;
2155 } else {
2156 auto it = dex_file_oat_filename_map_.find(dex_cache->GetDexFile());
2157 DCHECK(it != dex_file_oat_filename_map_.end()) << dex_cache->GetDexFile()->GetLocation();
2158 return it->second;
2159 }
2160}
2161
2162ImageWriter::ImageInfo& ImageWriter::GetImageInfo(const char* oat_filename) {
2163 auto it = image_info_map_.find(oat_filename);
2164 DCHECK(it != image_info_map_.end());
2165 return it->second;
2166}
2167
2168const ImageWriter::ImageInfo& ImageWriter::GetConstImageInfo(const char* oat_filename) const {
2169 auto it = image_info_map_.find(oat_filename);
2170 DCHECK(it != image_info_map_.end());
2171 return it->second;
2172}
2173
2174const ImageWriter::ImageInfo& ImageWriter::GetImageInfo(size_t index) const {
2175 DCHECK_LT(index, oat_filenames_.size());
2176 return GetConstImageInfo(oat_filenames_[index]);
2177}
2178
2179void ImageWriter::UpdateOatFile(const char* oat_filename) {
2180 std::unique_ptr<File> oat_file(OS::OpenFileForReading(oat_filename));
2181 DCHECK(oat_file != nullptr);
2182 size_t oat_loaded_size = 0;
2183 size_t oat_data_offset = 0;
2184 ElfWriter::GetOatElfInformation(oat_file.get(), &oat_loaded_size, &oat_data_offset);
2185
2186 ImageInfo& cur_image_info = GetImageInfo(oat_filename);
2187
2188 // Update the oat_offset of the next image info.
2189 auto it = std::find(oat_filenames_.begin(), oat_filenames_.end(), oat_filename);
2190 DCHECK(it != oat_filenames_.end());
2191
2192 it++;
2193 if (it != oat_filenames_.end()) {
2194 // There is a following one.
2195 ImageInfo& next_image_info = GetImageInfo(*it);
2196 next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
2197 }
2198}
2199
Brian Carlstrom7940e442013-07-12 13:46:57 -07002200} // namespace art