blob: 2e9e2879a6bbf0540555466e6efd75b06971818d [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));
Mathieu Chartier784bb092016-01-28 12:02:00 -0800279 // Empty the file in case it already exists.
280 if (image_file != nullptr) {
281 TEMP_FAILURE_RETRY(image_file->SetLength(0));
282 TEMP_FAILURE_RETRY(image_file->Flush());
283 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800284 } else {
285 LOG(ERROR) << "image fd " << image_fd << " name " << image_filename;
286 }
Jeff Haodcdc85b2015-12-04 14:06:18 -0800287 } else {
288 image_file.reset(OS::CreateEmptyFile(image_filename));
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800289 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800290
Jeff Haodcdc85b2015-12-04 14:06:18 -0800291 if (image_file == nullptr) {
292 LOG(ERROR) << "Failed to open image file " << image_filename;
293 return false;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800294 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800295
296 if (!compile_app_image_ && fchmod(image_file->Fd(), 0644) != 0) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800297 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
298 image_file->Erase();
299 return EXIT_FAILURE;
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800300 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800301
Jeff Haodcdc85b2015-12-04 14:06:18 -0800302 std::unique_ptr<char[]> compressed_data;
303 // Image data size excludes the bitmap and the header.
304 ImageHeader* const image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
305 const size_t image_data_size = image_header->GetImageSize() - sizeof(ImageHeader);
306 char* image_data = reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader);
307 size_t data_size;
308 const char* image_data_to_write;
Nicolas Geoffray83d4d722015-12-10 08:26:32 +0000309
Jeff Haodcdc85b2015-12-04 14:06:18 -0800310 CHECK_EQ(image_header->storage_mode_, image_storage_mode_);
311 switch (image_storage_mode_) {
312 case ImageHeader::kStorageModeLZ4: {
313 size_t compressed_max_size = LZ4_compressBound(image_data_size);
314 compressed_data.reset(new char[compressed_max_size]);
315 data_size = LZ4_compress(
316 reinterpret_cast<char*>(image_info.image_->Begin()) + sizeof(ImageHeader),
317 &compressed_data[0],
318 image_data_size);
319 image_data_to_write = &compressed_data[0];
320 VLOG(compiler) << "Compressed from " << image_data_size << " to " << data_size;
321 break;
322 }
323 case ImageHeader::kStorageModeUncompressed: {
324 data_size = image_data_size;
325 image_data_to_write = image_data;
326 break;
327 }
328 default: {
329 LOG(FATAL) << "Unsupported";
330 UNREACHABLE();
331 }
332 }
Mathieu Chartierceb07b32015-12-10 09:33:21 -0800333
Jeff Haodcdc85b2015-12-04 14:06:18 -0800334 // Write header first, as uncompressed.
335 image_header->data_size_ = data_size;
336 if (!image_file->WriteFully(image_info.image_->Begin(), sizeof(ImageHeader))) {
337 PLOG(ERROR) << "Failed to write image file header " << image_filename;
338 image_file->Erase();
339 return false;
340 }
341
342 // Write out the image + fields + methods.
343 const bool is_compressed = compressed_data != nullptr;
344 if (!image_file->WriteFully(image_data_to_write, data_size)) {
345 PLOG(ERROR) << "Failed to write image file data " << image_filename;
346 image_file->Erase();
347 return false;
348 }
349
350 // Write out the image bitmap at the page aligned start of the image end, also uncompressed for
351 // convenience.
352 const ImageSection& bitmap_section = image_header->GetImageSection(
353 ImageHeader::kSectionImageBitmap);
354 // Align up since data size may be unaligned if the image is compressed.
355 size_t bitmap_position_in_file = RoundUp(sizeof(ImageHeader) + data_size, kPageSize);
356 if (!is_compressed) {
357 CHECK_EQ(bitmap_position_in_file, bitmap_section.Offset());
358 }
359 if (!image_file->Write(reinterpret_cast<char*>(image_info.image_bitmap_->Begin()),
360 bitmap_section.Size(),
361 bitmap_position_in_file)) {
362 PLOG(ERROR) << "Failed to write image file " << image_filename;
363 image_file->Erase();
364 return false;
365 }
366 CHECK_EQ(bitmap_position_in_file + bitmap_section.Size(),
367 static_cast<size_t>(image_file->GetLength()));
368 if (image_file->FlushCloseOrErase() != 0) {
369 PLOG(ERROR) << "Failed to flush and close image file " << image_filename;
370 return false;
371 }
Andreas Gampe4303ba92014-11-06 01:00:46 -0800372 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700373 return true;
374}
375
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700376void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700377 DCHECK(object != nullptr);
378 DCHECK_NE(offset, 0U);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800379
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800380 // The object is already deflated from when we set the bin slot. Just overwrite the lock word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700381 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700382 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700383 DCHECK(IsImageOffsetAssigned(object));
384}
385
Mathieu Chartiere401d142015-04-22 13:56:20 -0700386void ImageWriter::UpdateImageOffset(mirror::Object* obj, uintptr_t offset) {
387 DCHECK(IsImageOffsetAssigned(obj)) << obj << " " << offset;
388 obj->SetLockWord(LockWord::FromForwardingAddress(offset), false);
389 DCHECK_EQ(obj->GetLockWord(false).ReadBarrierState(), 0u);
390}
391
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800392void ImageWriter::AssignImageOffset(mirror::Object* object, ImageWriter::BinSlot bin_slot) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700393 DCHECK(object != nullptr);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800394 DCHECK_NE(image_objects_offset_begin_, 0u);
395
Jeff Haodcdc85b2015-12-04 14:06:18 -0800396 const char* oat_filename = GetOatFilename(object);
397 ImageInfo& image_info = GetImageInfo(oat_filename);
398 size_t bin_slot_offset = image_info.bin_slot_offsets_[bin_slot.GetBin()];
Vladimir Markocf36d492015-08-12 19:27:26 +0100399 size_t new_offset = bin_slot_offset + bin_slot.GetIndex();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800400 DCHECK_ALIGNED(new_offset, kObjectAlignment);
401
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700402 SetImageOffset(object, new_offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800403 DCHECK_LT(new_offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700404}
405
Ian Rogersef7d42f2014-01-06 12:55:46 -0800406bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800407 // Will also return true if the bin slot was assigned since we are reusing the lock word.
Mathieu Chartier590fee92013-09-13 13:46:47 -0700408 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700409 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700410}
411
Ian Rogersef7d42f2014-01-06 12:55:46 -0800412size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700413 DCHECK(object != nullptr);
414 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700415 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700416 size_t offset = lock_word.ForwardingAddress();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800417 const char* oat_filename = GetOatFilename(object);
418 const ImageInfo& image_info = GetConstImageInfo(oat_filename);
419 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700420 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700421}
422
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800423void ImageWriter::SetImageBinSlot(mirror::Object* object, BinSlot bin_slot) {
424 DCHECK(object != nullptr);
425 DCHECK(!IsImageOffsetAssigned(object));
426 DCHECK(!IsImageBinSlotAssigned(object));
427
428 // Before we stomp over the lock word, save the hash code for later.
429 Monitor::Deflate(Thread::Current(), object);;
430 LockWord lw(object->GetLockWord(false));
431 switch (lw.GetState()) {
432 case LockWord::kFatLocked: {
433 LOG(FATAL) << "Fat locked object " << object << " found during object copy";
434 break;
435 }
436 case LockWord::kThinLocked: {
437 LOG(FATAL) << "Thin locked object " << object << " found during object copy";
438 break;
439 }
440 case LockWord::kUnlocked:
441 // No hash, don't need to save it.
442 break;
443 case LockWord::kHashCode:
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700444 DCHECK(saved_hashcode_map_.find(object) == saved_hashcode_map_.end());
445 saved_hashcode_map_.emplace(object, lw.GetHashCode());
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800446 break;
447 default:
448 LOG(FATAL) << "Unreachable.";
449 UNREACHABLE();
450 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -0700451 object->SetLockWord(LockWord::FromForwardingAddress(bin_slot.Uint32Value()), false);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700452 DCHECK_EQ(object->GetLockWord(false).ReadBarrierState(), 0u);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800453 DCHECK(IsImageBinSlotAssigned(object));
454}
455
Vladimir Marko20f85592015-03-19 10:07:02 +0000456void ImageWriter::PrepareDexCacheArraySlots() {
Vladimir Markof60c7e22015-11-23 18:05:08 +0000457 // Prepare dex cache array starts based on the ordering specified in the CompilerDriver.
Vladimir Markof60c7e22015-11-23 18:05:08 +0000458 // Set the slot size early to avoid DCHECK() failures in IsImageBinSlotAssigned()
459 // when AssignImageBinSlot() assigns their indexes out or order.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800460 for (const DexFile* dex_file : compiler_driver_.GetDexFilesForOatFile()) {
461 auto it = dex_file_oat_filename_map_.find(dex_file);
462 DCHECK(it != dex_file_oat_filename_map_.end()) << dex_file->GetLocation();
463 ImageInfo& image_info = GetImageInfo(it->second);
464 image_info.dex_cache_array_starts_.Put(dex_file, image_info.bin_slot_sizes_[kBinDexCacheArray]);
465 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
466 image_info.bin_slot_sizes_[kBinDexCacheArray] += layout.Size();
467 }
Vladimir Markof60c7e22015-11-23 18:05:08 +0000468
Vladimir Marko20f85592015-03-19 10:07:02 +0000469 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700470 Thread* const self = Thread::Current();
471 ReaderMutexLock mu(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800472 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700473 mirror::DexCache* dex_cache =
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800474 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800475 if (dex_cache == nullptr || IsInBootImage(dex_cache)) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700476 continue;
477 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000478 const DexFile* dex_file = dex_cache->GetDexFile();
Mathieu Chartierc7853442015-03-27 14:35:38 -0700479 DexCacheArraysLayout layout(target_ptr_size_, dex_file);
Vladimir Marko20f85592015-03-19 10:07:02 +0000480 DCHECK(layout.Valid());
Jeff Haodcdc85b2015-12-04 14:06:18 -0800481 const char* oat_filename = GetOatFilenameForDexCache(dex_cache);
482 ImageInfo& image_info = GetImageInfo(oat_filename);
483 uint32_t start = image_info.dex_cache_array_starts_.Get(dex_file);
Vladimir Marko05792b92015-08-03 11:56:49 +0100484 DCHECK_EQ(dex_file->NumTypeIds() != 0u, dex_cache->GetResolvedTypes() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800485 AddDexCacheArrayRelocation(dex_cache->GetResolvedTypes(),
486 start + layout.TypesOffset(),
487 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100488 DCHECK_EQ(dex_file->NumMethodIds() != 0u, dex_cache->GetResolvedMethods() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800489 AddDexCacheArrayRelocation(dex_cache->GetResolvedMethods(),
490 start + layout.MethodsOffset(),
491 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100492 DCHECK_EQ(dex_file->NumFieldIds() != 0u, dex_cache->GetResolvedFields() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800493 AddDexCacheArrayRelocation(dex_cache->GetResolvedFields(),
494 start + layout.FieldsOffset(),
495 dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +0100496 DCHECK_EQ(dex_file->NumStringIds() != 0u, dex_cache->GetStrings() != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800497 AddDexCacheArrayRelocation(dex_cache->GetStrings(), start + layout.StringsOffset(), dex_cache);
Vladimir Marko20f85592015-03-19 10:07:02 +0000498 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000499}
500
Jeff Haodcdc85b2015-12-04 14:06:18 -0800501void ImageWriter::AddDexCacheArrayRelocation(void* array, size_t offset, DexCache* dex_cache) {
Vladimir Marko05792b92015-08-03 11:56:49 +0100502 if (array != nullptr) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800503 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -0800504 const char* oat_filename = GetOatFilenameForDexCache(dex_cache);
505 native_object_relocations_.emplace(array,
506 NativeObjectRelocation { oat_filename, offset, kNativeObjectRelocationTypeDexCacheArray });
Vladimir Marko05792b92015-08-03 11:56:49 +0100507 }
508}
509
Mathieu Chartiere401d142015-04-22 13:56:20 -0700510void ImageWriter::AddMethodPointerArray(mirror::PointerArray* arr) {
511 DCHECK(arr != nullptr);
512 if (kIsDebugBuild) {
513 for (size_t i = 0, len = arr->GetLength(); i < len; i++) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800514 ArtMethod* method = arr->GetElementPtrSize<ArtMethod*>(i, target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700515 if (method != nullptr && !method->IsRuntimeMethod()) {
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800516 mirror::Class* klass = method->GetDeclaringClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800517 CHECK(klass == nullptr || KeepClass(klass))
518 << PrettyClass(klass) << " should be a kept class";
Mathieu Chartiere401d142015-04-22 13:56:20 -0700519 }
520 }
521 }
522 // kBinArtMethodClean picked arbitrarily, just required to differentiate between ArtFields and
523 // ArtMethods.
524 pointer_arrays_.emplace(arr, kBinArtMethodClean);
525}
526
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800527void ImageWriter::AssignImageBinSlot(mirror::Object* object) {
528 DCHECK(object != nullptr);
Jeff Haoc7d11882015-02-03 15:08:39 -0800529 size_t object_size = object->SizeOf();
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800530
531 // The magic happens here. We segregate objects into different bins based
532 // on how likely they are to get dirty at runtime.
533 //
534 // Likely-to-dirty objects get packed together into the same bin so that
535 // at runtime their page dirtiness ratio (how many dirty objects a page has) is
536 // maximized.
537 //
538 // This means more pages will stay either clean or shared dirty (with zygote) and
539 // the app will use less of its own (private) memory.
540 Bin bin = kBinRegular;
Vladimir Marko20f85592015-03-19 10:07:02 +0000541 size_t current_offset = 0u;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800542
543 if (kBinObjects) {
544 //
545 // Changing the bin of an object is purely a memory-use tuning.
546 // It has no change on runtime correctness.
547 //
548 // Memory analysis has determined that the following types of objects get dirtied
549 // the most:
550 //
Vladimir Marko20f85592015-03-19 10:07:02 +0000551 // * Dex cache arrays are stored in a special bin. The arrays for each dex cache have
552 // a fixed layout which helps improve generated code (using PC-relative addressing),
553 // so we pre-calculate their offsets separately in PrepareDexCacheArraySlots().
554 // Since these arrays are huge, most pages do not overlap other objects and it's not
555 // really important where they are for the clean/dirty separation. Due to their
Vladimir Marko05792b92015-08-03 11:56:49 +0100556 // special PC-relative addressing, we arbitrarily keep them at the end.
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800557 // * Class'es which are verified [their clinit runs only at runtime]
558 // - classes in general [because their static fields get overwritten]
559 // - initialized classes with all-final statics are unlikely to be ever dirty,
560 // so bin them separately
561 // * Art Methods that are:
562 // - native [their native entry point is not looked up until runtime]
563 // - have declaring classes that aren't initialized
564 // [their interpreter/quick entry points are trampolines until the class
565 // becomes initialized]
566 //
567 // We also assume the following objects get dirtied either never or extremely rarely:
568 // * Strings (they are immutable)
569 // * Art methods that aren't native and have initialized declared classes
570 //
571 // We assume that "regular" bin objects are highly unlikely to become dirtied,
572 // so packing them together will not result in a noticeably tighter dirty-to-clean ratio.
573 //
574 if (object->IsClass()) {
575 bin = kBinClassVerified;
576 mirror::Class* klass = object->AsClass();
577
Mathieu Chartiere401d142015-04-22 13:56:20 -0700578 // Add non-embedded vtable to the pointer array table if there is one.
579 auto* vtable = klass->GetVTable();
580 if (vtable != nullptr) {
581 AddMethodPointerArray(vtable);
582 }
583 auto* iftable = klass->GetIfTable();
584 if (iftable != nullptr) {
585 for (int32_t i = 0; i < klass->GetIfTableCount(); ++i) {
586 if (iftable->GetMethodArrayCount(i) > 0) {
587 AddMethodPointerArray(iftable->GetMethodArray(i));
588 }
589 }
590 }
591
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800592 if (klass->GetStatus() == Class::kStatusInitialized) {
593 bin = kBinClassInitialized;
594
595 // If the class's static fields are all final, put it into a separate bin
596 // since it's very likely it will stay clean.
597 uint32_t num_static_fields = klass->NumStaticFields();
598 if (num_static_fields == 0) {
599 bin = kBinClassInitializedFinalStatics;
600 } else {
601 // Maybe all the statics are final?
602 bool all_final = true;
603 for (uint32_t i = 0; i < num_static_fields; ++i) {
604 ArtField* field = klass->GetStaticField(i);
605 if (!field->IsFinal()) {
606 all_final = false;
607 break;
608 }
609 }
610
611 if (all_final) {
612 bin = kBinClassInitializedFinalStatics;
613 }
614 }
615 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800616 } else if (object->GetClass<kVerifyNone>()->IsStringClass()) {
617 bin = kBinString; // Strings are almost always immutable (except for object header).
618 } // else bin = kBinRegular
619 }
620
Jeff Haodcdc85b2015-12-04 14:06:18 -0800621 const char* oat_filename = GetOatFilename(object);
622 ImageInfo& image_info = GetImageInfo(oat_filename);
623
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800624 size_t offset_delta = RoundUp(object_size, kObjectAlignment); // 64-bit alignment
Jeff Haodcdc85b2015-12-04 14:06:18 -0800625 current_offset = image_info.bin_slot_sizes_[bin]; // How many bytes the current bin is at (aligned).
626 // Move the current bin size up to accommodate the object we just assigned a bin slot.
627 image_info.bin_slot_sizes_[bin] += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800628
629 BinSlot new_bin_slot(bin, current_offset);
630 SetImageBinSlot(object, new_bin_slot);
631
Jeff Haodcdc85b2015-12-04 14:06:18 -0800632 ++image_info.bin_slot_count_[bin];
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800633
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800634 // Grow the image closer to the end by the object we just assigned.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800635 image_info.image_end_ += offset_delta;
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800636}
637
Mathieu Chartiere401d142015-04-22 13:56:20 -0700638bool ImageWriter::WillMethodBeDirty(ArtMethod* m) const {
639 if (m->IsNative()) {
640 return true;
641 }
642 mirror::Class* declaring_class = m->GetDeclaringClass();
643 // Initialized is highly unlikely to dirty since there's no entry points to mutate.
644 return declaring_class == nullptr || declaring_class->GetStatus() != Class::kStatusInitialized;
645}
646
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800647bool ImageWriter::IsImageBinSlotAssigned(mirror::Object* object) const {
648 DCHECK(object != nullptr);
649
650 // We always stash the bin slot into a lockword, in the 'forwarding address' state.
651 // If it's in some other state, then we haven't yet assigned an image bin slot.
652 if (object->GetLockWord(false).GetState() != LockWord::kForwardingAddress) {
653 return false;
654 } else if (kIsDebugBuild) {
655 LockWord lock_word = object->GetLockWord(false);
656 size_t offset = lock_word.ForwardingAddress();
657 BinSlot bin_slot(offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800658 const char* oat_filename = GetOatFilename(object);
659 const ImageInfo& image_info = GetConstImageInfo(oat_filename);
660 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()])
Mathieu Chartiera808bac2015-11-05 16:33:15 -0800661 << "bin slot offset should not exceed the size of that bin";
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800662 }
663 return true;
664}
665
666ImageWriter::BinSlot ImageWriter::GetImageBinSlot(mirror::Object* object) const {
667 DCHECK(object != nullptr);
668 DCHECK(IsImageBinSlotAssigned(object));
669
670 LockWord lock_word = object->GetLockWord(false);
671 size_t offset = lock_word.ForwardingAddress(); // TODO: ForwardingAddress should be uint32_t
672 DCHECK_LE(offset, std::numeric_limits<uint32_t>::max());
673
674 BinSlot bin_slot(static_cast<uint32_t>(offset));
Jeff Haodcdc85b2015-12-04 14:06:18 -0800675 const char* oat_filename = GetOatFilename(object);
676 const ImageInfo& image_info = GetConstImageInfo(oat_filename);
677 DCHECK_LT(bin_slot.GetIndex(), image_info.bin_slot_sizes_[bin_slot.GetBin()]);
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800678
679 return bin_slot;
680}
681
Brian Carlstrom7940e442013-07-12 13:46:57 -0700682bool ImageWriter::AllocMemory() {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800683 for (const char* oat_filename : oat_filenames_) {
684 ImageInfo& image_info = GetImageInfo(oat_filename);
Mathieu Chartiera06ba052016-01-06 13:51:52 -0800685 ImageSection unused_sections[ImageHeader::kSectionCount];
686 const size_t length = RoundUp(
687 image_info.CreateImageSections(target_ptr_size_, unused_sections),
688 kPageSize);
689
Jeff Haodcdc85b2015-12-04 14:06:18 -0800690 std::string error_msg;
691 image_info.image_.reset(MemMap::MapAnonymous("image writer image",
692 nullptr,
693 length,
694 PROT_READ | PROT_WRITE,
695 false,
696 false,
697 &error_msg));
698 if (UNLIKELY(image_info.image_.get() == nullptr)) {
699 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
700 return false;
701 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700702
Jeff Haodcdc85b2015-12-04 14:06:18 -0800703 // Create the image bitmap, only needs to cover mirror object section which is up to image_end_.
704 CHECK_LE(image_info.image_end_, length);
705 image_info.image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create(
706 "image bitmap", image_info.image_->Begin(), RoundUp(image_info.image_end_, kPageSize)));
707 if (image_info.image_bitmap_.get() == nullptr) {
708 LOG(ERROR) << "Failed to allocate memory for image bitmap";
709 return false;
710 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700711 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700712 return true;
713}
714
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700715class ComputeLazyFieldsForClassesVisitor : public ClassVisitor {
716 public:
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -0800717 bool operator()(Class* c) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700718 StackHandleScope<1> hs(Thread::Current());
719 mirror::Class::ComputeName(hs.NewHandle(c));
720 return true;
721 }
722};
723
Brian Carlstrom7940e442013-07-12 13:46:57 -0700724void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700725 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700726 ComputeLazyFieldsForClassesVisitor visitor;
727 class_linker->VisitClassesWithoutClassesLock(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700728}
729
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800730static bool IsBootClassLoaderClass(mirror::Class* klass) SHARED_REQUIRES(Locks::mutator_lock_) {
731 return klass->GetClassLoader() == nullptr;
732}
733
734bool ImageWriter::IsBootClassLoaderNonImageClass(mirror::Class* klass) {
735 return IsBootClassLoaderClass(klass) && !IsInBootImage(klass);
736}
737
738bool ImageWriter::ContainsBootClassLoaderNonImageClass(mirror::Class* klass) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800739 bool early_exit = false;
740 std::unordered_set<mirror::Class*> visited;
741 return ContainsBootClassLoaderNonImageClassInternal(klass, &early_exit, &visited);
742}
743
744bool ImageWriter::ContainsBootClassLoaderNonImageClassInternal(
745 mirror::Class* klass,
746 bool* early_exit,
747 std::unordered_set<mirror::Class*>* visited) {
748 DCHECK(early_exit != nullptr);
749 DCHECK(visited != nullptr);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800750 DCHECK(compile_app_image_);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700751 if (klass == nullptr) {
752 return false;
753 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800754 auto found = prune_class_memo_.find(klass);
755 if (found != prune_class_memo_.end()) {
756 // Already computed, return the found value.
757 return found->second;
758 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800759 // Circular dependencies, return false but do not store the result in the memoization table.
760 if (visited->find(klass) != visited->end()) {
761 *early_exit = true;
762 return false;
763 }
764 visited->emplace(klass);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800765 bool result = IsBootClassLoaderNonImageClass(klass);
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800766 bool my_early_exit = false; // Only for ourselves, ignore caller.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800767 // Remove classes that failed to verify since we don't want to have java.lang.VerifyError in the
768 // app image.
769 if (klass->GetStatus() == mirror::Class::kStatusError) {
770 result = true;
771 } else {
772 CHECK(klass->GetVerifyError() == nullptr) << PrettyClass(klass);
773 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800774 if (!result) {
775 // Check interfaces since these wont be visited through VisitReferences.)
776 mirror::IfTable* if_table = klass->GetIfTable();
777 for (size_t i = 0, num_interfaces = klass->GetIfTableCount(); i < num_interfaces; ++i) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800778 result = result || ContainsBootClassLoaderNonImageClassInternal(
779 if_table->GetInterface(i),
780 &my_early_exit,
781 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800782 }
783 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800784 if (klass->IsObjectArrayClass()) {
785 result = result || ContainsBootClassLoaderNonImageClassInternal(
786 klass->GetComponentType(),
787 &my_early_exit,
788 visited);
789 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800790 // Check static fields and their classes.
791 size_t num_static_fields = klass->NumReferenceStaticFields();
792 if (num_static_fields != 0 && klass->IsResolved()) {
793 // Presumably GC can happen when we are cross compiling, it should not cause performance
794 // problems to do pointer size logic.
795 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(
796 Runtime::Current()->GetClassLinker()->GetImagePointerSize());
797 for (size_t i = 0u; i < num_static_fields; ++i) {
798 mirror::Object* ref = klass->GetFieldObject<mirror::Object>(field_offset);
799 if (ref != nullptr) {
800 if (ref->IsClass()) {
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800801 result = result ||
802 ContainsBootClassLoaderNonImageClassInternal(
803 ref->AsClass(),
804 &my_early_exit,
805 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800806 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800807 result = result ||
808 ContainsBootClassLoaderNonImageClassInternal(
809 ref->GetClass(),
810 &my_early_exit,
811 visited);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800812 }
813 field_offset = MemberOffset(field_offset.Uint32Value() +
814 sizeof(mirror::HeapReference<mirror::Object>));
815 }
816 }
Mathieu Chartier945c1c12015-11-24 15:37:12 -0800817 result = result ||
818 ContainsBootClassLoaderNonImageClassInternal(
819 klass->GetSuperClass(),
820 &my_early_exit,
821 visited);
822 // Erase the element we stored earlier since we are exiting the function.
823 auto it = visited->find(klass);
824 DCHECK(it != visited->end());
825 visited->erase(it);
826 // Only store result if it is true or none of the calls early exited due to circular
827 // dependencies. If visited is empty then we are the root caller, in this case the cycle was in
828 // a child call and we can remember the result.
829 if (result == true || !my_early_exit || visited->empty()) {
830 prune_class_memo_[klass] = result;
831 }
832 *early_exit |= my_early_exit;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800833 return result;
834}
835
836bool ImageWriter::KeepClass(Class* klass) {
837 if (klass == nullptr) {
838 return false;
839 }
840 if (compile_app_image_) {
841 // For app images, we need to prune boot loader classes that are not in the boot image since
842 // these may have already been loaded when the app image is loaded.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800843 // Keep classes in the boot image space since we don't want to re-resolve these.
844 return Runtime::Current()->GetHeap()->ObjectIsInBootImageSpace(klass) ||
845 !ContainsBootClassLoaderNonImageClass(klass);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800846 }
Ian Rogers1ff3c982014-08-12 02:30:58 -0700847 std::string temp;
848 return compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700849}
850
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700851class NonImageClassesVisitor : public ClassVisitor {
852 public:
853 explicit NonImageClassesVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
854
Mathieu Chartier1aa8ec22016-02-01 10:34:47 -0800855 bool operator()(Class* klass) OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800856 if (!image_writer_->KeepClass(klass)) {
857 classes_to_prune_.insert(klass);
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700858 }
859 return true;
860 }
861
Mathieu Chartier9b1c9b72016-02-02 10:09:58 -0800862 std::unordered_set<mirror::Class*> classes_to_prune_;
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700863 ImageWriter* const image_writer_;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700864};
865
866void ImageWriter::PruneNonImageClasses() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700867 Runtime* runtime = Runtime::Current();
868 ClassLinker* class_linker = runtime->GetClassLinker();
Mathieu Chartiere401d142015-04-22 13:56:20 -0700869 Thread* self = Thread::Current();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700870
871 // Make a list of classes we would like to prune.
Mathieu Chartiere0671ce2015-07-28 17:23:28 -0700872 NonImageClassesVisitor visitor(this);
873 class_linker->VisitClasses(&visitor);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700874
875 // Remove the undesired classes from the class roots.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800876 for (mirror::Class* klass : visitor.classes_to_prune_) {
877 std::string temp;
878 const char* name = klass->GetDescriptor(&temp);
879 VLOG(compiler) << "Pruning class " << name;
880 if (!compile_app_image_) {
881 DCHECK(IsBootClassLoaderClass(klass));
882 }
883 bool result = class_linker->RemoveClass(name, klass->GetClassLoader());
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800884 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700885 }
886
887 // Clear references to removed classes from the DexCaches.
Vladimir Marko05792b92015-08-03 11:56:49 +0100888 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700889
890 ScopedAssertNoThreadSuspension sa(self, __FUNCTION__);
891 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_); // For ClassInClassTable
892 ReaderMutexLock mu2(self, *class_linker->DexLock());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800893 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
894 mirror::DexCache* dex_cache = down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700895 if (dex_cache == nullptr) {
896 continue;
Mathieu Chartiere401d142015-04-22 13:56:20 -0700897 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700898 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
899 Class* klass = dex_cache->GetResolvedType(i);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800900 if (klass != nullptr && !KeepClass(klass)) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700901 dex_cache->SetResolvedType(i, nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700902 }
903 }
Vladimir Marko05792b92015-08-03 11:56:49 +0100904 ArtMethod** resolved_methods = dex_cache->GetResolvedMethods();
905 for (size_t i = 0, num = dex_cache->NumResolvedMethods(); i != num; ++i) {
906 ArtMethod* method =
907 mirror::DexCache::GetElementPtrSize(resolved_methods, i, target_ptr_size_);
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800908 DCHECK(method != nullptr) << "Expected resolution method instead of null method";
909 mirror::Class* declaring_class = method->GetDeclaringClass();
Alex Lightd07e1b32016-02-17 11:59:05 -0800910 // Copied methods may be held live by a class which was not an image class but have a
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800911 // declaring class which is an image class. Set it to the resolution method to be safe and
912 // prevent dangling pointers.
Alex Lightd07e1b32016-02-17 11:59:05 -0800913 if (method->MightBeCopied() || !KeepClass(declaring_class)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800914 mirror::DexCache::SetElementPtrSize(resolved_methods,
915 i,
916 resolution_method,
917 target_ptr_size_);
918 } else {
919 // Check that the class is still in the classes table.
920 DCHECK(class_linker->ClassInClassTable(declaring_class)) << "Class "
921 << PrettyClass(declaring_class) << " not in class linker table";
Brian Carlstrom7940e442013-07-12 13:46:57 -0700922 }
923 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800924 ArtField** resolved_fields = dex_cache->GetResolvedFields();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700925 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800926 ArtField* field = mirror::DexCache::GetElementPtrSize(resolved_fields, i, target_ptr_size_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800927 if (field != nullptr && !KeepClass(field->GetDeclaringClass())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -0700928 dex_cache->SetResolvedField(i, nullptr, target_ptr_size_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700929 }
930 }
Andreas Gampedd9d0552015-03-09 12:57:41 -0700931 // Clean the dex field. It might have been populated during the initialization phase, but
932 // contains data only valid during a real run.
933 dex_cache->SetFieldObject<false>(mirror::DexCache::DexOffset(), nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700934 }
Andreas Gampe8ac75952015-06-02 21:01:45 -0700935
936 // Drop the array class cache in the ClassLinker, as these are roots holding those classes live.
937 class_linker->DropFindArrayClassCache();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800938
939 // Clear to save RAM.
940 prune_class_memo_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700941}
942
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -0800943void ImageWriter::CheckNonImageClassesRemoved() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700944 if (compiler_driver_.GetImageClasses() != nullptr) {
945 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700946 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700947 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700948}
949
950void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
951 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800952 if (obj->IsClass() && !image_writer->IsInBootImage(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700953 Class* klass = obj->AsClass();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800954 if (!image_writer->KeepClass(klass)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700955 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700956 std::string temp;
Mathieu Chartierda5b28a2015-11-05 08:03:47 -0800957 CHECK(image_writer->KeepClass(klass)) << klass->GetDescriptor(&temp)
958 << " " << PrettyDescriptor(klass);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700959 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700960 }
961}
962
963void ImageWriter::DumpImageClasses() {
Andreas Gampeb1fcead2015-04-20 18:53:51 -0700964 auto image_classes = compiler_driver_.GetImageClasses();
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700965 CHECK(image_classes != nullptr);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700966 for (const std::string& image_class : *image_classes) {
967 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700968 }
969}
970
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800971mirror::String* ImageWriter::FindInternedString(mirror::String* string) {
972 Thread* const self = Thread::Current();
973 for (auto& pair : image_info_map_) {
974 const ImageInfo& image_info = pair.second;
975 mirror::String* const found = image_info.intern_table_->LookupStrong(self, string);
976 DCHECK(image_info.intern_table_->LookupWeak(self, string) == nullptr)
977 << string->ToModifiedUtf8();
978 if (found != nullptr) {
979 return found;
980 }
981 }
982 if (compile_app_image_) {
983 Runtime* const runtime = Runtime::Current();
984 mirror::String* found = runtime->GetInternTable()->LookupStrong(self, string);
985 // If we found it in the runtime intern table it could either be in the boot image or interned
986 // during app image compilation. If it was in the boot image return that, otherwise return null
987 // since it belongs to another image space.
988 if (found != nullptr && runtime->GetHeap()->ObjectIsInBootImageSpace(found)) {
989 return found;
990 }
991 DCHECK(runtime->GetInternTable()->LookupWeak(self, string) == nullptr)
992 << string->ToModifiedUtf8();
993 }
994 return nullptr;
995}
996
Igor Murashkinf5b4c502014-11-14 15:01:59 -0800997void ImageWriter::CalculateObjectBinSlots(Object* obj) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -0700998 DCHECK(obj != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700999 // if it is a string, we want to intern it if its not interned.
1000 if (obj->GetClass()->IsStringClass()) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001001 const char* oat_filename = GetOatFilename(obj);
1002 ImageInfo& image_info = GetImageInfo(oat_filename);
1003
Brian Carlstrom7940e442013-07-12 13:46:57 -07001004 // we must be an interned string that was forward referenced and already assigned
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001005 if (IsImageBinSlotAssigned(obj)) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001006 DCHECK_EQ(obj, FindInternedString(obj->AsString()));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001007 return;
1008 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001009 // Need to check if the string is already interned in another image info so that we don't have
1010 // the intern tables of two different images contain the same string.
1011 mirror::String* interned = FindInternedString(obj->AsString());
1012 if (interned == nullptr) {
1013 // Not in another image space, insert to our table.
1014 interned = image_info.intern_table_->InternStrongImageString(obj->AsString());
1015 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001016 if (obj != interned) {
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001017 if (!IsImageBinSlotAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001018 // interned obj is after us, allocate its location early
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001019 AssignImageBinSlot(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001020 }
1021 // point those looking for this object to the interned version.
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001022 SetImageBinSlot(obj, GetImageBinSlot(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001023 return;
1024 }
1025 // else (obj == interned), nothing to do but fall through to the normal case
1026 }
1027
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001028 AssignImageBinSlot(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001029}
1030
Jeff Haodcdc85b2015-12-04 14:06:18 -08001031ObjectArray<Object>* ImageWriter::CreateImageRoots(const char* oat_filename) const {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001032 Runtime* runtime = Runtime::Current();
1033 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001034 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001035 StackHandleScope<3> hs(self);
1036 Handle<Class> object_array_class(hs.NewHandle(
1037 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -07001038
Jeff Haodcdc85b2015-12-04 14:06:18 -08001039 std::unordered_set<const DexFile*> image_dex_files;
1040 for (auto& pair : dex_file_oat_filename_map_) {
1041 const DexFile* image_dex_file = pair.first;
1042 const char* image_oat_filename = pair.second;
1043 if (strcmp(oat_filename, image_oat_filename) == 0) {
1044 image_dex_files.insert(image_dex_file);
1045 }
1046 }
1047
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001048 // build an Object[] of all the DexCaches used in the source_space_.
1049 // Since we can't hold the dex lock when allocating the dex_caches
1050 // ObjectArray, we lock the dex lock twice, first to get the number
1051 // of dex caches first and then lock it again to copy the dex
1052 // caches. We check that the number of dex caches does not change.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001053 size_t dex_cache_count = 0;
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001054 {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001055 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001056 // Count number of dex caches not in the boot image.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001057 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1058 mirror::DexCache* dex_cache =
1059 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001060 const DexFile* dex_file = dex_cache->GetDexFile();
1061 if (!IsInBootImage(dex_cache)) {
1062 dex_cache_count += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1063 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001064 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001065 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001066 Handle<ObjectArray<Object>> dex_caches(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001067 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(), dex_cache_count)));
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001068 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
1069 {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001070 ReaderMutexLock mu(self, *class_linker->DexLock());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001071 size_t non_image_dex_caches = 0;
1072 // Re-count number of non image dex caches.
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001073 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1074 mirror::DexCache* dex_cache =
1075 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001076 const DexFile* dex_file = dex_cache->GetDexFile();
1077 if (!IsInBootImage(dex_cache)) {
1078 non_image_dex_caches += image_dex_files.find(dex_file) != image_dex_files.end() ? 1u : 0u;
1079 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001080 }
1081 CHECK_EQ(dex_cache_count, non_image_dex_caches)
1082 << "The number of non-image dex caches changed.";
Mathieu Chartier673ed3d2015-08-28 14:56:43 -07001083 size_t i = 0;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -08001084 for (const ClassLinker::DexCacheData& data : class_linker->GetDexCachesData()) {
1085 mirror::DexCache* dex_cache =
1086 down_cast<mirror::DexCache*>(self->DecodeJObject(data.weak_root));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001087 const DexFile* dex_file = dex_cache->GetDexFile();
1088 if (!IsInBootImage(dex_cache) && image_dex_files.find(dex_file) != image_dex_files.end()) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001089 dex_caches->Set<false>(i, dex_cache);
1090 ++i;
1091 }
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -07001092 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001093 }
1094
1095 // build an Object[] of the roots needed to restore the runtime
Mathieu Chartiere401d142015-04-22 13:56:20 -07001096 auto image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001097 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001098 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +01001099 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001100 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
Mathieu Chartier2cebb242015-04-21 16:50:40 -07001101 CHECK(image_roots->Get(i) != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001102 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001103 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001104}
1105
Mathieu Chartier590fee92013-09-13 13:46:47 -07001106// Walk instance fields of the given Class. Separate function to allow recursion on the super
1107// class.
1108void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
1109 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001110 StackHandleScope<1> hs(Thread::Current());
1111 Handle<mirror::Class> h_class(hs.NewHandle(klass));
1112 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001113 if (super != nullptr) {
1114 WalkInstanceFields(obj, super);
1115 }
1116 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001117 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Vladimir Marko76649e82014-11-10 18:32:59 +00001118 MemberOffset field_offset = h_class->GetFirstReferenceInstanceFieldOffset();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001119 for (size_t i = 0; i < num_reference_fields; ++i) {
Ian Rogersb0fa5dc2014-04-28 16:47:08 -07001120 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001121 if (value != nullptr) {
1122 WalkFieldsInOrder(value);
1123 }
Vladimir Marko76649e82014-11-10 18:32:59 +00001124 field_offset = MemberOffset(field_offset.Uint32Value() +
1125 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001126 }
1127}
1128
1129// For an unvisited object, visit it then all its children found via fields.
1130void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001131 if (IsInBootImage(obj)) {
1132 // Object is in the image, don't need to fix it up.
1133 return;
1134 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001135 // Use our own visitor routine (instead of GC visitor) to get better locality between
1136 // an object and its fields
1137 if (!IsImageBinSlotAssigned(obj)) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001138 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001139 StackHandleScope<2> hs(Thread::Current());
1140 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
1141 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001142 // visit the object itself.
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001143 CalculateObjectBinSlots(h_obj.Get());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001144 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -07001145 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001146 if (h_obj->IsClass()) {
Mathieu Chartierc7853442015-03-27 14:35:38 -07001147 size_t num_reference_static_fields = klass->NumReferenceStaticFields();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001148 MemberOffset field_offset = klass->GetFirstReferenceStaticFieldOffset(target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001149 for (size_t i = 0; i < num_reference_static_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001150 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001151 if (value != nullptr) {
1152 WalkFieldsInOrder(value);
1153 }
Vladimir Marko76649e82014-11-10 18:32:59 +00001154 field_offset = MemberOffset(field_offset.Uint32Value() +
1155 sizeof(mirror::HeapReference<mirror::Object>));
Mathieu Chartier590fee92013-09-13 13:46:47 -07001156 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001157 // Visit and assign offsets for fields and field arrays.
Mathieu Chartiere401d142015-04-22 13:56:20 -07001158 auto* as_klass = h_obj->AsClass();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001159 mirror::DexCache* dex_cache = as_klass->GetDexCache();
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001160 DCHECK_NE(klass->GetStatus(), mirror::Class::kStatusError);
1161 if (compile_app_image_) {
1162 // Extra sanity, no boot loader classes should be left!
1163 CHECK(!IsBootClassLoaderClass(as_klass)) << PrettyClass(as_klass);
1164 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001165 LengthPrefixedArray<ArtField>* fields[] = {
1166 as_klass->GetSFieldsPtr(), as_klass->GetIFieldsPtr(),
1167 };
Jeff Haodcdc85b2015-12-04 14:06:18 -08001168 const char* oat_file = GetOatFilenameForDexCache(dex_cache);
1169 ImageInfo& image_info = GetImageInfo(oat_file);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001170 {
1171 // Note: This table is only accessed from the image writer, so the lock is technically
1172 // unnecessary.
1173 WriterMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
1174 // Insert in the class table for this iamge.
1175 image_info.class_table_->Insert(as_klass);
1176 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001177 for (LengthPrefixedArray<ArtField>* cur_fields : fields) {
1178 // Total array length including header.
1179 if (cur_fields != nullptr) {
1180 const size_t header_size = LengthPrefixedArray<ArtField>::ComputeSize(0);
1181 // Forward the entire array at once.
1182 auto it = native_object_relocations_.find(cur_fields);
1183 CHECK(it == native_object_relocations_.end()) << "Field array " << cur_fields
1184 << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001185 size_t& offset = image_info.bin_slot_sizes_[kBinArtField];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001186 DCHECK(!IsInBootImage(cur_fields));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001187 native_object_relocations_.emplace(cur_fields,
1188 NativeObjectRelocation {oat_file, offset, kNativeObjectRelocationTypeArtFieldArray });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001189 offset += header_size;
1190 // Forward individual fields so that we can quickly find where they belong.
Vladimir Marko35831e82015-09-11 11:59:18 +01001191 for (size_t i = 0, count = cur_fields->size(); i < count; ++i) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001192 // Need to forward arrays separate of fields.
1193 ArtField* field = &cur_fields->At(i);
1194 auto it2 = native_object_relocations_.find(field);
1195 CHECK(it2 == native_object_relocations_.end()) << "Field at index=" << i
1196 << " already assigned " << PrettyField(field) << " static=" << field->IsStatic();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001197 DCHECK(!IsInBootImage(field));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001198 native_object_relocations_.emplace(field,
1199 NativeObjectRelocation {oat_file, offset, kNativeObjectRelocationTypeArtField });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001200 offset += sizeof(ArtField);
1201 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001202 }
1203 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001204 // Visit and assign offsets for methods.
Alex Lighte64300b2015-12-15 15:02:47 -08001205 size_t num_methods = as_klass->NumMethods();
1206 if (num_methods != 0) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001207 bool any_dirty = false;
Alex Lighte64300b2015-12-15 15:02:47 -08001208 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
1209 if (WillMethodBeDirty(&m)) {
1210 any_dirty = true;
1211 break;
1212 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001213 }
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001214 NativeObjectRelocationType type = any_dirty
1215 ? kNativeObjectRelocationTypeArtMethodDirty
1216 : kNativeObjectRelocationTypeArtMethodClean;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001217 Bin bin_type = BinTypeForNativeRelocationType(type);
1218 // Forward the entire array at once, but header first.
Alex Lighte64300b2015-12-15 15:02:47 -08001219 const size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
1220 const size_t method_size = ArtMethod::Size(target_ptr_size_);
Vladimir Markocf36d492015-08-12 19:27:26 +01001221 const size_t header_size = LengthPrefixedArray<ArtMethod>::ComputeSize(0,
1222 method_size,
1223 method_alignment);
Alex Lighte64300b2015-12-15 15:02:47 -08001224 LengthPrefixedArray<ArtMethod>* array = as_klass->GetMethodsPtr();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001225 auto it = native_object_relocations_.find(array);
Alex Lighte64300b2015-12-15 15:02:47 -08001226 CHECK(it == native_object_relocations_.end())
1227 << "Method array " << array << " already forwarded";
Jeff Haodcdc85b2015-12-04 14:06:18 -08001228 size_t& offset = image_info.bin_slot_sizes_[bin_type];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001229 DCHECK(!IsInBootImage(array));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001230 native_object_relocations_.emplace(array,
1231 NativeObjectRelocation {
1232 oat_file,
1233 offset,
1234 any_dirty ? kNativeObjectRelocationTypeArtMethodArrayDirty
1235 : kNativeObjectRelocationTypeArtMethodArrayClean });
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001236 offset += header_size;
Alex Lighte64300b2015-12-15 15:02:47 -08001237 for (auto& m : as_klass->GetMethods(target_ptr_size_)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001238 AssignMethodOffset(&m, type, oat_file);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001239 }
Alex Lighte64300b2015-12-15 15:02:47 -08001240 (any_dirty ? dirty_methods_ : clean_methods_) += num_methods;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001241 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001242 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -07001243 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001244 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001245 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001246 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001247 mirror::Object* value = obj_array->Get(i);
1248 if (value != nullptr) {
1249 WalkFieldsInOrder(value);
1250 }
1251 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001252 } else if (h_obj->IsClassLoader()) {
1253 // Register the class loader if it has a class table.
1254 // The fake boot class loader should not get registered and we should end up with only one
1255 // class loader.
1256 mirror::ClassLoader* class_loader = h_obj->AsClassLoader();
1257 if (class_loader->GetClassTable() != nullptr) {
1258 class_loaders_.insert(class_loader);
1259 }
Mathieu Chartier590fee92013-09-13 13:46:47 -07001260 }
1261 }
1262}
1263
Jeff Haodcdc85b2015-12-04 14:06:18 -08001264void ImageWriter::AssignMethodOffset(ArtMethod* method,
1265 NativeObjectRelocationType type,
1266 const char* oat_filename) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001267 DCHECK(!IsInBootImage(method));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001268 auto it = native_object_relocations_.find(method);
1269 CHECK(it == native_object_relocations_.end()) << "Method " << method << " already assigned "
Mathieu Chartiere401d142015-04-22 13:56:20 -07001270 << PrettyMethod(method);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001271 ImageInfo& image_info = GetImageInfo(oat_filename);
1272 size_t& offset = image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(type)];
1273 native_object_relocations_.emplace(method, NativeObjectRelocation { oat_filename, offset, type });
Vladimir Marko14632852015-08-17 12:07:23 +01001274 offset += ArtMethod::Size(target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001275}
1276
Mathieu Chartier590fee92013-09-13 13:46:47 -07001277void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
1278 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1279 DCHECK(writer != nullptr);
1280 writer->WalkFieldsInOrder(obj);
1281}
1282
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001283void ImageWriter::UnbinObjectsIntoOffsetCallback(mirror::Object* obj, void* arg) {
1284 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
1285 DCHECK(writer != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001286 if (!writer->IsInBootImage(obj)) {
1287 writer->UnbinObjectsIntoOffset(obj);
1288 }
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001289}
1290
1291void ImageWriter::UnbinObjectsIntoOffset(mirror::Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001292 DCHECK(!IsInBootImage(obj));
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001293 CHECK(obj != nullptr);
1294
1295 // We know the bin slot, and the total bin sizes for all objects by now,
1296 // so calculate the object's final image offset.
1297
1298 DCHECK(IsImageBinSlotAssigned(obj));
1299 BinSlot bin_slot = GetImageBinSlot(obj);
1300 // Change the lockword from a bin slot into an offset
1301 AssignImageOffset(obj, bin_slot);
1302}
1303
Vladimir Markof4da6752014-08-01 19:04:18 +01001304void ImageWriter::CalculateNewObjectOffsets() {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001305 Thread* const self = Thread::Current();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001306 StackHandleScopeCollection handles(self);
1307 std::vector<Handle<ObjectArray<Object>>> image_roots;
1308 for (const char* oat_filename : oat_filenames_) {
1309 std::string image_filename = oat_filename;
1310 image_roots.push_back(handles.NewHandle(CreateImageRoots(image_filename.c_str())));
1311 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001312
Mathieu Chartiere401d142015-04-22 13:56:20 -07001313 auto* runtime = Runtime::Current();
1314 auto* heap = runtime->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001315
Mathieu Chartier31e89252013-08-28 11:29:12 -07001316 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -07001317 // know where image_roots is going to end up
Jeff Haodcdc85b2015-12-04 14:06:18 -08001318 image_objects_offset_begin_ = RoundUp(sizeof(ImageHeader), kObjectAlignment); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -07001319
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001320 // Clear any pre-existing monitors which may have been in the monitor words, assign bin slots.
1321 heap->VisitObjects(WalkFieldsCallback, this);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001322 // Write the image runtime methods.
1323 image_methods_[ImageHeader::kResolutionMethod] = runtime->GetResolutionMethod();
1324 image_methods_[ImageHeader::kImtConflictMethod] = runtime->GetImtConflictMethod();
1325 image_methods_[ImageHeader::kImtUnimplementedMethod] = runtime->GetImtUnimplementedMethod();
1326 image_methods_[ImageHeader::kCalleeSaveMethod] = runtime->GetCalleeSaveMethod(Runtime::kSaveAll);
1327 image_methods_[ImageHeader::kRefsOnlySaveMethod] =
1328 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly);
1329 image_methods_[ImageHeader::kRefsAndArgsSaveMethod] =
1330 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001331
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001332 // Add room for fake length prefixed array for holding the image methods.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001333 const auto image_method_type = kNativeObjectRelocationTypeArtMethodArrayClean;
1334 auto it = native_object_relocations_.find(&image_method_array_);
1335 CHECK(it == native_object_relocations_.end());
Jeff Haodcdc85b2015-12-04 14:06:18 -08001336 ImageInfo& default_image_info = GetImageInfo(default_oat_filename_);
1337 size_t& offset =
1338 default_image_info.bin_slot_sizes_[BinTypeForNativeRelocationType(image_method_type)];
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001339 if (!compile_app_image_) {
1340 native_object_relocations_.emplace(&image_method_array_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001341 NativeObjectRelocation { default_oat_filename_, offset, image_method_type });
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001342 }
Vladimir Marko14632852015-08-17 12:07:23 +01001343 size_t method_alignment = ArtMethod::Alignment(target_ptr_size_);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001344 const size_t array_size = LengthPrefixedArray<ArtMethod>::ComputeSize(
Vladimir Marko14632852015-08-17 12:07:23 +01001345 0, ArtMethod::Size(target_ptr_size_), method_alignment);
Vladimir Markocf36d492015-08-12 19:27:26 +01001346 CHECK_ALIGNED_PARAM(array_size, method_alignment);
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001347 offset += array_size;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001348 for (auto* m : image_methods_) {
1349 CHECK(m != nullptr);
1350 CHECK(m->IsRuntimeMethod());
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001351 DCHECK_EQ(compile_app_image_, IsInBootImage(m)) << "Trampolines should be in boot image";
1352 if (!IsInBootImage(m)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001353 AssignMethodOffset(m, kNativeObjectRelocationTypeArtMethodClean, default_oat_filename_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001354 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001355 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001356 // Calculate size of the dex cache arrays slot and prepare offsets.
1357 PrepareDexCacheArraySlots();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001358
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001359 // Calculate the sizes of the intern tables and class tables.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001360 for (const char* oat_filename : oat_filenames_) {
1361 ImageInfo& image_info = GetImageInfo(oat_filename);
1362 // Calculate how big the intern table will be after being serialized.
1363 InternTable* const intern_table = image_info.intern_table_.get();
1364 CHECK_EQ(intern_table->WeakSize(), 0u) << " should have strong interned all the strings";
1365 image_info.intern_table_bytes_ = intern_table->WriteToMemory(nullptr);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001366 // Calculate the size of the class table.
1367 ReaderMutexLock mu(self, *Locks::classlinker_classes_lock_);
1368 image_info.class_table_bytes_ += image_info.class_table_->WriteToMemory(nullptr);
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001369 }
1370
Vladimir Markocf36d492015-08-12 19:27:26 +01001371 // Calculate bin slot offsets.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001372 for (const char* oat_filename : oat_filenames_) {
1373 ImageInfo& image_info = GetImageInfo(oat_filename);
1374 size_t bin_offset = image_objects_offset_begin_;
1375 for (size_t i = 0; i != kBinSize; ++i) {
1376 image_info.bin_slot_offsets_[i] = bin_offset;
1377 bin_offset += image_info.bin_slot_sizes_[i];
1378 if (i == kBinArtField) {
1379 static_assert(kBinArtField + 1 == kBinArtMethodClean, "Methods follow fields.");
1380 static_assert(alignof(ArtField) == 4u, "ArtField alignment is 4.");
1381 DCHECK_ALIGNED(bin_offset, 4u);
1382 DCHECK(method_alignment == 4u || method_alignment == 8u);
1383 bin_offset = RoundUp(bin_offset, method_alignment);
1384 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001385 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08001386 // NOTE: There may be additional padding between the bin slots and the intern table.
1387 DCHECK_EQ(image_info.image_end_,
1388 GetBinSizeSum(image_info, kBinMirrorCount) + image_objects_offset_begin_);
Vladimir Marko20f85592015-03-19 10:07:02 +00001389 }
Vladimir Markocf36d492015-08-12 19:27:26 +01001390
Jeff Haodcdc85b2015-12-04 14:06:18 -08001391 // Calculate image offsets.
1392 size_t image_offset = 0;
1393 for (const char* oat_filename : oat_filenames_) {
1394 ImageInfo& image_info = GetImageInfo(oat_filename);
1395 image_info.image_begin_ = global_image_begin_ + image_offset;
1396 image_info.image_offset_ = image_offset;
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001397 ImageSection unused_sections[ImageHeader::kSectionCount];
1398 image_info.image_size_ = RoundUp(
1399 image_info.CreateImageSections(target_ptr_size_, unused_sections),
1400 kPageSize);
1401 // There should be no gaps until the next image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001402 image_offset += image_info.image_size_;
1403 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001404
Hiroshi Yamauchi0c8c3032015-01-16 16:54:35 -08001405 // Transform each object's bin slot into an offset which will be used to do the final copy.
1406 heap->VisitObjects(UnbinObjectsIntoOffsetCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001407
Jeff Haodcdc85b2015-12-04 14:06:18 -08001408 // DCHECK_EQ(image_end_, GetBinSizeSum(kBinMirrorCount) + image_objects_offset_begin_);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001409
Jeff Haodcdc85b2015-12-04 14:06:18 -08001410 size_t i = 0;
1411 for (const char* oat_filename : oat_filenames_) {
1412 ImageInfo& image_info = GetImageInfo(oat_filename);
1413 image_info.image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots[i].Get()));
1414 i++;
1415 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001416
Mathieu Chartiere401d142015-04-22 13:56:20 -07001417 // Update the native relocations by adding their bin sums.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001418 for (auto& pair : native_object_relocations_) {
1419 NativeObjectRelocation& relocation = pair.second;
1420 Bin bin_type = BinTypeForNativeRelocationType(relocation.type);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001421 ImageInfo& image_info = GetImageInfo(relocation.oat_filename);
1422 relocation.offset += image_info.bin_slot_offsets_[bin_type];
Mathieu Chartiere401d142015-04-22 13:56:20 -07001423 }
1424
Jeff Haodcdc85b2015-12-04 14:06:18 -08001425 // Note that image_info.image_end_ is left at end of used mirror object section.
Vladimir Markof4da6752014-08-01 19:04:18 +01001426}
1427
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001428size_t ImageWriter::ImageInfo::CreateImageSections(size_t target_ptr_size,
1429 ImageSection* out_sections) const {
1430 DCHECK(out_sections != nullptr);
1431 // Objects section
1432 auto* objects_section = &out_sections[ImageHeader::kSectionObjects];
1433 *objects_section = ImageSection(0u, image_end_);
1434 size_t cur_pos = objects_section->End();
1435 // Add field section.
1436 auto* field_section = &out_sections[ImageHeader::kSectionArtFields];
1437 *field_section = ImageSection(cur_pos, bin_slot_sizes_[kBinArtField]);
1438 CHECK_EQ(bin_slot_offsets_[kBinArtField], field_section->Offset());
1439 cur_pos = field_section->End();
1440 // Round up to the alignment the required by the method section.
1441 cur_pos = RoundUp(cur_pos, ArtMethod::Alignment(target_ptr_size));
1442 // Add method section.
1443 auto* methods_section = &out_sections[ImageHeader::kSectionArtMethods];
1444 *methods_section = ImageSection(cur_pos,
1445 bin_slot_sizes_[kBinArtMethodClean] +
1446 bin_slot_sizes_[kBinArtMethodDirty]);
1447 CHECK_EQ(bin_slot_offsets_[kBinArtMethodClean], methods_section->Offset());
1448 cur_pos = methods_section->End();
1449 // Add dex cache arrays section.
1450 auto* dex_cache_arrays_section = &out_sections[ImageHeader::kSectionDexCacheArrays];
1451 *dex_cache_arrays_section = ImageSection(cur_pos, bin_slot_sizes_[kBinDexCacheArray]);
1452 CHECK_EQ(bin_slot_offsets_[kBinDexCacheArray], dex_cache_arrays_section->Offset());
1453 cur_pos = dex_cache_arrays_section->End();
1454 // Round up to the alignment the string table expects. See HashSet::WriteToMemory.
1455 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1456 // Calculate the size of the interned strings.
1457 auto* interned_strings_section = &out_sections[ImageHeader::kSectionInternedStrings];
1458 *interned_strings_section = ImageSection(cur_pos, intern_table_bytes_);
1459 cur_pos = interned_strings_section->End();
1460 // Round up to the alignment the class table expects. See HashSet::WriteToMemory.
1461 cur_pos = RoundUp(cur_pos, sizeof(uint64_t));
1462 // Calculate the size of the class table section.
1463 auto* class_table_section = &out_sections[ImageHeader::kSectionClassTable];
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001464 *class_table_section = ImageSection(cur_pos, class_table_bytes_);
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001465 cur_pos = class_table_section->End();
1466 // Image end goes right before the start of the image bitmap.
1467 return cur_pos;
1468}
1469
Vladimir Markof4da6752014-08-01 19:04:18 +01001470void ImageWriter::CreateHeader(size_t oat_loaded_size, size_t oat_data_offset) {
1471 CHECK_NE(0U, oat_loaded_size);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001472 const char* oat_filename = oat_file_->GetLocation().c_str();
1473 ImageInfo& image_info = GetImageInfo(oat_filename);
1474 const uint8_t* oat_file_begin = GetOatFileBegin(oat_filename);
Ian Rogers13735952014-10-08 12:43:28 -07001475 const uint8_t* oat_file_end = oat_file_begin + oat_loaded_size;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001476 image_info.oat_data_begin_ = const_cast<uint8_t*>(oat_file_begin) + oat_data_offset;
1477 const uint8_t* oat_data_end = image_info.oat_data_begin_ + oat_file_->Size();
1478 image_info.oat_size_ = oat_file_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001479
1480 // Create the image sections.
1481 ImageSection sections[ImageHeader::kSectionCount];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001482 const size_t image_end = image_info.CreateImageSections(target_ptr_size_, sections);
1483
Mathieu Chartiere401d142015-04-22 13:56:20 -07001484 // Finally bitmap section.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001485 const size_t bitmap_bytes = image_info.image_bitmap_->Size();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001486 auto* bitmap_section = &sections[ImageHeader::kSectionImageBitmap];
Mathieu Chartiera06ba052016-01-06 13:51:52 -08001487 *bitmap_section = ImageSection(RoundUp(image_end, kPageSize), RoundUp(bitmap_bytes, kPageSize));
Jeff Haodcdc85b2015-12-04 14:06:18 -08001488 if (VLOG_IS_ON(compiler)) {
1489 LOG(INFO) << "Creating header for " << oat_filename;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001490 size_t idx = 0;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001491 for (const ImageSection& section : sections) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001492 LOG(INFO) << static_cast<ImageHeader::ImageSections>(idx) << " " << section;
1493 ++idx;
1494 }
1495 LOG(INFO) << "Methods: clean=" << clean_methods_ << " dirty=" << dirty_methods_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001496 LOG(INFO) << "Image roots address=" << std::hex << image_info.image_roots_address_ << std::dec;
1497 LOG(INFO) << "Image begin=" << std::hex << reinterpret_cast<uintptr_t>(global_image_begin_)
1498 << " Image offset=" << image_info.image_offset_ << std::dec;
1499 LOG(INFO) << "Oat file begin=" << std::hex << reinterpret_cast<uintptr_t>(oat_file_begin)
1500 << " Oat data begin=" << reinterpret_cast<uintptr_t>(image_info.oat_data_begin_)
1501 << " Oat data end=" << reinterpret_cast<uintptr_t>(oat_data_end)
1502 << " Oat file end=" << reinterpret_cast<uintptr_t>(oat_file_end);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001503 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001504 // Store boot image info for app image so that we can relocate.
1505 uint32_t boot_image_begin = 0;
1506 uint32_t boot_image_end = 0;
1507 uint32_t boot_oat_begin = 0;
1508 uint32_t boot_oat_end = 0;
1509 gc::Heap* const heap = Runtime::Current()->GetHeap();
1510 heap->GetBootImagesSize(&boot_image_begin, &boot_image_end, &boot_oat_begin, &boot_oat_end);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001511
Mathieu Chartierceb07b32015-12-10 09:33:21 -08001512 // Create the header, leave 0 for data size since we will fill this in as we are writing the
1513 // image.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001514 new (image_info.image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_info.image_begin_),
1515 image_end,
1516 sections,
1517 image_info.image_roots_address_,
1518 oat_file_->GetOatHeader().GetChecksum(),
1519 PointerToLowMemUInt32(oat_file_begin),
1520 PointerToLowMemUInt32(image_info.oat_data_begin_),
1521 PointerToLowMemUInt32(oat_data_end),
1522 PointerToLowMemUInt32(oat_file_end),
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001523 boot_image_begin,
1524 boot_image_end - boot_image_begin,
1525 boot_oat_begin,
1526 boot_oat_end - boot_oat_begin,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001527 target_ptr_size_,
1528 compile_pic_,
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001529 /*is_pic*/compile_app_image_,
Jeff Haodcdc85b2015-12-04 14:06:18 -08001530 image_storage_mode_,
1531 /*data_size*/0u);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001532}
1533
1534ArtMethod* ImageWriter::GetImageMethodAddress(ArtMethod* method) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001535 auto it = native_object_relocations_.find(method);
1536 CHECK(it != native_object_relocations_.end()) << PrettyMethod(method) << " @ " << method;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001537 const char* oat_filename = GetOatFilename(method->GetDexCache());
1538 ImageInfo& image_info = GetImageInfo(oat_filename);
1539 CHECK_GE(it->second.offset, image_info.image_end_) << "ArtMethods should be after Objects";
1540 return reinterpret_cast<ArtMethod*>(image_info.image_begin_ + it->second.offset);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001541}
1542
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001543class FixupRootVisitor : public RootVisitor {
1544 public:
1545 explicit FixupRootVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {
1546 }
1547
1548 void VisitRoots(mirror::Object*** roots, size_t count, const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001549 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001550 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001551 *roots[i] = image_writer_->GetImageAddress(*roots[i]);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001552 }
1553 }
1554
1555 void VisitRoots(mirror::CompressedReference<mirror::Object>** roots, size_t count,
1556 const RootInfo& info ATTRIBUTE_UNUSED)
Mathieu Chartier90443472015-07-16 20:32:27 -07001557 OVERRIDE SHARED_REQUIRES(Locks::mutator_lock_) {
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001558 for (size_t i = 0; i < count; ++i) {
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001559 roots[i]->Assign(image_writer_->GetImageAddress(roots[i]->AsMirrorPtr()));
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001560 }
1561 }
1562
1563 private:
1564 ImageWriter* const image_writer_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001565};
1566
Mathieu Chartierc7853442015-03-27 14:35:38 -07001567void ImageWriter::CopyAndFixupNativeData() {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001568 const char* oat_filename = oat_file_->GetLocation().c_str();
1569 ImageInfo& image_info = GetImageInfo(oat_filename);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001570 // Copy ArtFields and methods to their locations and update the array for convenience.
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001571 for (auto& pair : native_object_relocations_) {
1572 NativeObjectRelocation& relocation = pair.second;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001573 // Only work with fields and methods that are in the current oat file.
1574 if (strcmp(relocation.oat_filename, oat_filename) != 0) {
1575 continue;
1576 }
1577 auto* dest = image_info.image_->Begin() + relocation.offset;
1578 DCHECK_GE(dest, image_info.image_->Begin() + image_info.image_end_);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001579 DCHECK(!IsInBootImage(pair.first));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001580 switch (relocation.type) {
1581 case kNativeObjectRelocationTypeArtField: {
1582 memcpy(dest, pair.first, sizeof(ArtField));
1583 reinterpret_cast<ArtField*>(dest)->SetDeclaringClass(
1584 GetImageAddress(reinterpret_cast<ArtField*>(pair.first)->GetDeclaringClass()));
1585 break;
1586 }
1587 case kNativeObjectRelocationTypeArtMethodClean:
1588 case kNativeObjectRelocationTypeArtMethodDirty: {
1589 CopyAndFixupMethod(reinterpret_cast<ArtMethod*>(pair.first),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001590 reinterpret_cast<ArtMethod*>(dest),
1591 image_info);
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001592 break;
1593 }
1594 // For arrays, copy just the header since the elements will get copied by their corresponding
1595 // relocations.
1596 case kNativeObjectRelocationTypeArtFieldArray: {
1597 memcpy(dest, pair.first, LengthPrefixedArray<ArtField>::ComputeSize(0));
1598 break;
1599 }
1600 case kNativeObjectRelocationTypeArtMethodArrayClean:
1601 case kNativeObjectRelocationTypeArtMethodArrayDirty: {
Vladimir Markocf36d492015-08-12 19:27:26 +01001602 memcpy(dest, pair.first, LengthPrefixedArray<ArtMethod>::ComputeSize(
1603 0,
Vladimir Marko14632852015-08-17 12:07:23 +01001604 ArtMethod::Size(target_ptr_size_),
1605 ArtMethod::Alignment(target_ptr_size_)));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001606 break;
Vladimir Marko05792b92015-08-03 11:56:49 +01001607 case kNativeObjectRelocationTypeDexCacheArray:
1608 // Nothing to copy here, everything is done in FixupDexCache().
1609 break;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001610 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001611 }
1612 }
1613 // Fixup the image method roots.
Jeff Haodcdc85b2015-12-04 14:06:18 -08001614 auto* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001615 const ImageSection& methods_section = image_header->GetMethodsSection();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001616 for (size_t i = 0; i < ImageHeader::kImageMethodsCount; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001617 ArtMethod* method = image_methods_[i];
1618 CHECK(method != nullptr);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001619 // Only place runtime methods in the image of the default oat file.
1620 if (method->IsRuntimeMethod() && strcmp(default_oat_filename_, oat_filename) != 0) {
1621 continue;
1622 }
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001623 if (!IsInBootImage(method)) {
1624 auto it = native_object_relocations_.find(method);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001625 CHECK(it != native_object_relocations_.end()) << "No forwarding for " << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001626 NativeObjectRelocation& relocation = it->second;
1627 CHECK(methods_section.Contains(relocation.offset)) << relocation.offset << " not in "
1628 << methods_section;
1629 CHECK(relocation.IsArtMethodRelocation()) << relocation.type;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001630 method = reinterpret_cast<ArtMethod*>(global_image_begin_ + it->second.offset);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001631 }
1632 image_header->SetImageMethod(static_cast<ImageHeader::ImageMethod>(i), method);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001633 }
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001634 FixupRootVisitor root_visitor(this);
1635
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001636 // Write the intern table into the image.
Mathieu Chartierea0831f2015-12-29 13:17:37 -08001637 if (image_info.intern_table_bytes_ > 0) {
1638 const ImageSection& intern_table_section = image_header->GetImageSection(
1639 ImageHeader::kSectionInternedStrings);
1640 InternTable* const intern_table = image_info.intern_table_.get();
1641 uint8_t* const intern_table_memory_ptr =
1642 image_info.image_->Begin() + intern_table_section.Offset();
1643 const size_t intern_table_bytes = intern_table->WriteToMemory(intern_table_memory_ptr);
1644 CHECK_EQ(intern_table_bytes, image_info.intern_table_bytes_);
1645 // Fixup the pointers in the newly written intern table to contain image addresses.
1646 InternTable temp_intern_table;
1647 // Note that we require that ReadFromMemory does not make an internal copy of the elements so that
1648 // the VisitRoots() will update the memory directly rather than the copies.
1649 // This also relies on visit roots not doing any verification which could fail after we update
1650 // the roots to be the image addresses.
1651 temp_intern_table.AddTableFromMemory(intern_table_memory_ptr);
1652 CHECK_EQ(temp_intern_table.Size(), intern_table->Size());
1653 temp_intern_table.VisitRoots(&root_visitor, kVisitRootFlagAllRoots);
1654 }
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001655 // Write the class table(s) into the image. class_table_bytes_ may be 0 if there are multiple
1656 // class loaders. Writing multiple class tables into the image is currently unsupported.
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001657 if (image_info.class_table_bytes_ > 0u) {
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001658 const ImageSection& class_table_section = image_header->GetImageSection(
1659 ImageHeader::kSectionClassTable);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001660 uint8_t* const class_table_memory_ptr =
1661 image_info.image_->Begin() + class_table_section.Offset();
Mathieu Chartier67ad20e2015-12-09 15:41:09 -08001662 ReaderMutexLock mu(Thread::Current(), *Locks::classlinker_classes_lock_);
Mathieu Chartier1f47b672016-01-07 16:29:01 -08001663
1664 ClassTable* table = image_info.class_table_.get();
1665 CHECK(table != nullptr);
1666 const size_t class_table_bytes = table->WriteToMemory(class_table_memory_ptr);
1667 CHECK_EQ(class_table_bytes, image_info.class_table_bytes_);
1668 // Fixup the pointers in the newly written class table to contain image addresses. See
1669 // above comment for intern tables.
1670 ClassTable temp_class_table;
1671 temp_class_table.ReadFromMemory(class_table_memory_ptr);
1672 CHECK_EQ(temp_class_table.NumZygoteClasses(), table->NumNonZygoteClasses() +
1673 table->NumZygoteClasses());
1674 BufferedRootVisitor<kDefaultBufferedRootCount> buffered_visitor(&root_visitor,
1675 RootInfo(kRootUnknown));
1676 temp_class_table.VisitRoots(buffered_visitor);
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001677 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001678}
1679
Mathieu Chartierfd04b6f2014-11-14 19:34:18 -08001680void ImageWriter::CopyAndFixupObjects() {
Brian Carlstrom7940e442013-07-12 13:46:57 -07001681 gc::Heap* heap = Runtime::Current()->GetHeap();
Mathieu Chartier590fee92013-09-13 13:46:47 -07001682 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
1683 // Fix up the object previously had hash codes.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001684 for (const auto& hash_pair : saved_hashcode_map_) {
Hiroshi Yamauchie15ea082015-02-09 17:11:42 -08001685 Object* obj = hash_pair.first;
Andreas Gampe3b45ef22015-05-26 21:34:09 -07001686 DCHECK_EQ(obj->GetLockWord<kVerifyNone>(false).ReadBarrierState(), 0U);
1687 obj->SetLockWord<kVerifyNone>(LockWord::FromHashCode(hash_pair.second, 0U), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -07001688 }
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001689 saved_hashcode_map_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -07001690}
1691
Mathieu Chartier590fee92013-09-13 13:46:47 -07001692void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -07001693 DCHECK(obj != nullptr);
1694 DCHECK(arg != nullptr);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001695 reinterpret_cast<ImageWriter*>(arg)->CopyAndFixupObject(obj);
1696}
1697
Mathieu Chartiere401d142015-04-22 13:56:20 -07001698void ImageWriter::FixupPointerArray(mirror::Object* dst, mirror::PointerArray* arr,
1699 mirror::Class* klass, Bin array_type) {
1700 CHECK(klass->IsArrayClass());
1701 CHECK(arr->IsIntArray() || arr->IsLongArray()) << PrettyClass(klass) << " " << arr;
1702 // Fixup int and long pointers for the ArtMethod or ArtField arrays.
Mathieu Chartierc7853442015-03-27 14:35:38 -07001703 const size_t num_elements = arr->GetLength();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001704 dst->SetClass(GetImageAddress(arr->GetClass()));
1705 auto* dest_array = down_cast<mirror::PointerArray*>(dst);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001706 for (size_t i = 0, count = num_elements; i < count; ++i) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001707 void* elem = arr->GetElementPtrSize<void*>(i, target_ptr_size_);
1708 if (elem != nullptr && !IsInBootImage(elem)) {
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001709 auto it = native_object_relocations_.find(elem);
Vladimir Marko05792b92015-08-03 11:56:49 +01001710 if (UNLIKELY(it == native_object_relocations_.end())) {
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001711 if (it->second.IsArtMethodRelocation()) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001712 auto* method = reinterpret_cast<ArtMethod*>(elem);
1713 LOG(FATAL) << "No relocation entry for ArtMethod " << PrettyMethod(method) << " @ "
1714 << method << " idx=" << i << "/" << num_elements << " with declaring class "
1715 << PrettyClass(method->GetDeclaringClass());
1716 } else {
1717 CHECK_EQ(array_type, kBinArtField);
1718 auto* field = reinterpret_cast<ArtField*>(elem);
1719 LOG(FATAL) << "No relocation entry for ArtField " << PrettyField(field) << " @ "
1720 << field << " idx=" << i << "/" << num_elements << " with declaring class "
1721 << PrettyClass(field->GetDeclaringClass());
1722 }
Vladimir Marko05792b92015-08-03 11:56:49 +01001723 UNREACHABLE();
Mathieu Chartiere401d142015-04-22 13:56:20 -07001724 } else {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001725 ImageInfo& image_info = GetImageInfo(it->second.oat_filename);
1726 elem = image_info.image_begin_ + it->second.offset;
Mathieu Chartiere401d142015-04-22 13:56:20 -07001727 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001728 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001729 dest_array->SetElementPtrSize<false, true>(i, elem, target_ptr_size_);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001730 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001731}
1732
1733void ImageWriter::CopyAndFixupObject(Object* obj) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001734 if (IsInBootImage(obj)) {
1735 return;
1736 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001737 size_t offset = GetImageOffset(obj);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001738 const char* oat_filename = GetOatFilename(obj);
1739 ImageInfo& image_info = GetImageInfo(oat_filename);
1740 auto* dst = reinterpret_cast<Object*>(image_info.image_->Begin() + offset);
1741 DCHECK_LT(offset, image_info.image_end_);
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001742 const auto* src = reinterpret_cast<const uint8_t*>(obj);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001743
Jeff Haodcdc85b2015-12-04 14:06:18 -08001744 image_info.image_bitmap_->Set(dst); // Mark the obj as live.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001745
1746 const size_t n = obj->SizeOf();
Jeff Haodcdc85b2015-12-04 14:06:18 -08001747 DCHECK_LE(offset + n, image_info.image_->Size());
Brian Carlstrom7940e442013-07-12 13:46:57 -07001748 memcpy(dst, src, n);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001749
Mathieu Chartierad2541a2013-10-25 10:05:23 -07001750 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
1751 // word.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001752 const auto it = saved_hashcode_map_.find(obj);
1753 dst->SetLockWord(it != saved_hashcode_map_.end() ?
1754 LockWord::FromHashCode(it->second, 0u) : LockWord::Default(), false);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001755 FixupObject(obj, dst);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001756}
1757
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001758// Rewrite all the references in the copied object to point to their image address equivalent
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001759class FixupVisitor {
1760 public:
1761 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
1762 }
1763
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001764 // Ignore class roots since we don't have a way to map them to the destination. These are handled
1765 // with other logic.
1766 void VisitRootIfNonNull(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED)
1767 const {}
1768 void VisitRoot(mirror::CompressedReference<mirror::Object>* root ATTRIBUTE_UNUSED) const {}
1769
1770
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001771 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001772 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -07001773 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001774 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
1775 // image.
1776 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001777 offset,
1778 image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001779 }
1780
1781 // java.lang.ref.Reference visitor.
Mathieu Chartierd39645e2015-06-09 17:50:29 -07001782 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED, mirror::Reference* ref) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001783 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001784 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Mathieu Chartiera808bac2015-11-05 16:33:15 -08001785 mirror::Reference::ReferentOffset(),
1786 image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001787 }
1788
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001789 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001790 ImageWriter* const image_writer_;
1791 mirror::Object* const copy_;
1792};
1793
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001794class FixupClassVisitor FINAL : public FixupVisitor {
1795 public:
1796 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
1797 }
1798
Mathieu Chartierc7853442015-03-27 14:35:38 -07001799 void operator()(Object* obj, MemberOffset offset, bool is_static ATTRIBUTE_UNUSED) const
Mathieu Chartier90443472015-07-16 20:32:27 -07001800 REQUIRES(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001801 DCHECK(obj->IsClass());
Igor Murashkinf5b4c502014-11-14 15:01:59 -08001802 FixupVisitor::operator()(obj, offset, /*is_static*/false);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001803 }
1804
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001805 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
1806 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mathieu Chartierda7c6502015-07-23 16:01:26 -07001807 SHARED_REQUIRES(Locks::mutator_lock_) REQUIRES(Locks::heap_bitmap_lock_) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001808 LOG(FATAL) << "Reference not expected here.";
1809 }
1810};
1811
Vladimir Marko05792b92015-08-03 11:56:49 +01001812uintptr_t ImageWriter::NativeOffsetInImage(void* obj) {
1813 DCHECK(obj != nullptr);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001814 DCHECK(!IsInBootImage(obj));
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001815 auto it = native_object_relocations_.find(obj);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08001816 CHECK(it != native_object_relocations_.end()) << obj << " spaces "
1817 << Runtime::Current()->GetHeap()->DumpSpaces();
Mathieu Chartierc0fe56a2015-08-11 13:01:23 -07001818 const NativeObjectRelocation& relocation = it->second;
Vladimir Marko05792b92015-08-03 11:56:49 +01001819 return relocation.offset;
1820}
1821
1822template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001823T* ImageWriter::NativeLocationInImage(T* obj, const char* oat_filename) {
1824 if (obj == nullptr || IsInBootImage(obj)) {
1825 return obj;
1826 } else {
1827 ImageInfo& image_info = GetImageInfo(oat_filename);
1828 return reinterpret_cast<T*>(image_info.image_begin_ + NativeOffsetInImage(obj));
1829 }
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001830}
1831
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001832template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001833T* ImageWriter::NativeCopyLocation(T* obj, mirror::DexCache* dex_cache) {
1834 if (obj == nullptr || IsInBootImage(obj)) {
1835 return obj;
1836 } else {
1837 const char* oat_filename = GetOatFilenameForDexCache(dex_cache);
1838 ImageInfo& image_info = GetImageInfo(oat_filename);
1839 return reinterpret_cast<T*>(image_info.image_->Begin() + NativeOffsetInImage(obj));
1840 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001841}
1842
1843class NativeLocationVisitor {
1844 public:
Jeff Haodcdc85b2015-12-04 14:06:18 -08001845 explicit NativeLocationVisitor(ImageWriter* image_writer, const char* oat_filename)
1846 : image_writer_(image_writer), oat_filename_(oat_filename) {}
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001847
1848 template <typename T>
Jeff Haodcdc85b2015-12-04 14:06:18 -08001849 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
1850 return image_writer_->NativeLocationInImage(ptr, oat_filename_);
1851 }
1852
1853 ArtMethod* operator()(ArtMethod* method) const SHARED_REQUIRES(Locks::mutator_lock_) {
1854 const char* oat_filename = method->IsRuntimeMethod() ? image_writer_->GetDefaultOatFilename() :
1855 image_writer_->GetOatFilenameForDexCache(method->GetDexCache());
1856 return image_writer_->NativeLocationInImage(method, oat_filename);
1857 }
1858
1859 ArtField* operator()(ArtField* field) const SHARED_REQUIRES(Locks::mutator_lock_) {
1860 const char* oat_filename = image_writer_->GetOatFilenameForDexCache(field->GetDexCache());
1861 return image_writer_->NativeLocationInImage(field, oat_filename);
Mathieu Chartierc7853442015-03-27 14:35:38 -07001862 }
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001863
1864 private:
1865 ImageWriter* const image_writer_;
Jeff Haodcdc85b2015-12-04 14:06:18 -08001866 const char* oat_filename_;
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001867};
1868
1869void ImageWriter::FixupClass(mirror::Class* orig, mirror::Class* copy) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08001870 const char* oat_filename = GetOatFilename(orig);
1871 orig->FixupNativePointers(copy, target_ptr_size_, NativeLocationVisitor(this, oat_filename));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001872 FixupClassVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001873 static_cast<mirror::Object*>(orig)->VisitReferences(visitor, visitor);
Andreas Gampeace0dc12016-01-20 13:33:13 -08001874
1875 // Remove the clinitThreadId. This is required for image determinism.
1876 copy->SetClinitThreadId(static_cast<pid_t>(0));
Mathieu Chartierc7853442015-03-27 14:35:38 -07001877}
1878
Ian Rogersef7d42f2014-01-06 12:55:46 -08001879void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -07001880 DCHECK(orig != nullptr);
1881 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -07001882 if (kUseBakerOrBrooksReadBarrier) {
1883 orig->AssertReadBarrierPointer();
1884 if (kUseBrooksReadBarrier) {
1885 // Note the address 'copy' isn't the same as the image address of 'orig'.
1886 copy->SetReadBarrierPointer(GetImageAddress(orig));
1887 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
1888 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -08001889 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001890 auto* klass = orig->GetClass();
1891 if (klass->IsIntArrayClass() || klass->IsLongArrayClass()) {
Vladimir Marko05792b92015-08-03 11:56:49 +01001892 // Is this a native pointer array?
Mathieu Chartiere401d142015-04-22 13:56:20 -07001893 auto it = pointer_arrays_.find(down_cast<mirror::PointerArray*>(orig));
1894 if (it != pointer_arrays_.end()) {
1895 // Should only need to fixup every pointer array exactly once.
1896 FixupPointerArray(copy, down_cast<mirror::PointerArray*>(orig), klass, it->second);
1897 pointer_arrays_.erase(it);
1898 return;
1899 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001900 }
Mathieu Chartierc7853442015-03-27 14:35:38 -07001901 if (orig->IsClass()) {
1902 FixupClass(orig->AsClass<kVerifyNone>(), down_cast<mirror::Class*>(copy));
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001903 } else {
Mathieu Chartiere401d142015-04-22 13:56:20 -07001904 if (klass == mirror::Method::StaticClass() || klass == mirror::Constructor::StaticClass()) {
1905 // Need to go update the ArtMethod.
1906 auto* dest = down_cast<mirror::AbstractMethod*>(copy);
1907 auto* src = down_cast<mirror::AbstractMethod*>(orig);
1908 ArtMethod* src_method = src->GetArtMethod();
Mathieu Chartier54d220e2015-07-30 16:20:06 -07001909 auto it = native_object_relocations_.find(src_method);
1910 CHECK(it != native_object_relocations_.end())
1911 << "Missing relocation for AbstractMethod.artMethod " << PrettyMethod(src_method);
Mathieu Chartiere401d142015-04-22 13:56:20 -07001912 dest->SetArtMethod(
Jeff Haodcdc85b2015-12-04 14:06:18 -08001913 reinterpret_cast<ArtMethod*>(global_image_begin_ + it->second.offset));
Vladimir Marko05792b92015-08-03 11:56:49 +01001914 } else if (!klass->IsArrayClass()) {
1915 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
1916 if (klass == class_linker->GetClassRoot(ClassLinker::kJavaLangDexCache)) {
1917 FixupDexCache(down_cast<mirror::DexCache*>(orig), down_cast<mirror::DexCache*>(copy));
Mathieu Chartier208a5cb2015-12-02 15:44:07 -08001918 } else if (klass->IsClassLoaderClass()) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001919 mirror::ClassLoader* copy_loader = down_cast<mirror::ClassLoader*>(copy);
Vladimir Marko05792b92015-08-03 11:56:49 +01001920 // If src is a ClassLoader, set the class table to null so that it gets recreated by the
1921 // ClassLoader.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001922 copy_loader->SetClassTable(nullptr);
Mathieu Chartier5550c562015-09-22 15:18:04 -07001923 // Also set allocator to null to be safe. The allocator is created when we create the class
1924 // table. We also never expect to unload things in the image since they are held live as
1925 // roots.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08001926 copy_loader->SetAllocator(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01001927 }
Mathieu Chartiere401d142015-04-22 13:56:20 -07001928 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001929 FixupVisitor visitor(this, copy);
Mathieu Chartier059ef3d2015-08-18 13:54:21 -07001930 orig->VisitReferences(visitor, visitor);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07001931 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07001932}
1933
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001934
1935class ImageAddressVisitor {
1936 public:
1937 explicit ImageAddressVisitor(ImageWriter* image_writer) : image_writer_(image_writer) {}
1938
1939 template <typename T>
1940 T* operator()(T* ptr) const SHARED_REQUIRES(Locks::mutator_lock_) {
1941 return image_writer_->GetImageAddress(ptr);
1942 }
1943
1944 private:
1945 ImageWriter* const image_writer_;
1946};
1947
1948
Vladimir Marko05792b92015-08-03 11:56:49 +01001949void ImageWriter::FixupDexCache(mirror::DexCache* orig_dex_cache,
1950 mirror::DexCache* copy_dex_cache) {
1951 // Though the DexCache array fields are usually treated as native pointers, we set the full
1952 // 64-bit values here, clearing the top 32 bits for 32-bit targets. The zero-extension is
1953 // done by casting to the unsigned type uintptr_t before casting to int64_t, i.e.
1954 // static_cast<int64_t>(reinterpret_cast<uintptr_t>(image_begin_ + offset))).
Jeff Haodcdc85b2015-12-04 14:06:18 -08001955 const char* oat_filename = GetOatFilenameForDexCache(orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01001956 GcRoot<mirror::String>* orig_strings = orig_dex_cache->GetStrings();
1957 if (orig_strings != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001958 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::StringsOffset(),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001959 NativeLocationInImage(orig_strings, oat_filename),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001960 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001961 orig_dex_cache->FixupStrings(NativeCopyLocation(orig_strings, orig_dex_cache),
1962 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001963 }
1964 GcRoot<mirror::Class>* orig_types = orig_dex_cache->GetResolvedTypes();
1965 if (orig_types != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001966 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedTypesOffset(),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001967 NativeLocationInImage(orig_types, oat_filename),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001968 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001969 orig_dex_cache->FixupResolvedTypes(NativeCopyLocation(orig_types, orig_dex_cache),
1970 ImageAddressVisitor(this));
Vladimir Marko05792b92015-08-03 11:56:49 +01001971 }
1972 ArtMethod** orig_methods = orig_dex_cache->GetResolvedMethods();
1973 if (orig_methods != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001974 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedMethodsOffset(),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001975 NativeLocationInImage(orig_methods, oat_filename),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001976 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001977 ArtMethod** copy_methods = NativeCopyLocation(orig_methods, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01001978 for (size_t i = 0, num = orig_dex_cache->NumResolvedMethods(); i != num; ++i) {
1979 ArtMethod* orig = mirror::DexCache::GetElementPtrSize(orig_methods, i, target_ptr_size_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001980 const char* method_oat_filename;
1981 if (orig == nullptr || orig->IsRuntimeMethod()) {
1982 method_oat_filename = default_oat_filename_;
1983 } else {
1984 method_oat_filename = GetOatFilenameForDexCache(orig->GetDexCache());
1985 }
1986 ArtMethod* copy = NativeLocationInImage(orig, method_oat_filename);
Vladimir Marko05792b92015-08-03 11:56:49 +01001987 mirror::DexCache::SetElementPtrSize(copy_methods, i, copy, target_ptr_size_);
1988 }
1989 }
1990 ArtField** orig_fields = orig_dex_cache->GetResolvedFields();
1991 if (orig_fields != nullptr) {
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001992 copy_dex_cache->SetFieldPtrWithSize<false>(mirror::DexCache::ResolvedFieldsOffset(),
Jeff Haodcdc85b2015-12-04 14:06:18 -08001993 NativeLocationInImage(orig_fields, oat_filename),
Mathieu Chartier4b00d342015-11-13 10:42:08 -08001994 /*pointer size*/8u);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001995 ArtField** copy_fields = NativeCopyLocation(orig_fields, orig_dex_cache);
Vladimir Marko05792b92015-08-03 11:56:49 +01001996 for (size_t i = 0, num = orig_dex_cache->NumResolvedFields(); i != num; ++i) {
1997 ArtField* orig = mirror::DexCache::GetElementPtrSize(orig_fields, i, target_ptr_size_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08001998 const char* field_oat_filename =
1999 orig == nullptr ? default_oat_filename_ : GetOatFilenameForDexCache(orig->GetDexCache());
2000 ArtField* copy = NativeLocationInImage(orig, field_oat_filename);
Vladimir Marko05792b92015-08-03 11:56:49 +01002001 mirror::DexCache::SetElementPtrSize(copy_fields, i, copy, target_ptr_size_);
2002 }
2003 }
Andreas Gampeace0dc12016-01-20 13:33:13 -08002004
2005 // Remove the DexFile pointers. They will be fixed up when the runtime loads the oat file. Leaving
2006 // compiler pointers in here will make the output non-deterministic.
2007 copy_dex_cache->SetDexFile(nullptr);
Vladimir Marko05792b92015-08-03 11:56:49 +01002008}
2009
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002010const uint8_t* ImageWriter::GetOatAddress(OatAddress type) const {
2011 DCHECK_LT(type, kOatAddressCount);
2012 // If we are compiling an app image, we need to use the stubs of the boot image.
2013 if (compile_app_image_) {
2014 // Use the current image pointers.
Mathieu Chartierfbc31082016-01-24 11:59:56 -08002015 const std::vector<gc::space::ImageSpace*>& image_spaces =
Jeff Haodcdc85b2015-12-04 14:06:18 -08002016 Runtime::Current()->GetHeap()->GetBootImageSpaces();
2017 DCHECK(!image_spaces.empty());
2018 const OatFile* oat_file = image_spaces[0]->GetOatFile();
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002019 CHECK(oat_file != nullptr);
2020 const OatHeader& header = oat_file->GetOatHeader();
2021 switch (type) {
2022 // TODO: We could maybe clean this up if we stored them in an array in the oat header.
2023 case kOatAddressQuickGenericJNITrampoline:
2024 return static_cast<const uint8_t*>(header.GetQuickGenericJniTrampoline());
2025 case kOatAddressInterpreterToInterpreterBridge:
2026 return static_cast<const uint8_t*>(header.GetInterpreterToInterpreterBridge());
2027 case kOatAddressInterpreterToCompiledCodeBridge:
2028 return static_cast<const uint8_t*>(header.GetInterpreterToCompiledCodeBridge());
2029 case kOatAddressJNIDlsymLookup:
2030 return static_cast<const uint8_t*>(header.GetJniDlsymLookup());
2031 case kOatAddressQuickIMTConflictTrampoline:
2032 return static_cast<const uint8_t*>(header.GetQuickImtConflictTrampoline());
2033 case kOatAddressQuickResolutionTrampoline:
2034 return static_cast<const uint8_t*>(header.GetQuickResolutionTrampoline());
2035 case kOatAddressQuickToInterpreterBridge:
2036 return static_cast<const uint8_t*>(header.GetQuickToInterpreterBridge());
2037 default:
2038 UNREACHABLE();
2039 }
2040 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002041 const ImageInfo& primary_image_info = GetImageInfo(0);
2042 return GetOatAddressForOffset(primary_image_info.oat_address_offsets_[type], primary_image_info);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002043}
2044
Jeff Haodcdc85b2015-12-04 14:06:18 -08002045const uint8_t* ImageWriter::GetQuickCode(ArtMethod* method,
2046 const ImageInfo& image_info,
2047 bool* quick_is_interpreted) {
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002048 DCHECK(!method->IsResolutionMethod()) << PrettyMethod(method);
2049 DCHECK(!method->IsImtConflictMethod()) << PrettyMethod(method);
2050 DCHECK(!method->IsImtUnimplementedMethod()) << PrettyMethod(method);
Alex Light9139e002015-10-09 15:59:48 -07002051 DCHECK(method->IsInvokable()) << PrettyMethod(method);
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002052 DCHECK(!IsInBootImage(method)) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002053
2054 // Use original code if it exists. Otherwise, set the code pointer to the resolution
2055 // trampoline.
2056
2057 // Quick entrypoint:
Jeff Haoc7d11882015-02-03 15:08:39 -08002058 uint32_t quick_oat_code_offset = PointerToLowMemUInt32(
2059 method->GetEntryPointFromQuickCompiledCodePtrSize(target_ptr_size_));
Jeff Haodcdc85b2015-12-04 14:06:18 -08002060 const uint8_t* quick_code = GetOatAddressForOffset(quick_oat_code_offset, image_info);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002061 *quick_is_interpreted = false;
Mathieu Chartiere401d142015-04-22 13:56:20 -07002062 if (quick_code != nullptr && (!method->IsStatic() || method->IsConstructor() ||
2063 method->GetDeclaringClass()->IsInitialized())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002064 // We have code for a non-static or initialized method, just use the code.
2065 } else if (quick_code == nullptr && method->IsNative() &&
2066 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
2067 // Non-static or initialized native method missing compiled code, use generic JNI version.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002068 quick_code = GetOatAddress(kOatAddressQuickGenericJNITrampoline);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002069 } else if (quick_code == nullptr && !method->IsNative()) {
2070 // We don't have code at all for a non-native method, use the interpreter.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002071 quick_code = GetOatAddress(kOatAddressQuickToInterpreterBridge);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002072 *quick_is_interpreted = true;
2073 } else {
2074 CHECK(!method->GetDeclaringClass()->IsInitialized());
2075 // We have code for a static method, but need to go through the resolution stub for class
2076 // initialization.
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002077 quick_code = GetOatAddress(kOatAddressQuickResolutionTrampoline);
2078 }
2079 if (!IsInBootOatFile(quick_code)) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002080 // DCHECK_GE(quick_code, oat_data_begin_);
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002081 }
2082 return quick_code;
2083}
2084
Jeff Haodcdc85b2015-12-04 14:06:18 -08002085void ImageWriter::CopyAndFixupMethod(ArtMethod* orig,
2086 ArtMethod* copy,
2087 const ImageInfo& image_info) {
Vladimir Marko14632852015-08-17 12:07:23 +01002088 memcpy(copy, orig, ArtMethod::Size(target_ptr_size_));
Mathieu Chartiere401d142015-04-22 13:56:20 -07002089
2090 copy->SetDeclaringClass(GetImageAddress(orig->GetDeclaringClassUnchecked()));
Vladimir Marko05792b92015-08-03 11:56:49 +01002091
Jeff Haodcdc85b2015-12-04 14:06:18 -08002092 const char* oat_filename;
Mathieu Chartiere467cea2016-01-07 18:36:19 -08002093 if (orig->IsRuntimeMethod() || compile_app_image_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002094 oat_filename = default_oat_filename_;
2095 } else {
2096 auto it = dex_file_oat_filename_map_.find(orig->GetDexFile());
2097 DCHECK(it != dex_file_oat_filename_map_.end()) << orig->GetDexFile()->GetLocation();
2098 oat_filename = it->second;
2099 }
Vladimir Marko05792b92015-08-03 11:56:49 +01002100 ArtMethod** orig_resolved_methods = orig->GetDexCacheResolvedMethods(target_ptr_size_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002101 copy->SetDexCacheResolvedMethods(NativeLocationInImage(orig_resolved_methods, oat_filename),
2102 target_ptr_size_);
Vladimir Marko05792b92015-08-03 11:56:49 +01002103 GcRoot<mirror::Class>* orig_resolved_types = orig->GetDexCacheResolvedTypes(target_ptr_size_);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002104 copy->SetDexCacheResolvedTypes(NativeLocationInImage(orig_resolved_types, oat_filename),
2105 target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002106
Ian Rogers848871b2013-08-05 10:56:33 -07002107 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
2108 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -07002109
Ian Rogers848871b2013-08-05 10:56:33 -07002110 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002111 Runtime* runtime = Runtime::Current();
2112 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002113 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002114 GetOatAddress(kOatAddressQuickResolutionTrampoline), target_ptr_size_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -07002115 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
2116 orig == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002117 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002118 GetOatAddress(kOatAddressQuickIMTConflictTrampoline), target_ptr_size_);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002119 } else if (UNLIKELY(orig->IsRuntimeMethod())) {
2120 bool found_one = false;
2121 for (size_t i = 0; i < static_cast<size_t>(Runtime::kLastCalleeSaveType); ++i) {
2122 auto idx = static_cast<Runtime::CalleeSaveType>(i);
2123 if (runtime->HasCalleeSaveMethod(idx) && runtime->GetCalleeSaveMethod(idx) == orig) {
2124 found_one = true;
2125 break;
2126 }
2127 }
2128 CHECK(found_one) << "Expected to find callee save method but got " << PrettyMethod(orig);
2129 CHECK(copy->IsRuntimeMethod());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002130 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07002131 // We assume all methods have code. If they don't currently then we set them to the use the
2132 // resolution trampoline. Abstract methods never have code and so we need to make sure their
2133 // use results in an AbstractMethodError. We use the interpreter to achieve this.
Alex Light9139e002015-10-09 15:59:48 -07002134 if (UNLIKELY(!orig->IsInvokable())) {
Mathieu Chartiere401d142015-04-22 13:56:20 -07002135 copy->SetEntryPointFromQuickCompiledCodePtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002136 GetOatAddress(kOatAddressQuickToInterpreterBridge), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002137 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -07002138 bool quick_is_interpreted;
Jeff Haodcdc85b2015-12-04 14:06:18 -08002139 const uint8_t* quick_code = GetQuickCode(orig, image_info, &quick_is_interpreted);
Mathieu Chartiere401d142015-04-22 13:56:20 -07002140 copy->SetEntryPointFromQuickCompiledCodePtrSize(quick_code, target_ptr_size_);
Sebastien Hertze1d07812014-05-21 15:44:09 +02002141
Sebastien Hertze1d07812014-05-21 15:44:09 +02002142 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -07002143 if (orig->IsNative()) {
2144 // The native method's pointer is set to a stub to lookup via dlsym.
2145 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartiere401d142015-04-22 13:56:20 -07002146 copy->SetEntryPointFromJniPtrSize(
Mathieu Chartierda5b28a2015-11-05 08:03:47 -08002147 GetOatAddress(kOatAddressJNIDlsymLookup), target_ptr_size_);
Ian Rogers848871b2013-08-05 10:56:33 -07002148 }
2149 }
Brian Carlstrom7940e442013-07-12 13:46:57 -07002150 }
2151}
2152
Alex Lighta59dd802014-07-02 16:28:08 -07002153static OatHeader* GetOatHeaderFromElf(ElfFile* elf) {
Tong Shen62d1ca32014-09-03 17:24:56 -07002154 uint64_t data_sec_offset;
2155 bool has_data_sec = elf->GetSectionOffsetAndSize(".rodata", &data_sec_offset, nullptr);
2156 if (!has_data_sec) {
Alex Lighta59dd802014-07-02 16:28:08 -07002157 return nullptr;
2158 }
Tong Shen62d1ca32014-09-03 17:24:56 -07002159 return reinterpret_cast<OatHeader*>(elf->Begin() + data_sec_offset);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -08002160}
2161
Vladimir Markof4da6752014-08-01 19:04:18 +01002162void ImageWriter::SetOatChecksumFromElfFile(File* elf_file) {
Alex Lighta59dd802014-07-02 16:28:08 -07002163 std::string error_msg;
Mathieu Chartiera808bac2015-11-05 16:33:15 -08002164 std::unique_ptr<ElfFile> elf(ElfFile::Open(elf_file,
2165 PROT_READ | PROT_WRITE,
2166 MAP_SHARED,
2167 &error_msg));
Alex Lighta59dd802014-07-02 16:28:08 -07002168 if (elf.get() == nullptr) {
Vladimir Markof4da6752014-08-01 19:04:18 +01002169 LOG(FATAL) << "Unable open oat file: " << error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -07002170 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -07002171 }
Alex Lighta59dd802014-07-02 16:28:08 -07002172 OatHeader* oat_header = GetOatHeaderFromElf(elf.get());
2173 CHECK(oat_header != nullptr);
2174 CHECK(oat_header->IsValid());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002175
Jeff Haodcdc85b2015-12-04 14:06:18 -08002176 ImageInfo& image_info = GetImageInfo(oat_file_->GetLocation().c_str());
2177 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_info.image_->Begin());
Alex Lighta59dd802014-07-02 16:28:08 -07002178 image_header->SetOatChecksum(oat_header->GetChecksum());
Brian Carlstrom7940e442013-07-12 13:46:57 -07002179}
2180
Jeff Haodcdc85b2015-12-04 14:06:18 -08002181size_t ImageWriter::GetBinSizeSum(ImageWriter::ImageInfo& image_info, ImageWriter::Bin up_to) const {
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002182 DCHECK_LE(up_to, kBinSize);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002183 return std::accumulate(&image_info.bin_slot_sizes_[0],
2184 &image_info.bin_slot_sizes_[up_to],
2185 /*init*/0);
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002186}
2187
2188ImageWriter::BinSlot::BinSlot(uint32_t lockword) : lockword_(lockword) {
2189 // These values may need to get updated if more bins are added to the enum Bin
Mathieu Chartiere401d142015-04-22 13:56:20 -07002190 static_assert(kBinBits == 3, "wrong number of bin bits");
2191 static_assert(kBinShift == 27, "wrong number of shift");
Igor Murashkinf5b4c502014-11-14 15:01:59 -08002192 static_assert(sizeof(BinSlot) == sizeof(LockWord), "BinSlot/LockWord must have equal sizes");
2193
2194 DCHECK_LT(GetBin(), kBinSize);
2195 DCHECK_ALIGNED(GetIndex(), kObjectAlignment);
2196}
2197
2198ImageWriter::BinSlot::BinSlot(Bin bin, uint32_t index)
2199 : BinSlot(index | (static_cast<uint32_t>(bin) << kBinShift)) {
2200 DCHECK_EQ(index, GetIndex());
2201}
2202
2203ImageWriter::Bin ImageWriter::BinSlot::GetBin() const {
2204 return static_cast<Bin>((lockword_ & kBinMask) >> kBinShift);
2205}
2206
2207uint32_t ImageWriter::BinSlot::GetIndex() const {
2208 return lockword_ & ~kBinMask;
2209}
2210
Jeff Haodcdc85b2015-12-04 14:06:18 -08002211uint8_t* ImageWriter::GetOatFileBegin(const char* oat_filename) const {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002212 uintptr_t last_image_end = 0;
2213 for (const char* oat_fn : oat_filenames_) {
2214 const ImageInfo& image_info = GetConstImageInfo(oat_fn);
2215 DCHECK(image_info.image_begin_ != nullptr);
2216 uintptr_t this_end = reinterpret_cast<uintptr_t>(image_info.image_begin_) +
2217 image_info.image_size_;
2218 last_image_end = std::max(this_end, last_image_end);
2219 }
2220 const ImageInfo& image_info = GetConstImageInfo(oat_filename);
2221 return reinterpret_cast<uint8_t*>(last_image_end) + image_info.oat_offset_;
Mathieu Chartierd39645e2015-06-09 17:50:29 -07002222}
2223
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002224ImageWriter::Bin ImageWriter::BinTypeForNativeRelocationType(NativeObjectRelocationType type) {
2225 switch (type) {
2226 case kNativeObjectRelocationTypeArtField:
2227 case kNativeObjectRelocationTypeArtFieldArray:
2228 return kBinArtField;
2229 case kNativeObjectRelocationTypeArtMethodClean:
2230 case kNativeObjectRelocationTypeArtMethodArrayClean:
2231 return kBinArtMethodClean;
2232 case kNativeObjectRelocationTypeArtMethodDirty:
2233 case kNativeObjectRelocationTypeArtMethodArrayDirty:
2234 return kBinArtMethodDirty;
Vladimir Marko05792b92015-08-03 11:56:49 +01002235 case kNativeObjectRelocationTypeDexCacheArray:
2236 return kBinDexCacheArray;
Mathieu Chartier54d220e2015-07-30 16:20:06 -07002237 }
2238 UNREACHABLE();
2239}
2240
Jeff Haodcdc85b2015-12-04 14:06:18 -08002241const char* ImageWriter::GetOatFilename(mirror::Object* obj) const {
2242 if (compile_app_image_) {
2243 return default_oat_filename_;
2244 } else {
2245 return GetOatFilenameForDexCache(obj->IsDexCache() ? obj->AsDexCache() :
2246 obj->IsClass() ? obj->AsClass()->GetDexCache() : obj->GetClass()->GetDexCache());
2247 }
2248}
2249
2250const char* ImageWriter::GetOatFilenameForDexCache(mirror::DexCache* dex_cache) const {
2251 if (compile_app_image_ || dex_cache == nullptr) {
2252 return default_oat_filename_;
2253 } else {
2254 auto it = dex_file_oat_filename_map_.find(dex_cache->GetDexFile());
2255 DCHECK(it != dex_file_oat_filename_map_.end()) << dex_cache->GetDexFile()->GetLocation();
2256 return it->second;
2257 }
2258}
2259
2260ImageWriter::ImageInfo& ImageWriter::GetImageInfo(const char* oat_filename) {
2261 auto it = image_info_map_.find(oat_filename);
2262 DCHECK(it != image_info_map_.end());
2263 return it->second;
2264}
2265
2266const ImageWriter::ImageInfo& ImageWriter::GetConstImageInfo(const char* oat_filename) const {
2267 auto it = image_info_map_.find(oat_filename);
2268 DCHECK(it != image_info_map_.end());
2269 return it->second;
2270}
2271
2272const ImageWriter::ImageInfo& ImageWriter::GetImageInfo(size_t index) const {
2273 DCHECK_LT(index, oat_filenames_.size());
2274 return GetConstImageInfo(oat_filenames_[index]);
2275}
2276
Vladimir Markod8904a52016-01-29 16:27:27 +00002277void ImageWriter::UpdateOatFile(File* oat_file, const char* oat_filename) {
Jeff Haodcdc85b2015-12-04 14:06:18 -08002278 DCHECK(oat_file != nullptr);
Mathieu Chartier14567fd2016-01-28 20:33:36 -08002279 if (compile_app_image_) {
2280 CHECK_EQ(oat_filenames_.size(), 1u) << "App image should have no next image.";
2281 return;
2282 }
Jeff Haodcdc85b2015-12-04 14:06:18 -08002283 ImageInfo& cur_image_info = GetImageInfo(oat_filename);
2284
2285 // Update the oat_offset of the next image info.
2286 auto it = std::find(oat_filenames_.begin(), oat_filenames_.end(), oat_filename);
2287 DCHECK(it != oat_filenames_.end());
2288
2289 it++;
2290 if (it != oat_filenames_.end()) {
Mathieu Chartier14567fd2016-01-28 20:33:36 -08002291 size_t oat_loaded_size = 0;
2292 size_t oat_data_offset = 0;
2293 ElfWriter::GetOatElfInformation(oat_file, &oat_loaded_size, &oat_data_offset);
Jeff Haodcdc85b2015-12-04 14:06:18 -08002294 // There is a following one.
2295 ImageInfo& next_image_info = GetImageInfo(*it);
2296 next_image_info.oat_offset_ = cur_image_info.oat_offset_ + oat_loaded_size;
2297 }
2298}
2299
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002300ImageWriter::ImageWriter(
2301 const CompilerDriver& compiler_driver,
2302 uintptr_t image_begin,
2303 bool compile_pic,
2304 bool compile_app_image,
2305 ImageHeader::StorageMode image_storage_mode,
2306 const std::vector<const char*> oat_filenames,
2307 const std::unordered_map<const DexFile*, const char*>& dex_file_oat_filename_map)
2308 : compiler_driver_(compiler_driver),
2309 global_image_begin_(reinterpret_cast<uint8_t*>(image_begin)),
2310 image_objects_offset_begin_(0),
2311 oat_file_(nullptr),
2312 compile_pic_(compile_pic),
2313 compile_app_image_(compile_app_image),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002314 target_ptr_size_(InstructionSetPointerSize(compiler_driver_.GetInstructionSet())),
2315 image_method_array_(ImageHeader::kImageMethodsCount),
2316 dirty_methods_(0u),
2317 clean_methods_(0u),
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002318 image_storage_mode_(image_storage_mode),
2319 dex_file_oat_filename_map_(dex_file_oat_filename_map),
2320 oat_filenames_(oat_filenames),
2321 default_oat_filename_(oat_filenames[0]) {
2322 CHECK_NE(image_begin, 0U);
2323 for (const char* oat_filename : oat_filenames) {
2324 image_info_map_.emplace(oat_filename, ImageInfo());
2325 }
2326 std::fill_n(image_methods_, arraysize(image_methods_), nullptr);
2327}
2328
Mathieu Chartier1f47b672016-01-07 16:29:01 -08002329ImageWriter::ImageInfo::ImageInfo()
2330 : intern_table_(new InternTable),
2331 class_table_(new ClassTable) {}
Mathieu Chartierea0831f2015-12-29 13:17:37 -08002332
Brian Carlstrom7940e442013-07-12 13:46:57 -07002333} // namespace art