blob: 448888f02df1865347a2d0429fb2bf0b7bdf2900 [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>
20
Ian Rogers700a4022014-05-19 16:49:03 -070021#include <memory>
Brian Carlstrom7940e442013-07-12 13:46:57 -070022#include <vector>
23
24#include "base/logging.h"
25#include "base/unix_file/fd_file.h"
26#include "class_linker.h"
27#include "compiled_method.h"
28#include "dex_file-inl.h"
29#include "driver/compiler_driver.h"
Alex Light53cb16b2014-06-12 11:26:29 -070030#include "elf_file.h"
31#include "elf_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070032#include "elf_writer.h"
33#include "gc/accounting/card_table-inl.h"
34#include "gc/accounting/heap_bitmap.h"
Mathieu Chartier31e89252013-08-28 11:29:12 -070035#include "gc/accounting/space_bitmap-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070036#include "gc/heap.h"
37#include "gc/space/large_object_space.h"
38#include "gc/space/space-inl.h"
39#include "globals.h"
40#include "image.h"
41#include "intern_table.h"
Mathieu Chartierad2541a2013-10-25 10:05:23 -070042#include "lock_word.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070043#include "mirror/art_field-inl.h"
44#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070045#include "mirror/array-inl.h"
46#include "mirror/class-inl.h"
47#include "mirror/class_loader.h"
48#include "mirror/dex_cache-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070049#include "mirror/object-inl.h"
50#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070051#include "mirror/string-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070052#include "oat.h"
53#include "oat_file.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070054#include "runtime.h"
55#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070056#include "handle_scope-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070057#include "utils.h"
58
Brian Carlstromea46f952013-07-30 01:26:50 -070059using ::art::mirror::ArtField;
60using ::art::mirror::ArtMethod;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070061using ::art::mirror::Class;
62using ::art::mirror::DexCache;
63using ::art::mirror::EntryPointFromInterpreter;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070064using ::art::mirror::Object;
65using ::art::mirror::ObjectArray;
66using ::art::mirror::String;
Brian Carlstrom7940e442013-07-12 13:46:57 -070067
68namespace art {
69
Vladimir Markof4da6752014-08-01 19:04:18 +010070bool ImageWriter::PrepareImageAddressSpace() {
71 {
72 Thread::Current()->TransitionFromSuspendedToRunnable();
73 PruneNonImageClasses(); // Remove junk
74 ComputeLazyFieldsForImageClasses(); // Add useful information
75 ComputeEagerResolvedStrings();
76 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
77 }
78 gc::Heap* heap = Runtime::Current()->GetHeap();
79 heap->CollectGarbage(false); // Remove garbage.
80
81 if (!AllocMemory()) {
82 return false;
83 }
84
85 if (kIsDebugBuild) {
86 ScopedObjectAccess soa(Thread::Current());
87 CheckNonImageClassesRemoved();
88 }
89
90 Thread::Current()->TransitionFromSuspendedToRunnable();
91 CalculateNewObjectOffsets();
92 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
93
94 return true;
95}
96
Brian Carlstrom7940e442013-07-12 13:46:57 -070097bool ImageWriter::Write(const std::string& image_filename,
Brian Carlstrom7940e442013-07-12 13:46:57 -070098 const std::string& oat_filename,
99 const std::string& oat_location) {
100 CHECK(!image_filename.empty());
101
Brian Carlstrom7940e442013-07-12 13:46:57 -0700102 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700103
Ian Rogers700a4022014-05-19 16:49:03 -0700104 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700105 if (oat_file.get() == NULL) {
106 LOG(ERROR) << "Failed to open oat file " << oat_filename << " for " << oat_location;
107 return false;
108 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700109 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -0700110 oat_file_ = OatFile::OpenReadable(oat_file.get(), oat_location, &error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700111 if (oat_file_ == nullptr) {
112 LOG(ERROR) << "Failed to open writable oat file " << oat_filename << " for " << oat_location
113 << ": " << error_msg;
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700114 return false;
115 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700116 CHECK_EQ(class_linker->RegisterOatFile(oat_file_), oat_file_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700117
Ian Rogers848871b2013-08-05 10:56:33 -0700118 interpreter_to_interpreter_bridge_offset_ =
119 oat_file_->GetOatHeader().GetInterpreterToInterpreterBridgeOffset();
120 interpreter_to_compiled_code_bridge_offset_ =
121 oat_file_->GetOatHeader().GetInterpreterToCompiledCodeBridgeOffset();
122
123 jni_dlsym_lookup_offset_ = oat_file_->GetOatHeader().GetJniDlsymLookupOffset();
124
Jeff Hao88474b42013-10-23 16:24:40 -0700125 portable_imt_conflict_trampoline_offset_ =
126 oat_file_->GetOatHeader().GetPortableImtConflictTrampolineOffset();
Ian Rogers848871b2013-08-05 10:56:33 -0700127 portable_resolution_trampoline_offset_ =
128 oat_file_->GetOatHeader().GetPortableResolutionTrampolineOffset();
129 portable_to_interpreter_bridge_offset_ =
130 oat_file_->GetOatHeader().GetPortableToInterpreterBridgeOffset();
131
Andreas Gampe2da88232014-02-27 12:26:20 -0800132 quick_generic_jni_trampoline_offset_ =
133 oat_file_->GetOatHeader().GetQuickGenericJniTrampolineOffset();
Jeff Hao88474b42013-10-23 16:24:40 -0700134 quick_imt_conflict_trampoline_offset_ =
135 oat_file_->GetOatHeader().GetQuickImtConflictTrampolineOffset();
Ian Rogers848871b2013-08-05 10:56:33 -0700136 quick_resolution_trampoline_offset_ =
137 oat_file_->GetOatHeader().GetQuickResolutionTrampolineOffset();
138 quick_to_interpreter_bridge_offset_ =
139 oat_file_->GetOatHeader().GetQuickToInterpreterBridgeOffset();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700140
Brian Carlstrom7940e442013-07-12 13:46:57 -0700141 size_t oat_loaded_size = 0;
142 size_t oat_data_offset = 0;
143 ElfWriter::GetOatElfInformation(oat_file.get(), oat_loaded_size, oat_data_offset);
Alex Light53cb16b2014-06-12 11:26:29 -0700144
Vladimir Markof4da6752014-08-01 19:04:18 +0100145 Thread::Current()->TransitionFromSuspendedToRunnable();
146 CreateHeader(oat_loaded_size, oat_data_offset);
147 CopyAndFixupObjects();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700148 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
149
Vladimir Markof4da6752014-08-01 19:04:18 +0100150 SetOatChecksumFromElfFile(oat_file.get());
151
Ian Rogers700a4022014-05-19 16:49:03 -0700152 std::unique_ptr<File> image_file(OS::CreateEmptyFile(image_filename.c_str()));
Mathieu Chartier31e89252013-08-28 11:29:12 -0700153 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700154 if (image_file.get() == NULL) {
155 LOG(ERROR) << "Failed to open image file " << image_filename;
156 return false;
157 }
158 if (fchmod(image_file->Fd(), 0644) != 0) {
159 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
160 return EXIT_FAILURE;
161 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700162
163 // Write out the image.
164 CHECK_EQ(image_end_, image_header->GetImageSize());
165 if (!image_file->WriteFully(image_->Begin(), image_end_)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700166 PLOG(ERROR) << "Failed to write image file " << image_filename;
167 return false;
168 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700169
170 // Write out the image bitmap at the page aligned start of the image end.
171 CHECK_ALIGNED(image_header->GetImageBitmapOffset(), kPageSize);
172 if (!image_file->Write(reinterpret_cast<char*>(image_bitmap_->Begin()),
173 image_header->GetImageBitmapSize(),
174 image_header->GetImageBitmapOffset())) {
175 PLOG(ERROR) << "Failed to write image file " << image_filename;
176 return false;
177 }
178
Brian Carlstrom7940e442013-07-12 13:46:57 -0700179 return true;
180}
181
Mathieu Chartier590fee92013-09-13 13:46:47 -0700182void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
183 DCHECK(object != nullptr);
184 DCHECK_NE(offset, 0U);
185 DCHECK(!IsImageOffsetAssigned(object));
186 mirror::Object* obj = reinterpret_cast<mirror::Object*>(image_->Begin() + offset);
187 DCHECK_ALIGNED(obj, kObjectAlignment);
188 image_bitmap_->Set(obj);
189 // Before we stomp over the lock word, save the hash code for later.
190 Monitor::Deflate(Thread::Current(), object);;
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700191 LockWord lw(object->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700192 switch (lw.GetState()) {
193 case LockWord::kFatLocked: {
194 LOG(FATAL) << "Fat locked object " << obj << " found during object copy";
195 break;
196 }
197 case LockWord::kThinLocked: {
198 LOG(FATAL) << "Thin locked object " << obj << " found during object copy";
199 break;
200 }
201 case LockWord::kUnlocked:
202 // No hash, don't need to save it.
203 break;
204 case LockWord::kHashCode:
205 saved_hashes_.push_back(std::make_pair(obj, lw.GetHashCode()));
206 break;
207 default:
208 LOG(FATAL) << "Unreachable.";
Ian Rogers2c4257b2014-10-24 14:20:06 -0700209 UNREACHABLE();
Mathieu Chartier31e89252013-08-28 11:29:12 -0700210 }
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700211 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700212 DCHECK(IsImageOffsetAssigned(object));
213}
214
215void ImageWriter::AssignImageOffset(mirror::Object* object) {
216 DCHECK(object != nullptr);
217 SetImageOffset(object, image_end_);
218 image_end_ += RoundUp(object->SizeOf(), 8); // 64-bit alignment
219 DCHECK_LT(image_end_, image_->Size());
220}
221
Ian Rogersef7d42f2014-01-06 12:55:46 -0800222bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700223 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700224 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700225}
226
Ian Rogersef7d42f2014-01-06 12:55:46 -0800227size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700228 DCHECK(object != nullptr);
229 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700230 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700231 size_t offset = lock_word.ForwardingAddress();
232 DCHECK_LT(offset, image_end_);
233 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700234}
235
Brian Carlstrom7940e442013-07-12 13:46:57 -0700236bool ImageWriter::AllocMemory() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700237 size_t length = RoundUp(Runtime::Current()->GetHeap()->GetTotalMemory(), kPageSize);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700238 std::string error_msg;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700239 image_.reset(MemMap::MapAnonymous("image writer image", NULL, length, PROT_READ | PROT_WRITE,
Ian Rogers3cd86d62014-08-14 08:53:12 -0700240 false, &error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700241 if (UNLIKELY(image_.get() == nullptr)) {
242 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700243 return false;
244 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700245
246 // Create the image bitmap.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700247 image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create("image bitmap", image_->Begin(),
248 length));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700249 if (image_bitmap_.get() == nullptr) {
250 LOG(ERROR) << "Failed to allocate memory for image bitmap";
251 return false;
252 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700253 return true;
254}
255
256void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700257 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700258 class_linker->VisitClassesWithoutClassesLock(ComputeLazyFieldsForClassesVisitor, NULL);
259}
260
261bool ImageWriter::ComputeLazyFieldsForClassesVisitor(Class* c, void* /*arg*/) {
Mathieu Chartierf8322842014-05-16 10:59:25 -0700262 Thread* self = Thread::Current();
263 StackHandleScope<1> hs(self);
264 mirror::Class::ComputeName(hs.NewHandle(c));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700265 return true;
266}
267
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700268void ImageWriter::ComputeEagerResolvedStringsCallback(Object* obj, void* arg ATTRIBUTE_UNUSED) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700269 if (!obj->GetClass()->IsStringClass()) {
270 return;
271 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700272 mirror::String* string = obj->AsString();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700273 const uint16_t* utf16_string = string->GetCharArray()->GetData() + string->GetOffset();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700274 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
275 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
276 size_t dex_cache_count = class_linker->GetDexCacheCount();
277 for (size_t i = 0; i < dex_cache_count; ++i) {
278 DexCache* dex_cache = class_linker->GetDexCache(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700279 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers24c534d2013-11-14 00:15:00 -0800280 const DexFile::StringId* string_id;
281 if (UNLIKELY(string->GetLength() == 0)) {
282 string_id = dex_file.FindStringId("");
283 } else {
284 string_id = dex_file.FindStringId(utf16_string);
285 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700286 if (string_id != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700287 // This string occurs in this dex file, assign the dex cache entry.
288 uint32_t string_idx = dex_file.GetIndexForStringId(*string_id);
289 if (dex_cache->GetResolvedString(string_idx) == NULL) {
290 dex_cache->SetResolvedString(string_idx, string);
291 }
292 }
293 }
294}
295
Mathieu Chartier590fee92013-09-13 13:46:47 -0700296void ImageWriter::ComputeEagerResolvedStrings() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
297 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
298 Runtime::Current()->GetHeap()->VisitObjects(ComputeEagerResolvedStringsCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700299}
300
Ian Rogersef7d42f2014-01-06 12:55:46 -0800301bool ImageWriter::IsImageClass(Class* klass) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700302 std::string temp;
303 return compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700304}
305
306struct NonImageClasses {
307 ImageWriter* image_writer;
308 std::set<std::string>* non_image_classes;
309};
310
311void ImageWriter::PruneNonImageClasses() {
312 if (compiler_driver_.GetImageClasses() == NULL) {
313 return;
314 }
315 Runtime* runtime = Runtime::Current();
316 ClassLinker* class_linker = runtime->GetClassLinker();
317
318 // Make a list of classes we would like to prune.
319 std::set<std::string> non_image_classes;
320 NonImageClasses context;
321 context.image_writer = this;
322 context.non_image_classes = &non_image_classes;
323 class_linker->VisitClasses(NonImageClassesVisitor, &context);
324
325 // Remove the undesired classes from the class roots.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700326 for (const std::string& it : non_image_classes) {
Mathieu Chartierc2e20622014-11-03 11:41:47 -0800327 bool result = class_linker->RemoveClass(it.c_str(), NULL);
328 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700329 }
330
331 // Clear references to removed classes from the DexCaches.
Brian Carlstromea46f952013-07-30 01:26:50 -0700332 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700333 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
334 size_t dex_cache_count = class_linker->GetDexCacheCount();
335 for (size_t idx = 0; idx < dex_cache_count; ++idx) {
336 DexCache* dex_cache = class_linker->GetDexCache(idx);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700337 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
338 Class* klass = dex_cache->GetResolvedType(i);
339 if (klass != NULL && !IsImageClass(klass)) {
340 dex_cache->SetResolvedType(i, NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700341 }
342 }
343 for (size_t i = 0; i < dex_cache->NumResolvedMethods(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700344 ArtMethod* method = dex_cache->GetResolvedMethod(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700345 if (method != NULL && !IsImageClass(method->GetDeclaringClass())) {
346 dex_cache->SetResolvedMethod(i, resolution_method);
347 }
348 }
349 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700350 ArtField* field = dex_cache->GetResolvedField(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700351 if (field != NULL && !IsImageClass(field->GetDeclaringClass())) {
352 dex_cache->SetResolvedField(i, NULL);
353 }
354 }
355 }
356}
357
358bool ImageWriter::NonImageClassesVisitor(Class* klass, void* arg) {
359 NonImageClasses* context = reinterpret_cast<NonImageClasses*>(arg);
360 if (!context->image_writer->IsImageClass(klass)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700361 std::string temp;
362 context->non_image_classes->insert(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700363 }
364 return true;
365}
366
367void ImageWriter::CheckNonImageClassesRemoved()
368 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700369 if (compiler_driver_.GetImageClasses() != nullptr) {
370 gc::Heap* heap = Runtime::Current()->GetHeap();
371 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
372 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700373 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700374}
375
376void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
377 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700378 if (obj->IsClass()) {
379 Class* klass = obj->AsClass();
380 if (!image_writer->IsImageClass(klass)) {
381 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700382 std::string temp;
383 CHECK(image_writer->IsImageClass(klass)) << klass->GetDescriptor(&temp)
Mathieu Chartier590fee92013-09-13 13:46:47 -0700384 << " " << PrettyDescriptor(klass);
385 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700386 }
387}
388
389void ImageWriter::DumpImageClasses() {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700390 const std::set<std::string>* image_classes = compiler_driver_.GetImageClasses();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700391 CHECK(image_classes != NULL);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700392 for (const std::string& image_class : *image_classes) {
393 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700394 }
395}
396
Mathieu Chartier590fee92013-09-13 13:46:47 -0700397void ImageWriter::CalculateObjectOffsets(Object* obj) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700398 DCHECK(obj != NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700399 // if it is a string, we want to intern it if its not interned.
400 if (obj->GetClass()->IsStringClass()) {
401 // we must be an interned string that was forward referenced and already assigned
Mathieu Chartier590fee92013-09-13 13:46:47 -0700402 if (IsImageOffsetAssigned(obj)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700403 DCHECK_EQ(obj, obj->AsString()->Intern());
404 return;
405 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700406 mirror::String* const interned = obj->AsString()->Intern();
407 if (obj != interned) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700408 if (!IsImageOffsetAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700409 // interned obj is after us, allocate its location early
Mathieu Chartier590fee92013-09-13 13:46:47 -0700410 AssignImageOffset(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700411 }
412 // point those looking for this object to the interned version.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700413 SetImageOffset(obj, GetImageOffset(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700414 return;
415 }
416 // else (obj == interned), nothing to do but fall through to the normal case
417 }
418
Mathieu Chartier590fee92013-09-13 13:46:47 -0700419 AssignImageOffset(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700420}
421
422ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
423 Runtime* runtime = Runtime::Current();
424 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700425 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700426 StackHandleScope<3> hs(self);
427 Handle<Class> object_array_class(hs.NewHandle(
428 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700429
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700430 // build an Object[] of all the DexCaches used in the source_space_.
431 // Since we can't hold the dex lock when allocating the dex_caches
432 // ObjectArray, we lock the dex lock twice, first to get the number
433 // of dex caches first and then lock it again to copy the dex
434 // caches. We check that the number of dex caches does not change.
435 size_t dex_cache_count;
436 {
437 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
438 dex_cache_count = class_linker->GetDexCacheCount();
439 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700440 Handle<ObjectArray<Object>> dex_caches(
441 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(),
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700442 dex_cache_count)));
443 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
444 {
445 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
446 CHECK_EQ(dex_cache_count, class_linker->GetDexCacheCount())
447 << "The number of dex caches changed.";
448 for (size_t i = 0; i < dex_cache_count; ++i) {
449 dex_caches->Set<false>(i, class_linker->GetDexCache(i));
450 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700451 }
452
453 // build an Object[] of the roots needed to restore the runtime
Ian Rogers700a4022014-05-19 16:49:03 -0700454 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700455 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100456 image_roots->Set<false>(ImageHeader::kResolutionMethod, runtime->GetResolutionMethod());
457 image_roots->Set<false>(ImageHeader::kImtConflictMethod, runtime->GetImtConflictMethod());
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700458 image_roots->Set<false>(ImageHeader::kImtUnimplementedMethod,
459 runtime->GetImtUnimplementedMethod());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100460 image_roots->Set<false>(ImageHeader::kDefaultImt, runtime->GetDefaultImt());
461 image_roots->Set<false>(ImageHeader::kCalleeSaveMethod,
462 runtime->GetCalleeSaveMethod(Runtime::kSaveAll));
463 image_roots->Set<false>(ImageHeader::kRefsOnlySaveMethod,
464 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly));
465 image_roots->Set<false>(ImageHeader::kRefsAndArgsSaveMethod,
466 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700467 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100468 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700469 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
470 CHECK(image_roots->Get(i) != NULL);
471 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700472 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700473}
474
Mathieu Chartier590fee92013-09-13 13:46:47 -0700475// Walk instance fields of the given Class. Separate function to allow recursion on the super
476// class.
477void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
478 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700479 StackHandleScope<1> hs(Thread::Current());
480 Handle<mirror::Class> h_class(hs.NewHandle(klass));
481 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700482 if (super != nullptr) {
483 WalkInstanceFields(obj, super);
484 }
485 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700486 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700487 for (size_t i = 0; i < num_reference_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700488 mirror::ArtField* field = h_class->GetInstanceField(i);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700489 MemberOffset field_offset = field->GetOffset();
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700490 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700491 if (value != nullptr) {
492 WalkFieldsInOrder(value);
493 }
494 }
495}
496
497// For an unvisited object, visit it then all its children found via fields.
498void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
499 if (!IsImageOffsetAssigned(obj)) {
500 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700501 StackHandleScope<2> hs(Thread::Current());
502 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
503 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700504 // visit the object itself.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700505 CalculateObjectOffsets(h_obj.Get());
506 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700507 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700508 if (h_obj->IsClass()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700509 size_t num_static_fields = klass->NumReferenceStaticFields();
510 for (size_t i = 0; i < num_static_fields; ++i) {
511 mirror::ArtField* field = klass->GetStaticField(i);
512 MemberOffset field_offset = field->GetOffset();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700513 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700514 if (value != nullptr) {
515 WalkFieldsInOrder(value);
516 }
517 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700518 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700519 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700520 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700521 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700522 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700523 mirror::Object* value = obj_array->Get(i);
524 if (value != nullptr) {
525 WalkFieldsInOrder(value);
526 }
527 }
528 }
529 }
530}
531
532void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
533 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
534 DCHECK(writer != nullptr);
535 writer->WalkFieldsInOrder(obj);
536}
537
Vladimir Markof4da6752014-08-01 19:04:18 +0100538void ImageWriter::CalculateNewObjectOffsets() {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700539 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700540 StackHandleScope<1> hs(self);
541 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(CreateImageRoots()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700542
543 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700544 DCHECK_EQ(0U, image_end_);
545
Mathieu Chartier31e89252013-08-28 11:29:12 -0700546 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -0700547 // know where image_roots is going to end up
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700548 image_end_ += RoundUp(sizeof(ImageHeader), 8); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -0700549
550 {
551 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700552 // TODO: Image spaces only?
Mathieu Chartier590fee92013-09-13 13:46:47 -0700553 DCHECK_LT(image_end_, image_->Size());
554 // Clear any pre-existing monitors which may have been in the monitor words.
555 heap->VisitObjects(WalkFieldsCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700556 }
557
Vladimir Markof4da6752014-08-01 19:04:18 +0100558 image_roots_address_ = PointerToLowMemUInt32(GetImageAddress(image_roots.Get()));
559
560 // Note that image_end_ is left at end of used space
561}
562
563void ImageWriter::CreateHeader(size_t oat_loaded_size, size_t oat_data_offset) {
564 CHECK_NE(0U, oat_loaded_size);
Ian Rogers13735952014-10-08 12:43:28 -0700565 const uint8_t* oat_file_begin = GetOatFileBegin();
566 const uint8_t* oat_file_end = oat_file_begin + oat_loaded_size;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700567 oat_data_begin_ = oat_file_begin + oat_data_offset;
Ian Rogers13735952014-10-08 12:43:28 -0700568 const uint8_t* oat_data_end = oat_data_begin_ + oat_file_->Size();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700569
Mathieu Chartier31e89252013-08-28 11:29:12 -0700570 // Return to write header at start of image with future location of image_roots. At this point,
571 // image_end_ is the size of the image (excluding bitmaps).
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700572 const size_t heap_bytes_per_bitmap_byte = kBitsPerByte * kObjectAlignment;
Mathieu Chartier12aeccd2013-11-13 15:52:06 -0800573 const size_t bitmap_bytes = RoundUp(image_end_, heap_bytes_per_bitmap_byte) /
574 heap_bytes_per_bitmap_byte;
Vladimir Markof4da6752014-08-01 19:04:18 +0100575 new (image_->Begin()) ImageHeader(PointerToLowMemUInt32(image_begin_),
576 static_cast<uint32_t>(image_end_),
577 RoundUp(image_end_, kPageSize),
578 RoundUp(bitmap_bytes, kPageSize),
579 image_roots_address_,
580 oat_file_->GetOatHeader().GetChecksum(),
581 PointerToLowMemUInt32(oat_file_begin),
582 PointerToLowMemUInt32(oat_data_begin_),
583 PointerToLowMemUInt32(oat_data_end),
Igor Murashkin46774762014-10-22 11:37:02 -0700584 PointerToLowMemUInt32(oat_file_end),
585 compile_pic_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700586}
587
Vladimir Markof4da6752014-08-01 19:04:18 +0100588
Brian Carlstrom7940e442013-07-12 13:46:57 -0700589void ImageWriter::CopyAndFixupObjects()
590 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -0700591 ScopedAssertNoThreadSuspension ants(Thread::Current(), "ImageWriter");
Brian Carlstrom7940e442013-07-12 13:46:57 -0700592 gc::Heap* heap = Runtime::Current()->GetHeap();
593 // TODO: heap validation can't handle this fix up pass
594 heap->DisableObjectValidation();
595 // TODO: Image spaces only?
Mathieu Chartier2d5f39e2014-09-19 17:52:37 -0700596 WriterMutexLock mu(ants.Self(), *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700597 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
598 // Fix up the object previously had hash codes.
599 for (const std::pair<mirror::Object*, uint32_t>& hash_pair : saved_hashes_) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700600 hash_pair.first->SetLockWord(LockWord::FromHashCode(hash_pair.second), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700601 }
602 saved_hashes_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700603}
604
Mathieu Chartier590fee92013-09-13 13:46:47 -0700605void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700606 DCHECK(obj != nullptr);
607 DCHECK(arg != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700608 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700609 // see GetLocalAddress for similar computation
610 size_t offset = image_writer->GetImageOffset(obj);
Ian Rogers13735952014-10-08 12:43:28 -0700611 uint8_t* dst = image_writer->image_->Begin() + offset;
612 const uint8_t* src = reinterpret_cast<const uint8_t*>(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700613 size_t n = obj->SizeOf();
614 DCHECK_LT(offset + n, image_writer->image_->Size());
615 memcpy(dst, src, n);
616 Object* copy = reinterpret_cast<Object*>(dst);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700617 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
618 // word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700619 copy->SetLockWord(LockWord(), false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700620 image_writer->FixupObject(obj, copy);
621}
622
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700623class FixupVisitor {
624 public:
625 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
626 }
627
628 void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
629 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -0700630 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700631 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
632 // image.
633 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700634 offset, image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700635 }
636
637 // java.lang.ref.Reference visitor.
638 void operator()(mirror::Class* /*klass*/, mirror::Reference* ref) const
639 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
640 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
641 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700642 mirror::Reference::ReferentOffset(), image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700643 }
644
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700645 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700646 ImageWriter* const image_writer_;
647 mirror::Object* const copy_;
648};
649
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700650class FixupClassVisitor FINAL : public FixupVisitor {
651 public:
652 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
653 }
654
655 void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
656 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
657 DCHECK(obj->IsClass());
658 FixupVisitor::operator()(obj, offset, false);
659
660 if (offset.Uint32Value() < mirror::Class::EmbeddedVTableOffset().Uint32Value()) {
661 return;
662 }
663 }
664
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700665 void operator()(mirror::Class* klass ATTRIBUTE_UNUSED,
666 mirror::Reference* ref ATTRIBUTE_UNUSED) const
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700667 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
668 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
669 LOG(FATAL) << "Reference not expected here.";
670 }
671};
672
Ian Rogersef7d42f2014-01-06 12:55:46 -0800673void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700674 DCHECK(orig != nullptr);
675 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700676 if (kUseBakerOrBrooksReadBarrier) {
677 orig->AssertReadBarrierPointer();
678 if (kUseBrooksReadBarrier) {
679 // Note the address 'copy' isn't the same as the image address of 'orig'.
680 copy->SetReadBarrierPointer(GetImageAddress(orig));
681 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
682 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800683 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700684 if (orig->IsClass() && orig->AsClass()->ShouldHaveEmbeddedImtAndVTable()) {
685 FixupClassVisitor visitor(this, copy);
686 orig->VisitReferences<true /*visit class*/>(visitor, visitor);
687 } else {
688 FixupVisitor visitor(this, copy);
689 orig->VisitReferences<true /*visit class*/>(visitor, visitor);
690 }
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700691 if (orig->IsArtMethod<kVerifyNone>()) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800692 FixupMethod(orig->AsArtMethod<kVerifyNone>(), down_cast<ArtMethod*>(copy));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700693 }
694}
695
Ian Rogers13735952014-10-08 12:43:28 -0700696const uint8_t* ImageWriter::GetQuickCode(mirror::ArtMethod* method, bool* quick_is_interpreted) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700697 DCHECK(!method->IsResolutionMethod() && !method->IsImtConflictMethod() &&
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700698 !method->IsImtUnimplementedMethod() && !method->IsAbstract()) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700699
700 // Use original code if it exists. Otherwise, set the code pointer to the resolution
701 // trampoline.
702
703 // Quick entrypoint:
Ian Rogers13735952014-10-08 12:43:28 -0700704 const uint8_t* quick_code = GetOatAddress(method->GetQuickOatCodeOffset());
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700705 *quick_is_interpreted = false;
706 if (quick_code != nullptr &&
707 (!method->IsStatic() || method->IsConstructor() || method->GetDeclaringClass()->IsInitialized())) {
708 // We have code for a non-static or initialized method, just use the code.
709 } else if (quick_code == nullptr && method->IsNative() &&
710 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
711 // Non-static or initialized native method missing compiled code, use generic JNI version.
712 quick_code = GetOatAddress(quick_generic_jni_trampoline_offset_);
713 } else if (quick_code == nullptr && !method->IsNative()) {
714 // We don't have code at all for a non-native method, use the interpreter.
715 quick_code = GetOatAddress(quick_to_interpreter_bridge_offset_);
716 *quick_is_interpreted = true;
717 } else {
718 CHECK(!method->GetDeclaringClass()->IsInitialized());
719 // We have code for a static method, but need to go through the resolution stub for class
720 // initialization.
721 quick_code = GetOatAddress(quick_resolution_trampoline_offset_);
722 }
723 return quick_code;
724}
725
Ian Rogers13735952014-10-08 12:43:28 -0700726const uint8_t* ImageWriter::GetQuickEntryPoint(mirror::ArtMethod* method) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700727 // Calculate the quick entry point following the same logic as FixupMethod() below.
728 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700729 Runtime* runtime = Runtime::Current();
730 if (UNLIKELY(method == runtime->GetResolutionMethod())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700731 return GetOatAddress(quick_resolution_trampoline_offset_);
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700732 } else if (UNLIKELY(method == runtime->GetImtConflictMethod() ||
733 method == runtime->GetImtUnimplementedMethod())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700734 return GetOatAddress(quick_imt_conflict_trampoline_offset_);
735 } else {
736 // We assume all methods have code. If they don't currently then we set them to the use the
737 // resolution trampoline. Abstract methods never have code and so we need to make sure their
738 // use results in an AbstractMethodError. We use the interpreter to achieve this.
739 if (UNLIKELY(method->IsAbstract())) {
740 return GetOatAddress(quick_to_interpreter_bridge_offset_);
741 } else {
742 bool quick_is_interpreted;
743 return GetQuickCode(method, &quick_is_interpreted);
744 }
745 }
746}
747
Ian Rogersef7d42f2014-01-06 12:55:46 -0800748void ImageWriter::FixupMethod(ArtMethod* orig, ArtMethod* copy) {
Ian Rogers848871b2013-08-05 10:56:33 -0700749 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
750 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -0700751
Ian Rogers848871b2013-08-05 10:56:33 -0700752 // The resolution method has a special trampoline to call.
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700753 Runtime* runtime = Runtime::Current();
754 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800755 copy->SetEntryPointFromPortableCompiledCode<kVerifyNone>(GetOatAddress(portable_resolution_trampoline_offset_));
756 copy->SetEntryPointFromQuickCompiledCode<kVerifyNone>(GetOatAddress(quick_resolution_trampoline_offset_));
Mathieu Chartier2d2621a2014-10-23 16:48:06 -0700757 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
758 orig == runtime->GetImtUnimplementedMethod())) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800759 copy->SetEntryPointFromPortableCompiledCode<kVerifyNone>(GetOatAddress(portable_imt_conflict_trampoline_offset_));
760 copy->SetEntryPointFromQuickCompiledCode<kVerifyNone>(GetOatAddress(quick_imt_conflict_trampoline_offset_));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700761 } else {
Ian Rogers848871b2013-08-05 10:56:33 -0700762 // We assume all methods have code. If they don't currently then we set them to the use the
763 // resolution trampoline. Abstract methods never have code and so we need to make sure their
764 // use results in an AbstractMethodError. We use the interpreter to achieve this.
765 if (UNLIKELY(orig->IsAbstract())) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800766 copy->SetEntryPointFromPortableCompiledCode<kVerifyNone>(GetOatAddress(portable_to_interpreter_bridge_offset_));
767 copy->SetEntryPointFromQuickCompiledCode<kVerifyNone>(GetOatAddress(quick_to_interpreter_bridge_offset_));
768 copy->SetEntryPointFromInterpreter<kVerifyNone>(reinterpret_cast<EntryPointFromInterpreter*>
Ian Rogers13735952014-10-08 12:43:28 -0700769 (const_cast<uint8_t*>(GetOatAddress(interpreter_to_interpreter_bridge_offset_))));
Ian Rogers848871b2013-08-05 10:56:33 -0700770 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700771 bool quick_is_interpreted;
Ian Rogers13735952014-10-08 12:43:28 -0700772 const uint8_t* quick_code = GetQuickCode(orig, &quick_is_interpreted);
Sebastien Hertze1d07812014-05-21 15:44:09 +0200773 copy->SetEntryPointFromQuickCompiledCode<kVerifyNone>(quick_code);
774
775 // Portable entrypoint:
Ian Rogers13735952014-10-08 12:43:28 -0700776 const uint8_t* portable_code = GetOatAddress(orig->GetPortableOatCodeOffset());
Sebastien Hertze1d07812014-05-21 15:44:09 +0200777 bool portable_is_interpreted = false;
778 if (portable_code != nullptr &&
779 (!orig->IsStatic() || orig->IsConstructor() || orig->GetDeclaringClass()->IsInitialized())) {
780 // We have code for a non-static or initialized method, just use the code.
781 } else if (portable_code == nullptr && orig->IsNative() &&
782 (!orig->IsStatic() || orig->GetDeclaringClass()->IsInitialized())) {
783 // Non-static or initialized native method missing compiled code, use generic JNI version.
784 // TODO: generic JNI support for LLVM.
785 portable_code = GetOatAddress(portable_resolution_trampoline_offset_);
786 } else if (portable_code == nullptr && !orig->IsNative()) {
787 // We don't have code at all for a non-native method, use the interpreter.
788 portable_code = GetOatAddress(portable_to_interpreter_bridge_offset_);
789 portable_is_interpreted = true;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800790 } else {
Sebastien Hertze1d07812014-05-21 15:44:09 +0200791 CHECK(!orig->GetDeclaringClass()->IsInitialized());
792 // We have code for a static method, but need to go through the resolution stub for class
793 // initialization.
794 portable_code = GetOatAddress(portable_resolution_trampoline_offset_);
Ian Rogers848871b2013-08-05 10:56:33 -0700795 }
Sebastien Hertze1d07812014-05-21 15:44:09 +0200796 copy->SetEntryPointFromPortableCompiledCode<kVerifyNone>(portable_code);
797
798 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -0700799 if (orig->IsNative()) {
800 // The native method's pointer is set to a stub to lookup via dlsym.
801 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartier4e305412014-02-19 10:54:44 -0800802 copy->SetNativeMethod<kVerifyNone>(GetOatAddress(jni_dlsym_lookup_offset_));
Ian Rogers848871b2013-08-05 10:56:33 -0700803 } else {
804 // Normal (non-abstract non-native) methods have various tables to relocate.
Ian Rogers848871b2013-08-05 10:56:33 -0700805 uint32_t native_gc_map_offset = orig->GetOatNativeGcMapOffset();
Ian Rogers13735952014-10-08 12:43:28 -0700806 const uint8_t* native_gc_map = GetOatAddress(native_gc_map_offset);
Mathieu Chartier4e305412014-02-19 10:54:44 -0800807 copy->SetNativeGcMap<kVerifyNone>(reinterpret_cast<const uint8_t*>(native_gc_map));
Ian Rogers848871b2013-08-05 10:56:33 -0700808 }
Sebastien Hertze1d07812014-05-21 15:44:09 +0200809
810 // Interpreter entrypoint:
811 // Set the interpreter entrypoint depending on whether there is compiled code or not.
812 uint32_t interpreter_code = (quick_is_interpreted && portable_is_interpreted)
813 ? interpreter_to_interpreter_bridge_offset_
814 : interpreter_to_compiled_code_bridge_offset_;
815 copy->SetEntryPointFromInterpreter<kVerifyNone>(
816 reinterpret_cast<EntryPointFromInterpreter*>(
Ian Rogers13735952014-10-08 12:43:28 -0700817 const_cast<uint8_t*>(GetOatAddress(interpreter_code))));
Ian Rogers848871b2013-08-05 10:56:33 -0700818 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700819 }
820}
821
Alex Lighta59dd802014-07-02 16:28:08 -0700822static OatHeader* GetOatHeaderFromElf(ElfFile* elf) {
Tong Shen62d1ca32014-09-03 17:24:56 -0700823 uint64_t data_sec_offset;
824 bool has_data_sec = elf->GetSectionOffsetAndSize(".rodata", &data_sec_offset, nullptr);
825 if (!has_data_sec) {
Alex Lighta59dd802014-07-02 16:28:08 -0700826 return nullptr;
827 }
Tong Shen62d1ca32014-09-03 17:24:56 -0700828 return reinterpret_cast<OatHeader*>(elf->Begin() + data_sec_offset);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800829}
830
Vladimir Markof4da6752014-08-01 19:04:18 +0100831void ImageWriter::SetOatChecksumFromElfFile(File* elf_file) {
Alex Lighta59dd802014-07-02 16:28:08 -0700832 std::string error_msg;
833 std::unique_ptr<ElfFile> elf(ElfFile::Open(elf_file, PROT_READ|PROT_WRITE,
834 MAP_SHARED, &error_msg));
835 if (elf.get() == nullptr) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100836 LOG(FATAL) << "Unable open oat file: " << error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -0700837 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700838 }
Alex Lighta59dd802014-07-02 16:28:08 -0700839 OatHeader* oat_header = GetOatHeaderFromElf(elf.get());
840 CHECK(oat_header != nullptr);
841 CHECK(oat_header->IsValid());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700842
Brian Carlstrom7940e442013-07-12 13:46:57 -0700843 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Alex Lighta59dd802014-07-02 16:28:08 -0700844 image_header->SetOatChecksum(oat_header->GetChecksum());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700845}
846
847} // namespace art