blob: c8720eab8a427f3b08719a4c2af082bcec52cd66 [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "image_writer.h"
18
19#include <sys/stat.h>
Mathieu Chartierceb07b32015-12-10 09:33:21 -080020#include <lz4.h>
Brian Carlstrom7940e442013-07-12 13:46:57 -070021
Ian Rogers700a4022014-05-19 16:49:03 -070022#include <memory>
Vladimir Marko20f85592015-03-19 10:07:02 +000023#include <numeric>
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080024#include <unordered_set>
Brian Carlstrom7940e442013-07-12 13:46:57 -070025#include <vector>
26
Mathieu Chartierc7853442015-03-27 14:35:38 -070027#include "art_field-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070028#include "art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070029#include "base/logging.h"
30#include "base/unix_file/fd_file.h"
Vladimir Marko3481ba22015-04-13 12:22:36 +010031#include "class_linker-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070032#include "compiled_method.h"
33#include "dex_file-inl.h"
34#include "driver/compiler_driver.h"
Alex Light53cb16b2014-06-12 11:26:29 -070035#include "elf_file.h"
36#include "elf_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070037#include "elf_writer.h"
38#include "gc/accounting/card_table-inl.h"
39#include "gc/accounting/heap_bitmap.h"
Mathieu Chartier31e89252013-08-28 11:29:12 -070040#include "gc/accounting/space_bitmap-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070041#include "gc/heap.h"
42#include "gc/space/large_object_space.h"
43#include "gc/space/space-inl.h"
44#include "globals.h"
45#include "image.h"
46#include "intern_table.h"
Mathieu Chartierc7853442015-03-27 14:35:38 -070047#include "linear_alloc.h"
Mathieu Chartierad2541a2013-10-25 10:05:23 -070048#include "lock_word.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070049#include "mirror/abstract_method.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070050#include "mirror/array-inl.h"
51#include "mirror/class-inl.h"
52#include "mirror/class_loader.h"
53#include "mirror/dex_cache-inl.h"
Mathieu Chartiere401d142015-04-22 13:56:20 -070054#include "mirror/method.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070055#include "mirror/object-inl.h"
56#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070057#include "mirror/string-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070058#include "oat.h"
59#include "oat_file.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070060#include "oat_file_manager.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070061#include "runtime.h"
62#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070063#include "handle_scope-inl.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000064#include "utils/dex_cache_arrays_layout-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070065
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070066using ::art::mirror::Class;
67using ::art::mirror::DexCache;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070068using ::art::mirror::Object;
69using ::art::mirror::ObjectArray;
70using ::art::mirror::String;
Brian Carlstrom7940e442013-07-12 13:46:57 -070071
72namespace art {
73
Igor Murashkinf5b4c502014-11-14 15:01:59 -080074// Separate objects into multiple bins to optimize dirty memory use.
75static constexpr bool kBinObjects = true;
76
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080077// Return true if an object is already in an image space.
78bool ImageWriter::IsInBootImage(const void* obj) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080079 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080080 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080081 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080082 return false;
83 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -080084 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
85 const uint8_t* image_begin = boot_image_space->Begin();
86 // Real image end including ArtMethods and ArtField sections.
87 const uint8_t* image_end = image_begin + boot_image_space->GetImageHeader().GetImageSize();
88 if (image_begin <= obj && obj < image_end) {
89 return true;
90 }
91 }
92 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080093}
94
95bool ImageWriter::IsInBootOatFile(const void* ptr) const {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080096 gc::Heap* const heap = Runtime::Current()->GetHeap();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080097 if (!compile_app_image_) {
Mathieu Chartiere467cea2016-01-07 18:36:19 -080098 DCHECK(heap->GetBootImageSpaces().empty());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -080099 return false;
100 }
Mathieu Chartiere467cea2016-01-07 18:36:19 -0800101 for (gc::space::ImageSpace* boot_image_space : heap->GetBootImageSpaces()) {
102 const ImageHeader& image_header = boot_image_space->GetImageHeader();
103 if (image_header.GetOatFileBegin() <= ptr && ptr < image_header.GetOatFileEnd()) {
104 return true;
105 }
106 }
107 return false;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800108}
109
Andreas Gampedd9d0552015-03-09 12:57:41 -0700110static void CheckNoDexObjectsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -0700111 SHARED_REQUIRES(Locks::mutator_lock_) {
Andreas Gampedd9d0552015-03-09 12:57:41 -0700112 Class* klass = obj->GetClass();
113 CHECK_NE(PrettyClass(klass), "com.android.dex.Dex");
114}
115
116static void CheckNoDexObjects() {
117 ScopedObjectAccess soa(Thread::Current());
118 Runtime::Current()->GetHeap()->VisitObjects(CheckNoDexObjectsCallback, nullptr);
119}
120
Vladimir Markof4da6752014-08-01 19:04:18 +0100121bool ImageWriter::PrepareImageAddressSpace() {
Mathieu Chartier2d721012014-11-10 11:08:06 -0800122 target_ptr_size_ = InstructionSetPointerSize(compiler_driver_.GetInstructionSet());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800123 gc::Heap* const heap = Runtime::Current()->GetHeap();
Vladimir Markof4da6752014-08-01 19:04:18 +0100124 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700125 ScopedObjectAccess soa(Thread::Current());
Vladimir Markof4da6752014-08-01 19:04:18 +0100126 PruneNonImageClasses(); // Remove junk
127 ComputeLazyFieldsForImageClasses(); // Add useful information
Vladimir Markof4da6752014-08-01 19:04:18 +0100128 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100129 heap->CollectGarbage(false); // Remove garbage.
130
Andreas Gampedd9d0552015-03-09 12:57:41 -0700131 // Dex caches must not have their dex fields set in the image. These are memory buffers of mapped
132 // dex files.
133 //
134 // We may open them in the unstarted-runtime code for class metadata. Their fields should all be
135 // reset in PruneNonImageClasses and the objects reclaimed in the GC. Make sure that's actually
136 // true.
137 if (kIsDebugBuild) {
138 CheckNoDexObjects();
139 }
140
Vladimir Markof4da6752014-08-01 19:04:18 +0100141 if (kIsDebugBuild) {
142 ScopedObjectAccess soa(Thread::Current());
143 CheckNonImageClassesRemoved();
144 }
145
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700146 {
147 ScopedObjectAccess soa(Thread::Current());
148 CalculateNewObjectOffsets();
149 }
Vladimir Markof4da6752014-08-01 19:04:18 +0100150
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700151 // This needs to happen after CalculateNewObjectOffsets since it relies on intern_table_bytes_ and
152 // bin size sums being calculated.
153 if (!AllocMemory()) {
154 return false;
155 }
156
Vladimir Markof4da6752014-08-01 19:04:18 +0100157 return true;
158}
159
Mathieu Chartiera90c7722015-10-29 15:41:36 -0700160bool ImageWriter::Write(int image_fd,
Jeff Haodcdc85b2015-12-04 14:06:18 -0800161 const std::vector<const char*>& image_filenames,
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800162 int oat_fd,
163 const std::vector<const char*>& oat_filenames,
164 const std::string& oat_location) {
165 // If image_fd or oat_fd are not kInvalidFd then we may have empty strings in image_filenames or
166 // oat_filenames.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800167 CHECK(!image_filenames.empty());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800168 if (image_fd != kInvalidFd) {
169 CHECK_EQ(image_filenames.size(), 1u);
170 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800171 CHECK(!oat_filenames.empty());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800172 if (oat_fd != kInvalidFd) {
173 CHECK_EQ(oat_filenames.size(), 1u);
174 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800175 CHECK_EQ(image_filenames.size(), oat_filenames.size());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700176
Jeff Haodcdc85b2015-12-04 14:06:18 -0800177 size_t oat_file_offset = 0;
178
179 for (size_t i = 0; i < oat_filenames.size(); ++i) {
180 const char* oat_filename = oat_filenames[i];
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800181 std::unique_ptr<File> oat_file;
182
183 if (oat_fd != -1) {
184 if (strlen(oat_filename) == 0u) {
185 oat_file.reset(new File(oat_fd, false));
186 } else {
187 oat_file.reset(new File(oat_fd, oat_filename, false));
188 }
189 int length = oat_file->GetLength();
190 if (length < 0) {
191 PLOG(ERROR) << "Oat file has negative length " << length;
192 return false;
193 } else {
194 // Leave the fd open since dex2oat still needs to write out the oat file with the fd.
195 oat_file->DisableAutoClose();
196 }
197 } else {
198 oat_file.reset(OS::OpenFileReadWrite(oat_filename));
199 }
200 if (oat_file == nullptr) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800201 PLOG(ERROR) << "Failed to open oat file " << oat_filename;
202 return false;
203 }
204 std::string error_msg;
205 oat_file_ = OatFile::OpenReadable(oat_file.get(), oat_filename, nullptr, &error_msg);
206 if (oat_file_ == nullptr) {
207 PLOG(ERROR) << "Failed to open writable oat file " << oat_filename;
208 oat_file->Erase();
209 return false;
210 }
211 Runtime::Current()->GetOatFileManager().RegisterOatFile(
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800212 std::unique_ptr<const OatFile>(oat_file_));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700213
Jeff Haodcdc85b2015-12-04 14:06:18 -0800214 const OatHeader& oat_header = oat_file_->GetOatHeader();
215 ImageInfo& image_info = GetImageInfo(oat_filename);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700216
Jeff Haodcdc85b2015-12-04 14:06:18 -0800217 size_t oat_loaded_size = 0;
218 size_t oat_data_offset = 0;
219 ElfWriter::GetOatElfInformation(oat_file.get(), &oat_loaded_size, &oat_data_offset);
220
221 DCHECK_EQ(image_info.oat_offset_, oat_file_offset);
222 oat_file_offset += oat_loaded_size;
223
224 if (i == 0) {
225 // Primary oat file, read the trampolines.
226 image_info.oat_address_offsets_[kOatAddressInterpreterToInterpreterBridge] =
227 oat_header.GetInterpreterToInterpreterBridgeOffset();
228 image_info.oat_address_offsets_[kOatAddressInterpreterToCompiledCodeBridge] =
229 oat_header.GetInterpreterToCompiledCodeBridgeOffset();
230 image_info.oat_address_offsets_[kOatAddressJNIDlsymLookup] =
231 oat_header.GetJniDlsymLookupOffset();
232 image_info.oat_address_offsets_[kOatAddressQuickGenericJNITrampoline] =
233 oat_header.GetQuickGenericJniTrampolineOffset();
234 image_info.oat_address_offsets_[kOatAddressQuickIMTConflictTrampoline] =
235 oat_header.GetQuickImtConflictTrampolineOffset();
236 image_info.oat_address_offsets_[kOatAddressQuickResolutionTrampoline] =
237 oat_header.GetQuickResolutionTrampolineOffset();
238 image_info.oat_address_offsets_[kOatAddressQuickToInterpreterBridge] =
239 oat_header.GetQuickToInterpreterBridgeOffset();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800240 }
241
242
243 {
244 ScopedObjectAccess soa(Thread::Current());
245 CreateHeader(oat_loaded_size, oat_data_offset);
246 CopyAndFixupNativeData();
247 }
248
249 SetOatChecksumFromElfFile(oat_file.get());
250
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800251 if (oat_fd != -1) {
252 // Leave fd open for caller.
253 if (oat_file->Flush() != 0) {
254 LOG(ERROR) << "Failed to flush oat file " << oat_filename << " for " << oat_location;
255 return false;
256 }
257 } else if (oat_file->FlushCloseOrErase() != 0) {
258 LOG(ERROR) << "Failed to flush and close oat file " << oat_filename
259 << " for " << oat_location;
Jeff Haodcdc85b2015-12-04 14:06:18 -0800260 return false;
261 }
262 }
Alex Light53cb16b2014-06-12 11:26:29 -0700263
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700264 {
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700265 // TODO: heap validation can't handle these fix up passes.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800266 ScopedObjectAccess soa(Thread::Current());
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700267 Runtime::Current()->GetHeap()->DisableObjectValidation();
268 CopyAndFixupObjects();
269 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700270
Jeff Haodcdc85b2015-12-04 14:06:18 -0800271 for (size_t i = 0; i < image_filenames.size(); ++i) {
272 const char* image_filename = image_filenames[i];
273 const char* oat_filename = oat_filenames[i];
274 ImageInfo& image_info = GetImageInfo(oat_filename);
275 std::unique_ptr<File> image_file;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800276 if (image_fd != kInvalidFd) {
277 if (strlen(image_filename) == 0u) {
278 image_file.reset(new File(image_fd, unix_file::kCheckSafeUsage));
279 } else {
280 LOG(ERROR) << "image fd " << image_fd << " name " << image_filename;
281 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800282 } else {
283 image_file.reset(OS::CreateEmptyFile(image_filename));
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800284 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800285
Jeff Haodcdc85b2015-12-04 14:06:18 -0800286 if (image_file == nullptr) {
287 LOG(ERROR) << "Failed to open image file " << image_filename;
288 return false;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800289 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800290
291 if (!compile_app_image_ && fchmod(image_file->Fd(), 0644) != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800292 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
293 image_file->Erase();
294 return EXIT_FAILURE;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800295 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800296
Jeff Haodcdc85b2015-12-04 14:06:18 -0800297 std::unique_ptr<char[]> compressed_data;
298 // Image data size excludes the bitmap and the header.
299 ImageHeader* const image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
300 const size_t image_data_size = image_header->GetImageSize() - sizeof(ImageHeader);
301 char* image_data = reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader);
302 size_t data_size;
303 const char* image_data_to_write;
Nicolas Geoffray83d4d722015-12-10 08:26:32 +0000304
Jeff Haodcdc85b2015-12-04 14:06:18 -0800305 CHECK_EQ(image_header->storage_mode_, image_storage_mode_);
306 switch (image_storage_mode_) {
307 case ImageHeader::kStorageModeLZ4: {
308 size_t compressed_max_size = LZ4_compressBound(image_data_size);
309 compressed_data.reset(new char[compressed_max_size]);
310 data_size = LZ4_compress(
311 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
312 &compressed_data[0],
313 image_data_size);
314 image_data_to_write = &compressed_data[0];
315 VLOG(compiler) << "Compressed from " << image_data_size << " to " << data_size;
316 break;
317 }
318 case ImageHeader::kStorageModeUncompressed: {
319 data_size = image_data_size;
320 image_data_to_write = image_data;
321 break;
322 }
323 default: {
324 LOG(FATAL) << "Unsupported";
325 UNREACHABLE();
326 }
327 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800328
Jeff Haodcdc85b2015-12-04 14:06:18 -0800329 // Write header first, as uncompressed.
330 image_header->data_size_ = data_size;
331 if (!image_file->WriteFully(image_info.image_->Begin(), sizeof(ImageHeader))) {
332 PLOG(ERROR) << "Failed to write image file header " << image_filename;
333 image_file->Erase();
334 return false;
335 }
336
337 // Write out the image + fields + methods.
338 const bool is_compressed = compressed_data != nullptr;
339 if (!image_file->WriteFully(image_data_to_write, data_size)) {
340 PLOG(ERROR) << "Failed to write image file data " << image_filename;
341 image_file->Erase();
342 return false;
343 }
344
345 // Write out the image bitmap at the page aligned start of the image end, also uncompressed for
346 // convenience.
347 const ImageSection& bitmap_section = image_header->GetImageSection(
348 ImageHeader::kSectionImageBitmap);
349 // Align up since data size may be unaligned if the image is compressed.
350 size_t bitmap_position_in_file = RoundUp(sizeof(ImageHeader) + data_size, kPageSize);
351 if (!is_compressed) {
352 CHECK_EQ(bitmap_position_in_file, bitmap_section.Offset());
353 }
354 if (!image_file->Write(reinterpret_cast<char*>(image_info.image_bitmap_->Begin()),
355 bitmap_section.Size(),
356 bitmap_position_in_file)) {
357 PLOG(ERROR) << "Failed to write image file " << image_filename;
358 image_file->Erase();
359 return false;
360 }
361 CHECK_EQ(bitmap_position_in_file + bitmap_section.Size(),
362 static_cast<size_t>(image_file->GetLength()));
363 if (image_file->FlushCloseOrErase() != 0) {
364 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
365 return false;
366 }
Andreas Gampe4303ba92014-11-06 01:00:46 -0800367 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700368 return true;
369}
370
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700371void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700372 DCHECK(object != nullptr);
373 DCHECK_NE(offset, 0U);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800374
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800375 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700376 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700377 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700378 DCHECK(IsImageOffsetAssigned(object));
379}
380
Mathieu Chartiere401d142015-04-22 13:56:20 -0700381void ImageWriter::UpdateImageOffset(mirror::Object* obj, uintptr_t offset) {
382 DCHECK(IsImageOffsetAssigned(obj)) << obj << " " << offset;
383 obj->SetLockWord(LockWord::FromForwardingAddress(offset), false);
384 DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0u);
385}
386
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800387void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700388 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800389 DCHECK_NE(image_objects_offset_begin_, 0u);
390
Jeff Haodcdc85b2015-12-04 14:06:18 -0800391 const char* oat_filename = GetOatFilename(object);
392 ImageInfo& image_info = GetImageInfo(oat_filename);
393 size_t bin_slot_offset = image_info.bin_slot_offsets_[bin_slot.GetBin()];
Vladimir Markocf36d492015-08-12 19:27:26 +0100394 size_t new_offset = bin_slot_offset + bin_slot.GetIndex();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800395 DCHECK_ALIGNED(new_offset, kObjectAlignment);
396
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700397 SetImageOffset(object, new_offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800398 DCHECK_LT(new_offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700399}
400
Ian Rogersef7d42f2014-01-06 12:55:46 -0800401bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800402 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700403 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700404 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700405}
406
Ian Rogersef7d42f2014-01-06 12:55:46 -0800407size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700408 DCHECK(object != nullptr);
409 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700410 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700411 size_t offset = lock_word.ForwardingAddress();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800412 const char* oat_filename = GetOatFilename(object);
413 const ImageInfo& image_info = GetConstImageInfo(oat_filename);
414 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700415 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700416}
417
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800418void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
419 DCHECK(object != nullptr);
420 DCHECK(!IsImageOffsetAssigned(object));
421 DCHECK(!IsImageBinSlotAssigned(object));
422
423 // Before we stomp over the lock word, save the hash code for later.
424 Monitor::Deflate(Thread::Current(), object);;
425 LockWord lw(object->GetLockWord(false));
426 switch (lw.GetState()) {
427 case LockWord::kFatLocked: {
428 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
429 break;
430 }
431 case LockWord::kThinLocked: {
432 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
433 break;
434 }
435 case LockWord::kUnlocked:
436 // No hash, don't need to save it.
437 break;
438 case LockWord::kHashCode:
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700439 DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
440 saved_hashcode_map_.emplace(object, lw.GetHashCode());
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800441 break;
442 default:
443 LOG(FATAL) << "Unreachable.";
444 UNREACHABLE();
445 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700446 object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700447 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800448 DCHECK(IsImageBinSlotAssigned(object));
449}
450
Vladimir Marko20f85592015-03-19 10:07:02 +0000451void ImageWriter::PrepareDexCacheArraySlots() {
Vladimir Markof60c7e22015-11-23 18:05:08 +0000452 // Prepare dex cache array starts based on the ordering specified in the CompilerDriver.
Vladimir Markof60c7e22015-11-23 18:05:08 +0000453 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
454 // when AssignImageBinSlot() assigns their indexes out or order.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800455 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
456 auto it = dex_file_oat_filename_map_.find(dex_file);
457 DCHECK(it != dex_file_oat_filename_map_.end()) << dex_file->GetLocation();
458 ImageInfo& image_info = GetImageInfo(it->second);
459 image_info.dex_cache_array_starts_.Put(dex_file, image_info.bin_slot_sizes_[kBinDexCacheArray]);
460 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
461 image_info.bin_slot_sizes_[kBinDexCacheArray] += layout.Size();
462 }
Vladimir Markof60c7e22015-11-23 18:05:08 +0000463
Vladimir Marko20f85592015-03-19 10:07:02 +0000464 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700465 Thread* const self = Thread::Current();
466 ReaderMutexLock mu(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800467 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700468 mirror::DexCache* dex_cache =
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800469 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800470 if (dex_cache == nullptr || IsInBootImage(dex_cache)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700471 continue;
472 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000473 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc7853442015-03-27 14:35:38 -0700474 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
Vladimir Marko20f85592015-03-19 10:07:02 +0000475 DCHECK(layout.Valid());
Jeff Haodcdc85b2015-12-04 14:06:18 -0800476 const char* oat_filename = GetOatFilenameForDexCache(dex_cache);
477 ImageInfo& image_info = GetImageInfo(oat_filename);
478 uint32_t start = image_info.dex_cache_array_starts_.Get(dex_file);
Vladimir Marko05792b92015-08-03 11:56:49 +0100479 DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800480 AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(),
481 start + layout.TypesOffset(),
482 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100483 DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800484 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(),
485 start + layout.MethodsOffset(),
486 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100487 DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800488 AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(),
489 start + layout.FieldsOffset(),
490 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100491 DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800492 AddDexCacheArrayRelocation(dex_cache->GetStrings(), start + layout.StringsOffset(), dex_cache);
Vladimir Marko20f85592015-03-19 10:07:02 +0000493 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000494}
495
Jeff Haodcdc85b2015-12-04 14:06:18 -0800496void ImageWriter::AddDexCacheArrayRelocation(void* array, size_t offset, DexCache* dex_cache) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100497 if (array != nullptr) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800498 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -0800499 const char* oat_filename = GetOatFilenameForDexCache(dex_cache);
500 native_object_relocations_.emplace(array,
501 NativeObjectRelocation { oat_filename, offset, kNativeObjectRelocationTypeDexCacheArray });
Vladimir Marko05792b92015-08-03 11:56:49 +0100502 }
503}
504
Mathieu Chartiere401d142015-04-22 13:56:20 -0700505void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) {
506 DCHECK(arr != nullptr);
507 if (kIsDebugBuild) {
508 for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800509 ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700510 if (method != nullptr && !method->IsRuntimeMethod()) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800511 mirror::Class* klass = method->GetDeclaringClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800512 CHECK(klass == nullptr || KeepClass(klass))
513 << PrettyClass(klass) << " should be a kept class";
Mathieu Chartiere401d142015-04-22 13:56:20 -0700514 }
515 }
516 }
517 // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
518 // ArtMethods.
519 pointer_arrays_.emplace(arr, kBinArtMethodClean);
520}
521
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800522void ImageWriter::AssignImageBinSlot(mirror::Object* object) {
523 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800524 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800525
526 // The magic happens here. We segregate objects into different bins based
527 // on how likely they are to get dirty at runtime.
528 //
529 // Likely-to-dirty objects get packed together into the same bin so that
530 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
531 // maximized.
532 //
533 // This means more pages will stay either clean or shared dirty (with zygote) and
534 // the app will use less of its own (private) memory.
535 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000536 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800537
538 if (kBinObjects) {
539 //
540 // Changing the bin of an object is purely a memory-use tuning.
541 // It has no change on runtime correctness.
542 //
543 // Memory analysis has determined that the following types of objects get dirtied
544 // the most:
545 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000546 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
547 // a fixed layout which helps improve generated code (using PC-relative addressing),
548 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
549 // Since these arrays are huge, most pages do not overlap other objects and it's not
550 // really important where they are for the clean/dirty separation. Due to their
Vladimir Marko05792b92015-08-03 11:56:49 +0100551 // special PC-relative addressing, we arbitrarily keep them at the end.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800552 // * Class'es which are verified [their clinit runs only at runtime]
553 // - classes in general [because their static fields get overwritten]
554 // - initialized classes with all-final statics are unlikely to be ever dirty,
555 // so bin them separately
556 // * Art Methods that are:
557 // - native [their native entry point is not looked up until runtime]
558 // - have declaring classes that aren't initialized
559 // [their interpreter/quick entry points are trampolines until the class
560 // becomes initialized]
561 //
562 // We also assume the following objects get dirtied either never or extremely rarely:
563 // * Strings (they are immutable)
564 // * Art methods that aren't native and have initialized declared classes
565 //
566 // We assume that "regular" bin objects are highly unlikely to become dirtied,
567 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
568 //
569 if (object->IsClass()) {
570 bin = kBinClassVerified;
571 mirror::Class* klass = object->AsClass();
572
Mathieu Chartiere401d142015-04-22 13:56:20 -0700573 // Add non-embedded vtable to the pointer array table if there is one.
574 auto* vtable = klass->GetVTable();
575 if (vtable != nullptr) {
576 AddMethodPointerArray(vtable);
577 }
578 auto* iftable = klass->GetIfTable();
579 if (iftable != nullptr) {
580 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
581 if (iftable->GetMethodArrayCount(i) > 0) {
582 AddMethodPointerArray(iftable->GetMethodArray(i));
583 }
584 }
585 }
586
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800587 if (klass->GetStatus() == Class::kStatusInitialized) {
588 bin = kBinClassInitialized;
589
590 // If the class's static fields are all final, put it into a separate bin
591 // since it's very likely it will stay clean.
592 uint32_t num_static_fields = klass->NumStaticFields();
593 if (num_static_fields == 0) {
594 bin = kBinClassInitializedFinalStatics;
595 } else {
596 // Maybe all the statics are final?
597 bool all_final = true;
598 for (uint32_t i = 0; i < num_static_fields; ++i) {
599 ArtField* field = klass->GetStaticField(i);
600 if (!field->IsFinal()) {
601 all_final = false;
602 break;
603 }
604 }
605
606 if (all_final) {
607 bin = kBinClassInitializedFinalStatics;
608 }
609 }
610 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800611 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
612 bin = kBinString; // Strings are almost always immutable (except for object header).
613 } // else bin = kBinRegular
614 }
615
Jeff Haodcdc85b2015-12-04 14:06:18 -0800616 const char* oat_filename = GetOatFilename(object);
617 ImageInfo& image_info = GetImageInfo(oat_filename);
618
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800619 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Jeff Haodcdc85b2015-12-04 14:06:18 -0800620 current_offset = image_info.bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
621 // Move the current bin size up to accommodate the object we just assigned a bin slot.
622 image_info.bin_slot_sizes_[bin] += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800623
624 BinSlot new_bin_slot(bin, current_offset);
625 SetImageBinSlot(object, new_bin_slot);
626
Jeff Haodcdc85b2015-12-04 14:06:18 -0800627 ++image_info.bin_slot_count_[bin];
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800628
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800629 // Grow the image closer to the end by the object we just assigned.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800630 image_info.image_end_ += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800631}
632
Mathieu Chartiere401d142015-04-22 13:56:20 -0700633bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
634 if (m->IsNative()) {
635 return true;
636 }
637 mirror::Class* declaring_class = m->GetDeclaringClass();
638 // Initialized is highly unlikely to dirty since there's no entry points to mutate.
639 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
640}
641
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800642bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
643 DCHECK(object != nullptr);
644
645 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
646 // If it's in some other state, then we haven't yet assigned an image bin slot.
647 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
648 return false;
649 } else if (kIsDebugBuild) {
650 LockWord lock_word = object->GetLockWord(false);
651 size_t offset = lock_word.ForwardingAddress();
652 BinSlot bin_slot(offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800653 const char* oat_filename = GetOatFilename(object);
654 const ImageInfo& image_info = GetConstImageInfo(oat_filename);
655 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()])
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800656 << "bin slot offset should not exceed the size of that bin";
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800657 }
658 return true;
659}
660
661ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
662 DCHECK(object != nullptr);
663 DCHECK(IsImageBinSlotAssigned(object));
664
665 LockWord lock_word = object->GetLockWord(false);
666 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
667 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
668
669 BinSlot bin_slot(static_cast<uint32_t>(offset));
Jeff Haodcdc85b2015-12-04 14:06:18 -0800670 const char* oat_filename = GetOatFilename(object);
671 const ImageInfo& image_info = GetConstImageInfo(oat_filename);
672 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()]);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800673
674 return bin_slot;
675}
676
Brian Carlstrom7940e442013-07-12 13:46:57 -0700677bool ImageWriter::AllocMemory() {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800678 for (const char* oat_filename : oat_filenames_) {
679 ImageInfo& image_info = GetImageInfo(oat_filename);
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800680 ImageSection unused_sections[ImageHeader::kSectionCount];
681 const size_t length = RoundUp(
682 image_info.CreateImageSections(target_ptr_size_, unused_sections),
683 kPageSize);
684
Jeff Haodcdc85b2015-12-04 14:06:18 -0800685 std::string error_msg;
686 image_info.image_.reset(MemMap::MapAnonymous("image writer image",
687 nullptr,
688 length,
689 PROT_READ | PROT_WRITE,
690 false,
691 false,
692 &error_msg));
693 if (UNLIKELY(image_info.image_.get() == nullptr)) {
694 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
695 return false;
696 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700697
Jeff Haodcdc85b2015-12-04 14:06:18 -0800698 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
699 CHECK_LE(image_info.image_end_, length);
700 image_info.image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
701 "image bitmap", image_info.image_->Begin(), RoundUp(image_info.image_end_, kPageSize)));
702 if (image_info.image_bitmap_.get() == nullptr) {
703 LOG(ERROR) << "Failed to allocate memory for image bitmap";
704 return false;
705 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700706 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700707 return true;
708}
709
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700710class ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
711 public:
712 bool Visit(Class* c) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
713 StackHandleScope<1> hs(Thread::Current());
714 mirror::Class::ComputeName(hs.NewHandle(c));
715 return true;
716 }
717};
718
Brian Carlstrom7940e442013-07-12 13:46:57 -0700719void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700720 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700721 ComputeLazyFieldsForClassesVisitor visitor;
722 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700723}
724
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800725static bool IsBootClassLoaderClass(mirror::Class* klass) SHARED_REQUIRES(Locks::mutator_lock_) {
726 return klass->GetClassLoader() == nullptr;
727}
728
729bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
730 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
731}
732
733bool ImageWriter::ContainsBootClassLoaderNonImageClass(mirror::Class* klass) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800734 bool early_exit = false;
735 std::unordered_set<mirror::Class*> visited;
736 return ContainsBootClassLoaderNonImageClassInternal(klass, &early_exit, &visited);
737}
738
739bool ImageWriter::ContainsBootClassLoaderNonImageClassInternal(
740 mirror::Class* klass,
741 bool* early_exit,
742 std::unordered_set<mirror::Class*>* visited) {
743 DCHECK(early_exit != nullptr);
744 DCHECK(visited != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800745 DCHECK(compile_app_image_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700746 if (klass == nullptr) {
747 return false;
748 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800749 auto found = prune_class_memo_.find(klass);
750 if (found != prune_class_memo_.end()) {
751 // Already computed, return the found value.
752 return found->second;
753 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800754 // Circular dependencies, return false but do not store the result in the memoization table.
755 if (visited->find(klass) != visited->end()) {
756 *early_exit = true;
757 return false;
758 }
759 visited->emplace(klass);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800760 bool result = IsBootClassLoaderNonImageClass(klass);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800761 bool my_early_exit = false; // Only for ourselves, ignore caller.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800762 // Remove classes that failed to verify since we don't want to have java.lang.VerifyError in the
763 // app image.
764 if (klass->GetStatus() == mirror::Class::kStatusError) {
765 result = true;
766 } else {
767 CHECK(klass->GetVerifyError() == nullptr) << PrettyClass(klass);
768 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800769 if (!result) {
770 // Check interfaces since these wont be visited through VisitReferences.)
771 mirror::IfTable* if_table = klass->GetIfTable();
772 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800773 result = result || ContainsBootClassLoaderNonImageClassInternal(
774 if_table->GetInterface(i),
775 &my_early_exit,
776 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800777 }
778 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800779 if (klass->IsObjectArrayClass()) {
780 result = result || ContainsBootClassLoaderNonImageClassInternal(
781 klass->GetComponentType(),
782 &my_early_exit,
783 visited);
784 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800785 // Check static fields and their classes.
786 size_t num_static_fields = klass->NumReferenceStaticFields();
787 if (num_static_fields != 0 && klass->IsResolved()) {
788 // Presumably GC can happen when we are cross compiling, it should not cause performance
789 // problems to do pointer size logic.
790 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
791 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
792 for (size_t i = 0u; i < num_static_fields; ++i) {
793 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
794 if (ref != nullptr) {
795 if (ref->IsClass()) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800796 result = result ||
797 ContainsBootClassLoaderNonImageClassInternal(
798 ref->AsClass(),
799 &my_early_exit,
800 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800801 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800802 result = result ||
803 ContainsBootClassLoaderNonImageClassInternal(
804 ref->GetClass(),
805 &my_early_exit,
806 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800807 }
808 field_offset = MemberOffset(field_offset.Uint32Value() +
809 sizeof(mirror::HeapReference<mirror::Object>));
810 }
811 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800812 result = result ||
813 ContainsBootClassLoaderNonImageClassInternal(
814 klass->GetSuperClass(),
815 &my_early_exit,
816 visited);
817 // Erase the element we stored earlier since we are exiting the function.
818 auto it = visited->find(klass);
819 DCHECK(it != visited->end());
820 visited->erase(it);
821 // Only store result if it is true or none of the calls early exited due to circular
822 // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
823 // a child call and we can remember the result.
824 if (result == true || !my_early_exit || visited->empty()) {
825 prune_class_memo_[klass] = result;
826 }
827 *early_exit |= my_early_exit;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800828 return result;
829}
830
831bool ImageWriter::KeepClass(Class* klass) {
832 if (klass == nullptr) {
833 return false;
834 }
835 if (compile_app_image_) {
836 // For app images, we need to prune boot loader classes that are not in the boot image since
837 // these may have already been loaded when the app image is loaded.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800838 // Keep classes in the boot image space since we don't want to re-resolve these.
839 return Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass) ||
840 !ContainsBootClassLoaderNonImageClass(klass);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800841 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700842 std::string temp;
843 return compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700844}
845
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700846class NonImageClassesVisitor : public ClassVisitor {
847 public:
848 explicit NonImageClassesVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
849
850 bool Visit(Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800851 if (!image_writer_->KeepClass(klass)) {
852 classes_to_prune_.insert(klass);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700853 }
854 return true;
855 }
856
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800857 std::unordered_set<mirror::Class*> classes_to_prune_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700858 ImageWriter* const image_writer_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700859};
860
861void ImageWriter::PruneNonImageClasses() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700862 Runtime* runtime = Runtime::Current();
863 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700864 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700865
866 // Make a list of classes we would like to prune.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700867 NonImageClassesVisitor visitor(this);
868 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700869
870 // Remove the undesired classes from the class roots.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800871 for (mirror::Class* klass : visitor.classes_to_prune_) {
872 std::string temp;
873 const char* name = klass->GetDescriptor(&temp);
874 VLOG(compiler) << "Pruning class " << name;
875 if (!compile_app_image_) {
876 DCHECK(IsBootClassLoaderClass(klass));
877 }
878 bool result = class_linker->RemoveClass(name, klass->GetClassLoader());
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800879 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700880 }
881
882 // Clear references to removed classes from the DexCaches.
Vladimir Marko05792b92015-08-03 11:56:49 +0100883 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700884
885 ScopedAssertNoThreadSuspension sa(self, __FUNCTION__);
886 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); // For ClassInClassTable
887 ReaderMutexLock mu2(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800888 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
889 mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700890 if (dex_cache == nullptr) {
891 continue;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700892 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700893 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
894 Class* klass = dex_cache->GetResolvedType(i);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800895 if (klass != nullptr && !KeepClass(klass)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700896 dex_cache->SetResolvedType(i, nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700897 }
898 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100899 ArtMethod** resolved_methods = dex_cache->GetResolvedMethods();
900 for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) {
901 ArtMethod* method =
902 mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800903 DCHECK(method != nullptr) << "Expected resolution method instead of null method";
904 mirror::Class* declaring_class = method->GetDeclaringClass();
905 // Miranda methods may be held live by a class which was not an image class but have a
906 // declaring class which is an image class. Set it to the resolution method to be safe and
907 // prevent dangling pointers.
908 if (method->IsMiranda() || !KeepClass(declaring_class)) {
909 mirror::DexCache::SetElementPtrSize(resolved_methods,
910 i,
911 resolution_method,
912 target_ptr_size_);
913 } else {
914 // Check that the class is still in the classes table.
915 DCHECK(class_linker->ClassInClassTable(declaring_class)) << "Class "
916 << PrettyClass(declaring_class) << " not in class linker table";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700917 }
918 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800919 ArtField** resolved_fields = dex_cache->GetResolvedFields();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700920 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800921 ArtField* field = mirror::DexCache::GetElementPtrSize(resolved_fields, i, target_ptr_size_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800922 if (field != nullptr && !KeepClass(field->GetDeclaringClass())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700923 dex_cache->SetResolvedField(i, nullptr, target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700924 }
925 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700926 // Clean the dex field. It might have been populated during the initialization phase, but
927 // contains data only valid during a real run.
928 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700929 }
Andreas Gampe8ac75952015-06-02 21:01:45 -0700930
931 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
932 class_linker->DropFindArrayClassCache();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800933
934 // Clear to save RAM.
935 prune_class_memo_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700936}
937
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800938void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700939 if (compiler_driver_.GetImageClasses() != nullptr) {
940 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700941 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700942 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700943}
944
945void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
946 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800947 if (obj->IsClass() && !image_writer->IsInBootImage(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700948 Class* klass = obj->AsClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800949 if (!image_writer->KeepClass(klass)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700950 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700951 std::string temp;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800952 CHECK(image_writer->KeepClass(klass)) << klass->GetDescriptor(&temp)
953 << " " << PrettyDescriptor(klass);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700954 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700955 }
956}
957
958void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700959 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700960 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700961 for (const std::string& image_class : *image_classes) {
962 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700963 }
964}
965
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800966mirror::String* ImageWriter::FindInternedString(mirror::String* string) {
967 Thread* const self = Thread::Current();
968 for (auto& pair : image_info_map_) {
969 const ImageInfo& image_info = pair.second;
970 mirror::String* const found = image_info.intern_table_->LookupStrong(self, string);
971 DCHECK(image_info.intern_table_->LookupWeak(self, string) == nullptr)
972 << string->ToModifiedUtf8();
973 if (found != nullptr) {
974 return found;
975 }
976 }
977 if (compile_app_image_) {
978 Runtime* const runtime = Runtime::Current();
979 mirror::String* found = runtime->GetInternTable()->LookupStrong(self, string);
980 // If we found it in the runtime intern table it could either be in the boot image or interned
981 // during app image compilation. If it was in the boot image return that, otherwise return null
982 // since it belongs to another image space.
983 if (found != nullptr && runtime->GetHeap()->ObjectIsInBootImageSpace(found)) {
984 return found;
985 }
986 DCHECK(runtime->GetInternTable()->LookupWeak(self, string) == nullptr)
987 << string->ToModifiedUtf8();
988 }
989 return nullptr;
990}
991
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800992void ImageWriter::CalculateObjectBinSlots(Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700993 DCHECK(obj != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700994 // if it is a string, we want to intern it if its not interned.
995 if (obj->GetClass()->IsStringClass()) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -0800996 const char* oat_filename = GetOatFilename(obj);
997 ImageInfo& image_info = GetImageInfo(oat_filename);
998
Brian Carlstrom7940e442013-07-12 13:46:57 -0700999 // we must be an interned string that was forward referenced and already assigned
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001000 if (IsImageBinSlotAssigned(obj)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001001 DCHECK_EQ(obj, FindInternedString(obj->AsString()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001002 return;
1003 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001004 // Need to check if the string is already interned in another image info so that we don't have
1005 // the intern tables of two different images contain the same string.
1006 mirror::String* interned = FindInternedString(obj->AsString());
1007 if (interned == nullptr) {
1008 // Not in another image space, insert to our table.
1009 interned = image_info.intern_table_->InternStrongImageString(obj->AsString());
1010 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001011 if (obj != interned) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001012 if (!IsImageBinSlotAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001013 // interned obj is after us, allocate its location early
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001014 AssignImageBinSlot(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001015 }
1016 // point those looking for this object to the interned version.
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001017 SetImageBinSlot(obj, GetImageBinSlot(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001018 return;
1019 }
1020 // else (obj == interned), nothing to do but fall through to the normal case
1021 }
1022
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001023 AssignImageBinSlot(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001024}
1025
Jeff Haodcdc85b2015-12-04 14:06:18 -08001026ObjectArray<Object>* ImageWriter::CreateImageRoots(const char* oat_filename) const {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001027 Runtime* runtime = Runtime::Current();
1028 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001029 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001030 StackHandleScope<3> hs(self);
1031 Handle<Class> object_array_class(hs.NewHandle(
1032 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001033
Jeff Haodcdc85b2015-12-04 14:06:18 -08001034 std::unordered_set<const DexFile*> image_dex_files;
1035 for (auto& pair : dex_file_oat_filename_map_) {
1036 const DexFile* image_dex_file = pair.first;
1037 const char* image_oat_filename = pair.second;
1038 if (strcmp(oat_filename, image_oat_filename) == 0) {
1039 image_dex_files.insert(image_dex_file);
1040 }
1041 }
1042
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001043 // build an Object[] of all the DexCaches used in the source_space_.
1044 // Since we can't hold the dex lock when allocating the dex_caches
1045 // ObjectArray, we lock the dex lock twice, first to get the number
1046 // of dex caches first and then lock it again to copy the dex
1047 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001048 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001049 {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001050 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001051 // Count number of dex caches not in the boot image.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001052 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1053 mirror::DexCache* dex_cache =
1054 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001055 const DexFile* dex_file = dex_cache->GetDexFile();
1056 if (!IsInBootImage(dex_cache)) {
1057 dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1058 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001059 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001060 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001061 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001062 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001063 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
1064 {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001065 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001066 size_t non_image_dex_caches = 0;
1067 // Re-count number of non image dex caches.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001068 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1069 mirror::DexCache* dex_cache =
1070 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001071 const DexFile* dex_file = dex_cache->GetDexFile();
1072 if (!IsInBootImage(dex_cache)) {
1073 non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1074 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001075 }
1076 CHECK_EQ(dex_cache_count, non_image_dex_caches)
1077 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001078 size_t i = 0;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001079 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1080 mirror::DexCache* dex_cache =
1081 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001082 const DexFile* dex_file = dex_cache->GetDexFile();
1083 if (!IsInBootImage(dex_cache) && image_dex_files.find(dex_file) != image_dex_files.end()) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001084 dex_caches->Set<false>(i, dex_cache);
1085 ++i;
1086 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001087 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001088 }
1089
1090 // build an Object[] of the roots needed to restore the runtime
Mathieu Chartiere401d142015-04-22 13:56:20 -07001091 auto image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001092 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001093 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001094 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001095 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001096 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001097 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001098 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001099}
1100
Mathieu Chartier590fee92013-09-13 13:46:47 -07001101// Walk instance fields of the given Class. Separate function to allow recursion on the super
1102// class.
1103void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
1104 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001105 StackHandleScope<1> hs(Thread::Current());
1106 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1107 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001108 if (super != nullptr) {
1109 WalkInstanceFields(obj, super);
1110 }
1111 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001112 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Marko76649e82014-11-10 18:32:59 +00001113 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001114 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001115 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001116 if (value != nullptr) {
1117 WalkFieldsInOrder(value);
1118 }
Vladimir Marko76649e82014-11-10 18:32:59 +00001119 field_offset = MemberOffset(field_offset.Uint32Value() +
1120 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001121 }
1122}
1123
1124// For an unvisited object, visit it then all its children found via fields.
1125void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001126 if (IsInBootImage(obj)) {
1127 // Object is in the image, don't need to fix it up.
1128 return;
1129 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001130 // Use our own visitor routine (instead of GC visitor) to get better locality between
1131 // an object and its fields
1132 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001133 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001134 StackHandleScope<2> hs(Thread::Current());
1135 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
1136 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001137 // visit the object itself.
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001138 CalculateObjectBinSlots(h_obj.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001139 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001140 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001141 if (h_obj->IsClass()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001142 size_t num_reference_static_fields = klass->NumReferenceStaticFields();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001143 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001144 for (size_t i = 0; i < num_reference_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001145 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001146 if (value != nullptr) {
1147 WalkFieldsInOrder(value);
1148 }
Vladimir Marko76649e82014-11-10 18:32:59 +00001149 field_offset = MemberOffset(field_offset.Uint32Value() +
1150 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001151 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001152 // Visit and assign offsets for fields and field arrays.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001153 auto* as_klass = h_obj->AsClass();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001154 mirror::DexCache* dex_cache = as_klass->GetDexCache();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001155 DCHECK_NE(klass->GetStatus(), mirror::Class::kStatusError);
1156 if (compile_app_image_) {
1157 // Extra sanity, no boot loader classes should be left!
1158 CHECK(!IsBootClassLoaderClass(as_klass)) << PrettyClass(as_klass);
1159 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001160 LengthPrefixedArray<ArtField>* fields[] = {
1161 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
1162 };
Jeff Haodcdc85b2015-12-04 14:06:18 -08001163 const char* oat_file = GetOatFilenameForDexCache(dex_cache);
1164 ImageInfo& image_info = GetImageInfo(oat_file);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001165 {
1166 // Note: This table is only accessed from the image writer, so the lock is technically
1167 // unnecessary.
1168 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1169 // Insert in the class table for this iamge.
1170 image_info.class_table_->Insert(as_klass);
1171 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001172 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1173 // Total array length including header.
1174 if (cur_fields != nullptr) {
1175 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
1176 // Forward the entire array at once.
1177 auto it = native_object_relocations_.find(cur_fields);
1178 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
1179 << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001180 size_t& offset = image_info.bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001181 DCHECK(!IsInBootImage(cur_fields));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001182 native_object_relocations_.emplace(cur_fields,
1183 NativeObjectRelocation {oat_file, offset, kNativeObjectRelocationTypeArtFieldArray });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001184 offset += header_size;
1185 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +01001186 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001187 // Need to forward arrays separate of fields.
1188 ArtField* field = &cur_fields->At(i);
1189 auto it2 = native_object_relocations_.find(field);
1190 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
1191 << " already assigned " << PrettyField(field) << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001192 DCHECK(!IsInBootImage(field));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001193 native_object_relocations_.emplace(field,
1194 NativeObjectRelocation {oat_file, offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001195 offset += sizeof(ArtField);
1196 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001197 }
1198 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001199 // Visit and assign offsets for methods.
Alex Lighte64300b2015-12-15 15:02:47 -08001200 size_t num_methods = as_klass->NumMethods();
1201 if (num_methods != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001202 bool any_dirty = false;
Alex Lighte64300b2015-12-15 15:02:47 -08001203 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1204 if (WillMethodBeDirty(&m)) {
1205 any_dirty = true;
1206 break;
1207 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001208 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001209 NativeObjectRelocationType type = any_dirty
1210 ? kNativeObjectRelocationTypeArtMethodDirty
1211 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001212 Bin bin_type = BinTypeForNativeRelocationType(type);
1213 // Forward the entire array at once, but header first.
Alex Lighte64300b2015-12-15 15:02:47 -08001214 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1215 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01001216 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1217 method_size,
1218 method_alignment);
Alex Lighte64300b2015-12-15 15:02:47 -08001219 LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001220 auto it = native_object_relocations_.find(array);
Alex Lighte64300b2015-12-15 15:02:47 -08001221 CHECK(it == native_object_relocations_.end())
1222 << "Method array " << array << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001223 size_t& offset = image_info.bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001224 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001225 native_object_relocations_.emplace(array,
1226 NativeObjectRelocation {
1227 oat_file,
1228 offset,
1229 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty
1230 : kNativeObjectRelocationTypeArtMethodArrayClean });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001231 offset += header_size;
Alex Lighte64300b2015-12-15 15:02:47 -08001232 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001233 AssignMethodOffset(&m, type, oat_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001234 }
Alex Lighte64300b2015-12-15 15:02:47 -08001235 (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001236 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001237 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001238 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001239 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001240 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001241 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001242 mirror::Object* value = obj_array->Get(i);
1243 if (value != nullptr) {
1244 WalkFieldsInOrder(value);
1245 }
1246 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001247 } else if (h_obj->IsClassLoader()) {
1248 // Register the class loader if it has a class table.
1249 // The fake boot class loader should not get registered and we should end up with only one
1250 // class loader.
1251 mirror::ClassLoader* class_loader = h_obj->AsClassLoader();
1252 if (class_loader->GetClassTable() != nullptr) {
1253 class_loaders_.insert(class_loader);
1254 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001255 }
1256 }
1257}
1258
Jeff Haodcdc85b2015-12-04 14:06:18 -08001259void ImageWriter::AssignMethodOffset(ArtMethod* method,
1260 NativeObjectRelocationType type,
1261 const char* oat_filename) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001262 DCHECK(!IsInBootImage(method));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001263 auto it = native_object_relocations_.find(method);
1264 CHECK(it == native_object_relocations_.end()) << "Method " << method << " already assigned "
Mathieu Chartiere401d142015-04-22 13:56:20 -07001265 << PrettyMethod(method);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001266 ImageInfo& image_info = GetImageInfo(oat_filename);
1267 size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
1268 native_object_relocations_.emplace(method, NativeObjectRelocation { oat_filename, offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001269 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001270}
1271
Mathieu Chartier590fee92013-09-13 13:46:47 -07001272void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
1273 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1274 DCHECK(writer != nullptr);
1275 writer->WalkFieldsInOrder(obj);
1276}
1277
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001278void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
1279 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1280 DCHECK(writer != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001281 if (!writer->IsInBootImage(obj)) {
1282 writer->UnbinObjectsIntoOffset(obj);
1283 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001284}
1285
1286void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001287 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001288 CHECK(obj != nullptr);
1289
1290 // We know the bin slot, and the total bin sizes for all objects by now,
1291 // so calculate the object's final image offset.
1292
1293 DCHECK(IsImageBinSlotAssigned(obj));
1294 BinSlot bin_slot = GetImageBinSlot(obj);
1295 // Change the lockword from a bin slot into an offset
1296 AssignImageOffset(obj, bin_slot);
1297}
1298
Vladimir Markof4da6752014-08-01 19:04:18 +01001299void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001300 Thread* const self = Thread::Current();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001301 StackHandleScopeCollection handles(self);
1302 std::vector<Handle<ObjectArray<Object>>> image_roots;
1303 for (const char* oat_filename : oat_filenames_) {
1304 std::string image_filename = oat_filename;
1305 image_roots.push_back(handles.NewHandle(CreateImageRoots(image_filename.c_str())));
1306 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001307
Mathieu Chartiere401d142015-04-22 13:56:20 -07001308 auto* runtime = Runtime::Current();
1309 auto* heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001310
Mathieu Chartier31e89252013-08-28 11:29:12 -07001311 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001312 // know where image_roots is going to end up
Jeff Haodcdc85b2015-12-04 14:06:18 -08001313 image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001314
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001315 // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
1316 heap->VisitObjects(WalkFieldsCallback, this);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001317 // Write the image runtime methods.
1318 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1319 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1320 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
1321 image_methods_[ImageHeader::kCalleeSaveMethod] = runtime->GetCalleeSaveMethod(Runtime::kSaveAll);
1322 image_methods_[ImageHeader::kRefsOnlySaveMethod] =
1323 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly);
1324 image_methods_[ImageHeader::kRefsAndArgsSaveMethod] =
1325 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001326
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001327 // Add room for fake length prefixed array for holding the image methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001328 const auto image_method_type = kNativeObjectRelocationTypeArtMethodArrayClean;
1329 auto it = native_object_relocations_.find(&image_method_array_);
1330 CHECK(it == native_object_relocations_.end());
Jeff Haodcdc85b2015-12-04 14:06:18 -08001331 ImageInfo& default_image_info = GetImageInfo(default_oat_filename_);
1332 size_t& offset =
1333 default_image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(image_method_type)];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001334 if (!compile_app_image_) {
1335 native_object_relocations_.emplace(&image_method_array_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001336 NativeObjectRelocation { default_oat_filename_, offset, image_method_type });
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001337 }
Vladimir Marko14632852015-08-17 12:07:23 +01001338 size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001339 const size_t array_size = LengthPrefixedArray<ArtMethod>::ComputeSize(
Vladimir Marko14632852015-08-17 12:07:23 +01001340 0, ArtMethod::Size(target_ptr_size_), method_alignment);
Vladimir Markocf36d492015-08-12 19:27:26 +01001341 CHECK_ALIGNED_PARAM(array_size, method_alignment);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001342 offset += array_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001343 for (auto* m : image_methods_) {
1344 CHECK(m != nullptr);
1345 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001346 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1347 if (!IsInBootImage(m)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001348 AssignMethodOffset(m, kNativeObjectRelocationTypeArtMethodClean, default_oat_filename_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001349 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001350 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001351 // Calculate size of the dex cache arrays slot and prepare offsets.
1352 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001353
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001354 // Calculate the sizes of the intern tables and class tables.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001355 for (const char* oat_filename : oat_filenames_) {
1356 ImageInfo& image_info = GetImageInfo(oat_filename);
1357 // Calculate how big the intern table will be after being serialized.
1358 InternTable* const intern_table = image_info.intern_table_.get();
1359 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
1360 image_info.intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001361 // Calculate the size of the class table.
1362 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
1363 image_info.class_table_bytes_ += image_info.class_table_->WriteToMemory(nullptr);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001364 }
1365
Vladimir Markocf36d492015-08-12 19:27:26 +01001366 // Calculate bin slot offsets.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001367 for (const char* oat_filename : oat_filenames_) {
1368 ImageInfo& image_info = GetImageInfo(oat_filename);
1369 size_t bin_offset = image_objects_offset_begin_;
1370 for (size_t i = 0; i != kBinSize; ++i) {
1371 image_info.bin_slot_offsets_[i] = bin_offset;
1372 bin_offset += image_info.bin_slot_sizes_[i];
1373 if (i == kBinArtField) {
1374 static_assert(kBinArtField + 1 == kBinArtMethodClean, "Methods follow fields.");
1375 static_assert(alignof(ArtField) == 4u, "ArtField alignment is 4.");
1376 DCHECK_ALIGNED(bin_offset, 4u);
1377 DCHECK(method_alignment == 4u || method_alignment == 8u);
1378 bin_offset = RoundUp(bin_offset, method_alignment);
1379 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001380 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001381 // NOTE: There may be additional padding between the bin slots and the intern table.
1382 DCHECK_EQ(image_info.image_end_,
1383 GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_);
Vladimir Marko20f85592015-03-19 10:07:02 +00001384 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001385
Jeff Haodcdc85b2015-12-04 14:06:18 -08001386 // Calculate image offsets.
1387 size_t image_offset = 0;
1388 for (const char* oat_filename : oat_filenames_) {
1389 ImageInfo& image_info = GetImageInfo(oat_filename);
1390 image_info.image_begin_ = global_image_begin_ + image_offset;
1391 image_info.image_offset_ = image_offset;
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001392 ImageSection unused_sections[ImageHeader::kSectionCount];
1393 image_info.image_size_ = RoundUp(
1394 image_info.CreateImageSections(target_ptr_size_, unused_sections),
1395 kPageSize);
1396 // There should be no gaps until the next image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001397 image_offset += image_info.image_size_;
1398 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001399
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001400 // Transform each object's bin slot into an offset which will be used to do the final copy.
1401 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001402
Jeff Haodcdc85b2015-12-04 14:06:18 -08001403 // DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001404
Jeff Haodcdc85b2015-12-04 14:06:18 -08001405 size_t i = 0;
1406 for (const char* oat_filename : oat_filenames_) {
1407 ImageInfo& image_info = GetImageInfo(oat_filename);
1408 image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
1409 i++;
1410 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001411
Mathieu Chartiere401d142015-04-22 13:56:20 -07001412 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001413 for (auto& pair : native_object_relocations_) {
1414 NativeObjectRelocation& relocation = pair.second;
1415 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001416 ImageInfo& image_info = GetImageInfo(relocation.oat_filename);
1417 relocation.offset += image_info.bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001418 }
1419
Jeff Haodcdc85b2015-12-04 14:06:18 -08001420 // Note that image_info.image_end_ is left at end of used mirror object section.
Vladimir Markof4da6752014-08-01 19:04:18 +01001421}
1422
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001423size_t ImageWriter::ImageInfo::CreateImageSections(size_t target_ptr_size,
1424 ImageSection* out_sections) const {
1425 DCHECK(out_sections != nullptr);
1426 // Objects section
1427 auto* objects_section = &out_sections[ImageHeader::kSectionObjects];
1428 *objects_section = ImageSection(0u, image_end_);
1429 size_t cur_pos = objects_section->End();
1430 // Add field section.
1431 auto* field_section = &out_sections[ImageHeader::kSectionArtFields];
1432 *field_section = ImageSection(cur_pos, bin_slot_sizes_[kBinArtField]);
1433 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
1434 cur_pos = field_section->End();
1435 // Round up to the alignment the required by the method section.
1436 cur_pos = RoundUp(cur_pos, ArtMethod::Alignment(target_ptr_size));
1437 // Add method section.
1438 auto* methods_section = &out_sections[ImageHeader::kSectionArtMethods];
1439 *methods_section = ImageSection(cur_pos,
1440 bin_slot_sizes_[kBinArtMethodClean] +
1441 bin_slot_sizes_[kBinArtMethodDirty]);
1442 CHECK_EQ(bin_slot_offsets_[kBinArtMethodClean], methods_section->Offset());
1443 cur_pos = methods_section->End();
1444 // Add dex cache arrays section.
1445 auto* dex_cache_arrays_section = &out_sections[ImageHeader::kSectionDexCacheArrays];
1446 *dex_cache_arrays_section = ImageSection(cur_pos, bin_slot_sizes_[kBinDexCacheArray]);
1447 CHECK_EQ(bin_slot_offsets_[kBinDexCacheArray], dex_cache_arrays_section->Offset());
1448 cur_pos = dex_cache_arrays_section->End();
1449 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
1450 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1451 // Calculate the size of the interned strings.
1452 auto* interned_strings_section = &out_sections[ImageHeader::kSectionInternedStrings];
1453 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1454 cur_pos = interned_strings_section->End();
1455 // Round up to the alignment the class table expects. See HashSet::WriteToMemory.
1456 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1457 // Calculate the size of the class table section.
1458 auto* class_table_section = &out_sections[ImageHeader::kSectionClassTable];
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001459 *class_table_section = ImageSection(cur_pos, class_table_bytes_);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001460 cur_pos = class_table_section->End();
1461 // Image end goes right before the start of the image bitmap.
1462 return cur_pos;
1463}
1464
Vladimir Markof4da6752014-08-01 19:04:18 +01001465void ImageWriter::CreateHeader(size_t oat_loaded_size, size_t oat_data_offset) {
1466 CHECK_NE(0U, oat_loaded_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001467 const char* oat_filename = oat_file_->GetLocation().c_str();
1468 ImageInfo& image_info = GetImageInfo(oat_filename);
1469 const uint8_t* oat_file_begin = GetOatFileBegin(oat_filename);
Ian Rogers13735952014-10-08 12:43:28 -07001470 const uint8_t* oat_file_end = oat_file_begin + oat_loaded_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001471 image_info.oat_data_begin_ = const_cast<uint8_t*>(oat_file_begin) + oat_data_offset;
1472 const uint8_t* oat_data_end = image_info.oat_data_begin_ + oat_file_->Size();
1473 image_info.oat_size_ = oat_file_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001474
1475 // Create the image sections.
1476 ImageSection sections[ImageHeader::kSectionCount];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001477 const size_t image_end = image_info.CreateImageSections(target_ptr_size_, sections);
1478
Mathieu Chartiere401d142015-04-22 13:56:20 -07001479 // Finally bitmap section.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001480 const size_t bitmap_bytes = image_info.image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001481 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001482 *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001483 if (VLOG_IS_ON(compiler)) {
1484 LOG(INFO) << "Creating header for " << oat_filename;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001485 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001486 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001487 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1488 ++idx;
1489 }
1490 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001491 LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
1492 LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
1493 << " Image offset=" << image_info.image_offset_ << std::dec;
1494 LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
1495 << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
1496 << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
1497 << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001498 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001499 // Store boot image info for app image so that we can relocate.
1500 uint32_t boot_image_begin = 0;
1501 uint32_t boot_image_end = 0;
1502 uint32_t boot_oat_begin = 0;
1503 uint32_t boot_oat_end = 0;
1504 gc::Heap* const heap = Runtime::Current()->GetHeap();
1505 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001506
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001507 // Create the header, leave 0 for data size since we will fill this in as we are writing the
1508 // image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001509 new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_),
1510 image_end,
1511 sections,
1512 image_info.image_roots_address_,
1513 oat_file_->GetOatHeader().GetChecksum(),
1514 PointerToLowMemUInt32(oat_file_begin),
1515 PointerToLowMemUInt32(image_info.oat_data_begin_),
1516 PointerToLowMemUInt32(oat_data_end),
1517 PointerToLowMemUInt32(oat_file_end),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001518 boot_image_begin,
1519 boot_image_end - boot_image_begin,
1520 boot_oat_begin,
1521 boot_oat_end - boot_oat_begin,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001522 target_ptr_size_,
1523 compile_pic_,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001524 /*is_pic*/compile_app_image_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001525 image_storage_mode_,
1526 /*data_size*/0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001527}
1528
1529ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001530 auto it = native_object_relocations_.find(method);
1531 CHECK(it != native_object_relocations_.end()) << PrettyMethod(method) << " @ " << method;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001532 const char* oat_filename = GetOatFilename(method->GetDexCache());
1533 ImageInfo& image_info = GetImageInfo(oat_filename);
1534 CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects";
1535 return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001536}
1537
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001538class FixupRootVisitor : public RootVisitor {
1539 public:
1540 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1541 }
1542
1543 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001544 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001545 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001546 *roots[i] = image_writer_->GetImageAddress(*roots[i]);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001547 }
1548 }
1549
1550 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1551 const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001552 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001553 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001554 roots[i]->Assign(image_writer_->GetImageAddress(roots[i]->AsMirrorPtr()));
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001555 }
1556 }
1557
1558 private:
1559 ImageWriter* const image_writer_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001560};
1561
Mathieu Chartierc7853442015-03-27 14:35:38 -07001562void ImageWriter::CopyAndFixupNativeData() {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001563 const char* oat_filename = oat_file_->GetLocation().c_str();
1564 ImageInfo& image_info = GetImageInfo(oat_filename);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001565 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001566 for (auto& pair : native_object_relocations_) {
1567 NativeObjectRelocation& relocation = pair.second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001568 // Only work with fields and methods that are in the current oat file.
1569 if (strcmp(relocation.oat_filename, oat_filename) != 0) {
1570 continue;
1571 }
1572 auto* dest = image_info.image_->Begin() + relocation.offset;
1573 DCHECK_GE(dest, image_info.image_->Begin() + image_info.image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001574 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001575 switch (relocation.type) {
1576 case kNativeObjectRelocationTypeArtField: {
1577 memcpy(dest, pair.first, sizeof(ArtField));
1578 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
1579 GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass()));
1580 break;
1581 }
1582 case kNativeObjectRelocationTypeArtMethodClean:
1583 case kNativeObjectRelocationTypeArtMethodDirty: {
1584 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001585 reinterpret_cast<ArtMethod*>(dest),
1586 image_info);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001587 break;
1588 }
1589 // For arrays, copy just the header since the elements will get copied by their corresponding
1590 // relocations.
1591 case kNativeObjectRelocationTypeArtFieldArray: {
1592 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1593 break;
1594 }
1595 case kNativeObjectRelocationTypeArtMethodArrayClean:
1596 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markocf36d492015-08-12 19:27:26 +01001597 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(
1598 0,
Vladimir Marko14632852015-08-17 12:07:23 +01001599 ArtMethod::Size(target_ptr_size_),
1600 ArtMethod::Alignment(target_ptr_size_)));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001601 break;
Vladimir Marko05792b92015-08-03 11:56:49 +01001602 case kNativeObjectRelocationTypeDexCacheArray:
1603 // Nothing to copy here, everything is done in FixupDexCache().
1604 break;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001605 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001606 }
1607 }
1608 // Fixup the image method roots.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001609 auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001610 const ImageSection& methods_section = image_header->GetMethodsSection();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001611 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001612 ArtMethod* method = image_methods_[i];
1613 CHECK(method != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001614 // Only place runtime methods in the image of the default oat file.
1615 if (method->IsRuntimeMethod() && strcmp(default_oat_filename_, oat_filename) != 0) {
1616 continue;
1617 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001618 if (!IsInBootImage(method)) {
1619 auto it = native_object_relocations_.find(method);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001620 CHECK(it != native_object_relocations_.end()) << "No forwarding for " << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001621 NativeObjectRelocation& relocation = it->second;
1622 CHECK(methods_section.Contains(relocation.offset)) << relocation.offset << " not in "
1623 << methods_section;
1624 CHECK(relocation.IsArtMethodRelocation()) << relocation.type;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001625 method = reinterpret_cast<ArtMethod*>(global_image_begin_ + it->second.offset);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001626 }
1627 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001628 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001629 FixupRootVisitor root_visitor(this);
1630
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001631 // Write the intern table into the image.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001632 if (image_info.intern_table_bytes_ > 0) {
1633 const ImageSection& intern_table_section = image_header->GetImageSection(
1634 ImageHeader::kSectionInternedStrings);
1635 InternTable* const intern_table = image_info.intern_table_.get();
1636 uint8_t* const intern_table_memory_ptr =
1637 image_info.image_->Begin() + intern_table_section.Offset();
1638 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
1639 CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
1640 // Fixup the pointers in the newly written intern table to contain image addresses.
1641 InternTable temp_intern_table;
1642 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1643 // the VisitRoots() will update the memory directly rather than the copies.
1644 // This also relies on visit roots not doing any verification which could fail after we update
1645 // the roots to be the image addresses.
1646 temp_intern_table.AddTableFromMemory(intern_table_memory_ptr);
1647 CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
1648 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
1649 }
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001650 // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
1651 // class loaders. Writing multiple class tables into the image is currently unsupported.
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001652 if (image_info.class_table_bytes_ > 0u) {
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001653 const ImageSection& class_table_section = image_header->GetImageSection(
1654 ImageHeader::kSectionClassTable);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001655 uint8_t* const class_table_memory_ptr =
1656 image_info.image_->Begin() + class_table_section.Offset();
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001657 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001658
1659 ClassTable* table = image_info.class_table_.get();
1660 CHECK(table != nullptr);
1661 const size_t class_table_bytes = table->WriteToMemory(class_table_memory_ptr);
1662 CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
1663 // Fixup the pointers in the newly written class table to contain image addresses. See
1664 // above comment for intern tables.
1665 ClassTable temp_class_table;
1666 temp_class_table.ReadFromMemory(class_table_memory_ptr);
1667 CHECK_EQ(temp_class_table.NumZygoteClasses(), table->NumNonZygoteClasses() +
1668 table->NumZygoteClasses());
1669 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(&root_visitor,
1670 RootInfo(kRootUnknown));
1671 temp_class_table.VisitRoots(buffered_visitor);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001672 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001673}
1674
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001675void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001676 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001677 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1678 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001679 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001680 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07001681 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
1682 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001683 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001684 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001685}
1686
Mathieu Chartier590fee92013-09-13 13:46:47 -07001687void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001688 DCHECK(obj != nullptr);
1689 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001690 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1691}
1692
Mathieu Chartiere401d142015-04-22 13:56:20 -07001693void ImageWriter::FixupPointerArray(mirror::Object* dst, mirror::PointerArray* arr,
1694 mirror::Class* klass, Bin array_type) {
1695 CHECK(klass->IsArrayClass());
1696 CHECK(arr->IsIntArray() || arr->IsLongArray()) << PrettyClass(klass) << " " << arr;
1697 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001698 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001699 dst->SetClass(GetImageAddress(arr->GetClass()));
1700 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001701 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001702 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
1703 if (elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001704 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01001705 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001706 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001707 auto* method = reinterpret_cast<ArtMethod*>(elem);
1708 LOG(FATAL) << "No relocation entry for ArtMethod " << PrettyMethod(method) << " @ "
1709 << method << " idx=" << i << "/" << num_elements << " with declaring class "
1710 << PrettyClass(method->GetDeclaringClass());
1711 } else {
1712 CHECK_EQ(array_type, kBinArtField);
1713 auto* field = reinterpret_cast<ArtField*>(elem);
1714 LOG(FATAL) << "No relocation entry for ArtField " << PrettyField(field) << " @ "
1715 << field << " idx=" << i << "/" << num_elements << " with declaring class "
1716 << PrettyClass(field->GetDeclaringClass());
1717 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001718 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001719 } else {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001720 ImageInfo& image_info = GetImageInfo(it->second.oat_filename);
1721 elem = image_info.image_begin_ + it->second.offset;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001722 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001723 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001724 dest_array->SetElementPtrSize<false, true>(i, elem, target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001725 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001726}
1727
1728void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001729 if (IsInBootImage(obj)) {
1730 return;
1731 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001732 size_t offset = GetImageOffset(obj);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001733 const char* oat_filename = GetOatFilename(obj);
1734 ImageInfo& image_info = GetImageInfo(oat_filename);
1735 auto* dst = reinterpret_cast<Object*>(image_info.image_->Begin() + offset);
1736 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001737 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001738
Jeff Haodcdc85b2015-12-04 14:06:18 -08001739 image_info.image_bitmap_->Set(dst); // Mark the obj as live.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001740
1741 const size_t n = obj->SizeOf();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001742 DCHECK_LE(offset + n, image_info.image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001743 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001744
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001745 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1746 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001747 const auto it = saved_hashcode_map_.find(obj);
1748 dst->SetLockWord(it != saved_hashcode_map_.end() ?
1749 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001750 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001751}
1752
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001753// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001754class FixupVisitor {
1755 public:
1756 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1757 }
1758
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001759 // Ignore class roots since we don't have a way to map them to the destination. These are handled
1760 // with other logic.
1761 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1762 const {}
1763 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1764
1765
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001766 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001767 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -07001768 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001769 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1770 // image.
1771 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001772 offset,
1773 image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001774 }
1775
1776 // java.lang.ref.Reference visitor.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001777 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001778 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001779 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001780 mirror::Reference::ReferentOffset(),
1781 image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001782 }
1783
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001784 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001785 ImageWriter* const image_writer_;
1786 mirror::Object* const copy_;
1787};
1788
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001789class FixupClassVisitor FINAL : public FixupVisitor {
1790 public:
1791 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1792 }
1793
Mathieu Chartierc7853442015-03-27 14:35:38 -07001794 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001795 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001796 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001797 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001798 }
1799
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001800 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1801 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001802 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001803 LOG(FATAL) << "Reference not expected here.";
1804 }
1805};
1806
Vladimir Marko05792b92015-08-03 11:56:49 +01001807uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
1808 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001809 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001810 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001811 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1812 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001813 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01001814 return relocation.offset;
1815}
1816
1817template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001818T* ImageWriter::NativeLocationInImage(T* obj, const char* oat_filename) {
1819 if (obj == nullptr || IsInBootImage(obj)) {
1820 return obj;
1821 } else {
1822 ImageInfo& image_info = GetImageInfo(oat_filename);
1823 return reinterpret_cast<T*>(image_info.image_begin_ + NativeOffsetInImage(obj));
1824 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001825}
1826
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001827template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001828T* ImageWriter::NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) {
1829 if (obj == nullptr || IsInBootImage(obj)) {
1830 return obj;
1831 } else {
1832 const char* oat_filename = GetOatFilenameForDexCache(dex_cache);
1833 ImageInfo& image_info = GetImageInfo(oat_filename);
1834 return reinterpret_cast<T*>(image_info.image_->Begin() + NativeOffsetInImage(obj));
1835 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001836}
1837
1838class NativeLocationVisitor {
1839 public:
Jeff Haodcdc85b2015-12-04 14:06:18 -08001840 explicit NativeLocationVisitor(ImageWriter* image_writer, const char* oat_filename)
1841 : image_writer_(image_writer), oat_filename_(oat_filename) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001842
1843 template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001844 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
1845 return image_writer_->NativeLocationInImage(ptr, oat_filename_);
1846 }
1847
1848 ArtMethod* operator()(ArtMethod* method) const SHARED_REQUIRES(Locks::mutator_lock_) {
1849 const char* oat_filename = method->IsRuntimeMethod() ? image_writer_->GetDefaultOatFilename() :
1850 image_writer_->GetOatFilenameForDexCache(method->GetDexCache());
1851 return image_writer_->NativeLocationInImage(method, oat_filename);
1852 }
1853
1854 ArtField* operator()(ArtField* field) const SHARED_REQUIRES(Locks::mutator_lock_) {
1855 const char* oat_filename = image_writer_->GetOatFilenameForDexCache(field->GetDexCache());
1856 return image_writer_->NativeLocationInImage(field, oat_filename);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001857 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001858
1859 private:
1860 ImageWriter* const image_writer_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001861 const char* oat_filename_;
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001862};
1863
1864void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001865 const char* oat_filename = GetOatFilename(orig);
1866 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this, oat_filename));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001867 FixupClassVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001868 static_cast<mirror::Object*>(orig)->VisitReferences(visitor, visitor);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001869
1870 // Remove the clinitThreadId. This is required for image determinism.
1871 copy->SetClinitThreadId(static_cast<pid_t>(0));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001872}
1873
Ian Rogersef7d42f2014-01-06 12:55:46 -08001874void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001875 DCHECK(orig != nullptr);
1876 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07001877 if (kUseBakerOrBrooksReadBarrier) {
1878 orig->AssertReadBarrierPointer();
1879 if (kUseBrooksReadBarrier) {
1880 // Note the address 'copy' isn't the same as the image address of 'orig'.
1881 copy->SetReadBarrierPointer(GetImageAddress(orig));
1882 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
1883 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08001884 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001885 auto* klass = orig->GetClass();
1886 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001887 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07001888 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
1889 if (it != pointer_arrays_.end()) {
1890 // Should only need to fixup every pointer array exactly once.
1891 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
1892 pointer_arrays_.erase(it);
1893 return;
1894 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001895 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001896 if (orig->IsClass()) {
1897 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001898 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001899 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
1900 // Need to go update the ArtMethod.
1901 auto* dest = down_cast<mirror::AbstractMethod*>(copy);
1902 auto* src = down_cast<mirror::AbstractMethod*>(orig);
1903 ArtMethod* src_method = src->GetArtMethod();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001904 auto it = native_object_relocations_.find(src_method);
1905 CHECK(it != native_object_relocations_.end())
1906 << "Missing relocation for AbstractMethod.artMethod " << PrettyMethod(src_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001907 dest->SetArtMethod(
Jeff Haodcdc85b2015-12-04 14:06:18 -08001908 reinterpret_cast<ArtMethod*>(global_image_begin_ + it->second.offset));
Vladimir Marko05792b92015-08-03 11:56:49 +01001909 } else if (!klass->IsArrayClass()) {
1910 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1911 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
1912 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001913 } else if (klass->IsClassLoaderClass()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001914 mirror::ClassLoader* copy_loader = down_cast<mirror::ClassLoader*>(copy);
Vladimir Marko05792b92015-08-03 11:56:49 +01001915 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
1916 // ClassLoader.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001917 copy_loader->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07001918 // Also set allocator to null to be safe. The allocator is created when we create the class
1919 // table. We also never expect to unload things in the image since they are held live as
1920 // roots.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001921 copy_loader->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01001922 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001923 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001924 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001925 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001926 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001927}
1928
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001929
1930class ImageAddressVisitor {
1931 public:
1932 explicit ImageAddressVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
1933
1934 template <typename T>
1935 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
1936 return image_writer_->GetImageAddress(ptr);
1937 }
1938
1939 private:
1940 ImageWriter* const image_writer_;
1941};
1942
1943
Vladimir Marko05792b92015-08-03 11:56:49 +01001944void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
1945 mirror::DexCache* copy_dex_cache) {
1946 // Though the DexCache array fields are usually treated as native pointers, we set the full
1947 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
1948 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
1949 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
Jeff Haodcdc85b2015-12-04 14:06:18 -08001950 const char* oat_filename = GetOatFilenameForDexCache(orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01001951 GcRoot<mirror::String>* orig_strings = orig_dex_cache->GetStrings();
1952 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001953 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001954 NativeLocationInImage(orig_strings, oat_filename),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001955 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001956 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings, orig_dex_cache),
1957 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001958 }
1959 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
1960 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001961 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001962 NativeLocationInImage(orig_types, oat_filename),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001963 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001964 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types, orig_dex_cache),
1965 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001966 }
1967 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
1968 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001969 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001970 NativeLocationInImage(orig_methods, oat_filename),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001971 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001972 ArtMethod** copy_methods = NativeCopyLocation(orig_methods, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01001973 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
1974 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001975 const char* method_oat_filename;
1976 if (orig == nullptr || orig->IsRuntimeMethod()) {
1977 method_oat_filename = default_oat_filename_;
1978 } else {
1979 method_oat_filename = GetOatFilenameForDexCache(orig->GetDexCache());
1980 }
1981 ArtMethod* copy = NativeLocationInImage(orig, method_oat_filename);
Vladimir Marko05792b92015-08-03 11:56:49 +01001982 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
1983 }
1984 }
1985 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
1986 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001987 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001988 NativeLocationInImage(orig_fields, oat_filename),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001989 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001990 ArtField** copy_fields = NativeCopyLocation(orig_fields, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01001991 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
1992 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, i, target_ptr_size_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001993 const char* field_oat_filename =
1994 orig == nullptr ? default_oat_filename_ : GetOatFilenameForDexCache(orig->GetDexCache());
1995 ArtField* copy = NativeLocationInImage(orig, field_oat_filename);
Vladimir Marko05792b92015-08-03 11:56:49 +01001996 mirror::DexCache::SetElementPtrSize(copy_fields, i, copy, target_ptr_size_);
1997 }
1998 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08001999
2000 // Remove the DexFile pointers. They will be fixed up when the runtime loads the oat file. Leaving
2001 // compiler pointers in here will make the output non-deterministic.
2002 copy_dex_cache->SetDexFile(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002003}
2004
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002005const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
2006 DCHECK_LT(type, kOatAddressCount);
2007 // If we are compiling an app image, we need to use the stubs of the boot image.
2008 if (compile_app_image_) {
2009 // Use the current image pointers.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002010 const std::vector<gc::space::ImageSpace*>& image_spaces =
Jeff Haodcdc85b2015-12-04 14:06:18 -08002011 Runtime::Current()->GetHeap()->GetBootImageSpaces();
2012 DCHECK(!image_spaces.empty());
2013 const OatFile* oat_file = image_spaces[0]->GetOatFile();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002014 CHECK(oat_file != nullptr);
2015 const OatHeader& header = oat_file->GetOatHeader();
2016 switch (type) {
2017 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
2018 case kOatAddressQuickGenericJNITrampoline:
2019 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
2020 case kOatAddressInterpreterToInterpreterBridge:
2021 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
2022 case kOatAddressInterpreterToCompiledCodeBridge:
2023 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
2024 case kOatAddressJNIDlsymLookup:
2025 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
2026 case kOatAddressQuickIMTConflictTrampoline:
2027 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
2028 case kOatAddressQuickResolutionTrampoline:
2029 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
2030 case kOatAddressQuickToInterpreterBridge:
2031 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
2032 default:
2033 UNREACHABLE();
2034 }
2035 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002036 const ImageInfo& primary_image_info = GetImageInfo(0);
2037 return GetOatAddressForOffset(primary_image_info.oat_address_offsets_[type], primary_image_info);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002038}
2039
Jeff Haodcdc85b2015-12-04 14:06:18 -08002040const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method,
2041 const ImageInfo& image_info,
2042 bool* quick_is_interpreted) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002043 DCHECK(!method->IsResolutionMethod()) << PrettyMethod(method);
2044 DCHECK(!method->IsImtConflictMethod()) << PrettyMethod(method);
2045 DCHECK(!method->IsImtUnimplementedMethod()) << PrettyMethod(method);
Alex Light9139e002015-10-09 15:59:48 -07002046 DCHECK(method->IsInvokable()) << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002047 DCHECK(!IsInBootImage(method)) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002048
2049 // Use original code if it exists. Otherwise, set the code pointer to the resolution
2050 // trampoline.
2051
2052 // Quick entrypoint:
Jeff Haoc7d11882015-02-03 15:08:39 -08002053 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(
2054 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_));
Jeff Haodcdc85b2015-12-04 14:06:18 -08002055 const uint8_t* quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002056 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002057 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
2058 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002059 // We have code for a non-static or initialized method, just use the code.
2060 } else if (quick_code == nullptr && method->IsNative() &&
2061 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
2062 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002063 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002064 } else if (quick_code == nullptr && !method->IsNative()) {
2065 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002066 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002067 *quick_is_interpreted = true;
2068 } else {
2069 CHECK(!method->GetDeclaringClass()->IsInitialized());
2070 // We have code for a static method, but need to go through the resolution stub for class
2071 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002072 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
2073 }
2074 if (!IsInBootOatFile(quick_code)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002075 // DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002076 }
2077 return quick_code;
2078}
2079
Jeff Haodcdc85b2015-12-04 14:06:18 -08002080void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
2081 ArtMethod* copy,
2082 const ImageInfo& image_info) {
Vladimir Marko14632852015-08-17 12:07:23 +01002083 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002084
2085 copy->SetDeclaringClass(GetImageAddress(orig->GetDeclaringClassUnchecked()));
Vladimir Marko05792b92015-08-03 11:56:49 +01002086
Jeff Haodcdc85b2015-12-04 14:06:18 -08002087 const char* oat_filename;
Mathieu Chartiere467cea2016-01-07 18:36:19 -08002088 if (orig->IsRuntimeMethod() || compile_app_image_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002089 oat_filename = default_oat_filename_;
2090 } else {
2091 auto it = dex_file_oat_filename_map_.find(orig->GetDexFile());
2092 DCHECK(it != dex_file_oat_filename_map_.end()) << orig->GetDexFile()->GetLocation();
2093 oat_filename = it->second;
2094 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002095 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002096 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods, oat_filename),
2097 target_ptr_size_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002098 GcRoot<mirror::Class>* orig_resolved_types = orig->GetDexCacheResolvedTypes(target_ptr_size_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002099 copy->SetDexCacheResolvedTypes(NativeLocationInImage(orig_resolved_types, oat_filename),
2100 target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002101
Ian Rogers848871b2013-08-05 10:56:33 -07002102 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
2103 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07002104
Ian Rogers848871b2013-08-05 10:56:33 -07002105 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002106 Runtime* runtime = Runtime::Current();
2107 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002108 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002109 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002110 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
2111 orig == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002112 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002113 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002114 } else if (UNLIKELY(orig->IsRuntimeMethod())) {
2115 bool found_one = false;
2116 for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) {
2117 auto idx = static_cast<Runtime::CalleeSaveType>(i);
2118 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
2119 found_one = true;
2120 break;
2121 }
2122 }
2123 CHECK(found_one) << "Expected to find callee save method but got " << PrettyMethod(orig);
2124 CHECK(copy->IsRuntimeMethod());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002125 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002126 // We assume all methods have code. If they don't currently then we set them to the use the
2127 // resolution trampoline. Abstract methods never have code and so we need to make sure their
2128 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07002129 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002130 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002131 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002132 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002133 bool quick_is_interpreted;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002134 const uint8_t* quick_code = GetQuickCode(orig, image_info, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002135 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02002136
Sebastien Hertze1d07812014-05-21 15:44:09 +02002137 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07002138 if (orig->IsNative()) {
2139 // The native method's pointer is set to a stub to lookup via dlsym.
2140 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002141 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002142 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002143 }
2144 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002145 }
2146}
2147
Alex Lighta59dd802014-07-02 16:28:08 -07002148static OatHeader* GetOatHeaderFromElf(ElfFile* elf) {
Tong Shen62d1ca32014-09-03 17:24:56 -07002149 uint64_t data_sec_offset;
2150 bool has_data_sec = elf->GetSectionOffsetAndSize(".rodata", &data_sec_offset, nullptr);
2151 if (!has_data_sec) {
Alex Lighta59dd802014-07-02 16:28:08 -07002152 return nullptr;
2153 }
Tong Shen62d1ca32014-09-03 17:24:56 -07002154 return reinterpret_cast<OatHeader*>(elf->Begin() + data_sec_offset);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08002155}
2156
Vladimir Markof4da6752014-08-01 19:04:18 +01002157void ImageWriter::SetOatChecksumFromElfFile(File* elf_file) {
Alex Lighta59dd802014-07-02 16:28:08 -07002158 std::string error_msg;
Mathieu Chartiera808bac2015-11-05 16:33:15 -08002159 std::unique_ptr<ElfFile> elf(ElfFile::Open(elf_file,
2160 PROT_READ | PROT_WRITE,
2161 MAP_SHARED,
2162 &error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -07002163 if (elf.get() == nullptr) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002164 LOG(FATAL) << "Unable open oat file: " << error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07002165 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002166 }
Alex Lighta59dd802014-07-02 16:28:08 -07002167 OatHeader* oat_header = GetOatHeaderFromElf(elf.get());
2168 CHECK(oat_header != nullptr);
2169 CHECK(oat_header->IsValid());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002170
Jeff Haodcdc85b2015-12-04 14:06:18 -08002171 ImageInfo& image_info = GetImageInfo(oat_file_->GetLocation().c_str());
2172 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Alex Lighta59dd802014-07-02 16:28:08 -07002173 image_header->SetOatChecksum(oat_header->GetChecksum());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002174}
2175
Jeff Haodcdc85b2015-12-04 14:06:18 -08002176size_t ImageWriter::GetBinSizeSum(ImageWriter::ImageInfo& image_info, ImageWriter::Bin up_to) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002177 DCHECK_LE(up_to, kBinSize);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002178 return std::accumulate(&image_info.bin_slot_sizes_[0],
2179 &image_info.bin_slot_sizes_[up_to],
2180 /*init*/0);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002181}
2182
2183ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
2184 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07002185 static_assert(kBinBits == 3, "wrong number of bin bits");
2186 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002187 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
2188
2189 DCHECK_LT(GetBin(), kBinSize);
2190 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
2191}
2192
2193ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
2194 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
2195 DCHECK_EQ(index, GetIndex());
2196}
2197
2198ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
2199 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
2200}
2201
2202uint32_t ImageWriter::BinSlot::GetIndex() const {
2203 return lockword_ & ~kBinMask;
2204}
2205
Jeff Haodcdc85b2015-12-04 14:06:18 -08002206uint8_t* ImageWriter::GetOatFileBegin(const char* oat_filename) const {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002207 uintptr_t last_image_end = 0;
2208 for (const char* oat_fn : oat_filenames_) {
2209 const ImageInfo& image_info = GetConstImageInfo(oat_fn);
2210 DCHECK(image_info.image_begin_ != nullptr);
2211 uintptr_t this_end = reinterpret_cast<uintptr_t>(image_info.image_begin_) +
2212 image_info.image_size_;
2213 last_image_end = std::max(this_end, last_image_end);
2214 }
2215 const ImageInfo& image_info = GetConstImageInfo(oat_filename);
2216 return reinterpret_cast<uint8_t*>(last_image_end) + image_info.oat_offset_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002217}
2218
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002219ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
2220 switch (type) {
2221 case kNativeObjectRelocationTypeArtField:
2222 case kNativeObjectRelocationTypeArtFieldArray:
2223 return kBinArtField;
2224 case kNativeObjectRelocationTypeArtMethodClean:
2225 case kNativeObjectRelocationTypeArtMethodArrayClean:
2226 return kBinArtMethodClean;
2227 case kNativeObjectRelocationTypeArtMethodDirty:
2228 case kNativeObjectRelocationTypeArtMethodArrayDirty:
2229 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01002230 case kNativeObjectRelocationTypeDexCacheArray:
2231 return kBinDexCacheArray;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002232 }
2233 UNREACHABLE();
2234}
2235
Jeff Haodcdc85b2015-12-04 14:06:18 -08002236const char* ImageWriter::GetOatFilename(mirror::Object* obj) const {
2237 if (compile_app_image_) {
2238 return default_oat_filename_;
2239 } else {
2240 return GetOatFilenameForDexCache(obj->IsDexCache() ? obj->AsDexCache() :
2241 obj->IsClass() ? obj->AsClass()->GetDexCache() : obj->GetClass()->GetDexCache());
2242 }
2243}
2244
2245const char* ImageWriter::GetOatFilenameForDexCache(mirror::DexCache* dex_cache) const {
2246 if (compile_app_image_ || dex_cache == nullptr) {
2247 return default_oat_filename_;
2248 } else {
2249 auto it = dex_file_oat_filename_map_.find(dex_cache->GetDexFile());
2250 DCHECK(it != dex_file_oat_filename_map_.end()) << dex_cache->GetDexFile()->GetLocation();
2251 return it->second;
2252 }
2253}
2254
2255ImageWriter::ImageInfo& ImageWriter::GetImageInfo(const char* oat_filename) {
2256 auto it = image_info_map_.find(oat_filename);
2257 DCHECK(it != image_info_map_.end());
2258 return it->second;
2259}
2260
2261const ImageWriter::ImageInfo& ImageWriter::GetConstImageInfo(const char* oat_filename) const {
2262 auto it = image_info_map_.find(oat_filename);
2263 DCHECK(it != image_info_map_.end());
2264 return it->second;
2265}
2266
2267const ImageWriter::ImageInfo& ImageWriter::GetImageInfo(size_t index) const {
2268 DCHECK_LT(index, oat_filenames_.size());
2269 return GetConstImageInfo(oat_filenames_[index]);
2270}
2271
2272void ImageWriter::UpdateOatFile(const char* oat_filename) {
2273 std::unique_ptr<File> oat_file(OS::OpenFileForReading(oat_filename));
2274 DCHECK(oat_file != nullptr);
2275 size_t oat_loaded_size = 0;
2276 size_t oat_data_offset = 0;
2277 ElfWriter::GetOatElfInformation(oat_file.get(), &oat_loaded_size, &oat_data_offset);
2278
2279 ImageInfo& cur_image_info = GetImageInfo(oat_filename);
2280
2281 // Update the oat_offset of the next image info.
2282 auto it = std::find(oat_filenames_.begin(), oat_filenames_.end(), oat_filename);
2283 DCHECK(it != oat_filenames_.end());
2284
2285 it++;
2286 if (it != oat_filenames_.end()) {
2287 // There is a following one.
2288 ImageInfo& next_image_info = GetImageInfo(*it);
2289 next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
2290 }
2291}
2292
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002293ImageWriter::ImageWriter(
2294 const CompilerDriver& compiler_driver,
2295 uintptr_t image_begin,
2296 bool compile_pic,
2297 bool compile_app_image,
2298 ImageHeader::StorageMode image_storage_mode,
2299 const std::vector<const char*> oat_filenames,
2300 const std::unordered_map<const DexFile*, const char*>& dex_file_oat_filename_map)
2301 : compiler_driver_(compiler_driver),
2302 global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
2303 image_objects_offset_begin_(0),
2304 oat_file_(nullptr),
2305 compile_pic_(compile_pic),
2306 compile_app_image_(compile_app_image),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002307 target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())),
2308 image_method_array_(ImageHeader::kImageMethodsCount),
2309 dirty_methods_(0u),
2310 clean_methods_(0u),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002311 image_storage_mode_(image_storage_mode),
2312 dex_file_oat_filename_map_(dex_file_oat_filename_map),
2313 oat_filenames_(oat_filenames),
2314 default_oat_filename_(oat_filenames[0]) {
2315 CHECK_NE(image_begin, 0U);
2316 for (const char* oat_filename : oat_filenames) {
2317 image_info_map_.emplace(oat_filename, ImageInfo());
2318 }
2319 std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
2320}
2321
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002322ImageWriter::ImageInfo::ImageInfo()
2323 : intern_table_(new InternTable),
2324 class_table_(new ClassTable) {}
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002325
Brian Carlstrom7940e442013-07-12 13:46:57 -07002326} // namespace art