blob: 0b304ebd1dd5c21c8b197e6ef13c91b26f07fd55 [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"
Alex Lighta59dd802014-07-02 16:28:08 -070032#include "elf_patcher.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070033#include "elf_writer.h"
34#include "gc/accounting/card_table-inl.h"
35#include "gc/accounting/heap_bitmap.h"
Mathieu Chartier31e89252013-08-28 11:29:12 -070036#include "gc/accounting/space_bitmap-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070037#include "gc/heap.h"
38#include "gc/space/large_object_space.h"
39#include "gc/space/space-inl.h"
40#include "globals.h"
41#include "image.h"
42#include "intern_table.h"
Mathieu Chartierad2541a2013-10-25 10:05:23 -070043#include "lock_word.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070044#include "mirror/art_field-inl.h"
45#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070046#include "mirror/array-inl.h"
47#include "mirror/class-inl.h"
48#include "mirror/class_loader.h"
49#include "mirror/dex_cache-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070050#include "mirror/object-inl.h"
51#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070052#include "mirror/string-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070053#include "oat.h"
54#include "oat_file.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070055#include "runtime.h"
56#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070057#include "handle_scope-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070058#include "utils.h"
59
Brian Carlstromea46f952013-07-30 01:26:50 -070060using ::art::mirror::ArtField;
61using ::art::mirror::ArtMethod;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070062using ::art::mirror::Class;
63using ::art::mirror::DexCache;
64using ::art::mirror::EntryPointFromInterpreter;
Brian Carlstrom3e3d5912013-07-18 00:19:45 -070065using ::art::mirror::Object;
66using ::art::mirror::ObjectArray;
67using ::art::mirror::String;
Brian Carlstrom7940e442013-07-12 13:46:57 -070068
69namespace art {
70
71bool ImageWriter::Write(const std::string& image_filename,
72 uintptr_t image_begin,
73 const std::string& oat_filename,
Igor Murashkin90ca5c02014-10-22 11:37:02 -070074 const std::string& oat_location,
75 bool compile_pic) {
Brian Carlstrom7940e442013-07-12 13:46:57 -070076 CHECK(!image_filename.empty());
77
78 CHECK_NE(image_begin, 0U);
79 image_begin_ = reinterpret_cast<byte*>(image_begin);
Igor Murashkin90ca5c02014-10-22 11:37:02 -070080 compile_pic_ = compile_pic;
Brian Carlstrom7940e442013-07-12 13:46:57 -070081
82 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -070083
Ian Rogers700a4022014-05-19 16:49:03 -070084 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -070085 if (oat_file.get() == NULL) {
86 LOG(ERROR) << "Failed to open oat file " << oat_filename << " for " << oat_location;
87 return false;
88 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -070089 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -070090 oat_file_ = OatFile::OpenReadable(oat_file.get(), oat_location, &error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -070091 if (oat_file_ == nullptr) {
92 LOG(ERROR) << "Failed to open writable oat file " << oat_filename << " for " << oat_location
93 << ": " << error_msg;
Brian Carlstromc50d8e12013-07-23 22:35:16 -070094 return false;
95 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -070096 CHECK_EQ(class_linker->RegisterOatFile(oat_file_), oat_file_);
Brian Carlstrom7940e442013-07-12 13:46:57 -070097
Ian Rogers848871b2013-08-05 10:56:33 -070098 interpreter_to_interpreter_bridge_offset_ =
99 oat_file_->GetOatHeader().GetInterpreterToInterpreterBridgeOffset();
100 interpreter_to_compiled_code_bridge_offset_ =
101 oat_file_->GetOatHeader().GetInterpreterToCompiledCodeBridgeOffset();
102
103 jni_dlsym_lookup_offset_ = oat_file_->GetOatHeader().GetJniDlsymLookupOffset();
104
Jeff Hao88474b42013-10-23 16:24:40 -0700105 portable_imt_conflict_trampoline_offset_ =
106 oat_file_->GetOatHeader().GetPortableImtConflictTrampolineOffset();
Ian Rogers848871b2013-08-05 10:56:33 -0700107 portable_resolution_trampoline_offset_ =
108 oat_file_->GetOatHeader().GetPortableResolutionTrampolineOffset();
109 portable_to_interpreter_bridge_offset_ =
110 oat_file_->GetOatHeader().GetPortableToInterpreterBridgeOffset();
111
Andreas Gampe2da88232014-02-27 12:26:20 -0800112 quick_generic_jni_trampoline_offset_ =
113 oat_file_->GetOatHeader().GetQuickGenericJniTrampolineOffset();
Jeff Hao88474b42013-10-23 16:24:40 -0700114 quick_imt_conflict_trampoline_offset_ =
115 oat_file_->GetOatHeader().GetQuickImtConflictTrampolineOffset();
Ian Rogers848871b2013-08-05 10:56:33 -0700116 quick_resolution_trampoline_offset_ =
117 oat_file_->GetOatHeader().GetQuickResolutionTrampolineOffset();
118 quick_to_interpreter_bridge_offset_ =
119 oat_file_->GetOatHeader().GetQuickToInterpreterBridgeOffset();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700120 {
121 Thread::Current()->TransitionFromSuspendedToRunnable();
122 PruneNonImageClasses(); // Remove junk
123 ComputeLazyFieldsForImageClasses(); // Add useful information
124 ComputeEagerResolvedStrings();
125 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
126 }
127 gc::Heap* heap = Runtime::Current()->GetHeap();
128 heap->CollectGarbage(false); // Remove garbage.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700129
130 if (!AllocMemory()) {
131 return false;
132 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700133
134 if (kIsDebugBuild) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700135 ScopedObjectAccess soa(Thread::Current());
136 CheckNonImageClassesRemoved();
137 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700138
Brian Carlstrom7940e442013-07-12 13:46:57 -0700139 Thread::Current()->TransitionFromSuspendedToRunnable();
140 size_t oat_loaded_size = 0;
141 size_t oat_data_offset = 0;
142 ElfWriter::GetOatElfInformation(oat_file.get(), oat_loaded_size, oat_data_offset);
143 CalculateNewObjectOffsets(oat_loaded_size, oat_data_offset);
144 CopyAndFixupObjects();
Alex Light53cb16b2014-06-12 11:26:29 -0700145
146 PatchOatCodeAndMethods(oat_file.get());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700147 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
148
Ian Rogers700a4022014-05-19 16:49:03 -0700149 std::unique_ptr<File> image_file(OS::CreateEmptyFile(image_filename.c_str()));
Mathieu Chartier31e89252013-08-28 11:29:12 -0700150 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700151 if (image_file.get() == NULL) {
152 LOG(ERROR) << "Failed to open image file " << image_filename;
153 return false;
154 }
155 if (fchmod(image_file->Fd(), 0644) != 0) {
156 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
157 return EXIT_FAILURE;
158 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700159
160 // Write out the image.
161 CHECK_EQ(image_end_, image_header->GetImageSize());
162 if (!image_file->WriteFully(image_->Begin(), image_end_)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700163 PLOG(ERROR) << "Failed to write image file " << image_filename;
164 return false;
165 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700166
167 // Write out the image bitmap at the page aligned start of the image end.
168 CHECK_ALIGNED(image_header->GetImageBitmapOffset(), kPageSize);
169 if (!image_file->Write(reinterpret_cast<char*>(image_bitmap_->Begin()),
170 image_header->GetImageBitmapSize(),
171 image_header->GetImageBitmapOffset())) {
172 PLOG(ERROR) << "Failed to write image file " << image_filename;
173 return false;
174 }
175
Brian Carlstrom7940e442013-07-12 13:46:57 -0700176 return true;
177}
178
Mathieu Chartier590fee92013-09-13 13:46:47 -0700179void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
180 DCHECK(object != nullptr);
181 DCHECK_NE(offset, 0U);
182 DCHECK(!IsImageOffsetAssigned(object));
183 mirror::Object* obj = reinterpret_cast<mirror::Object*>(image_->Begin() + offset);
184 DCHECK_ALIGNED(obj, kObjectAlignment);
185 image_bitmap_->Set(obj);
186 // Before we stomp over the lock word, save the hash code for later.
187 Monitor::Deflate(Thread::Current(), object);;
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700188 LockWord lw(object->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700189 switch (lw.GetState()) {
190 case LockWord::kFatLocked: {
191 LOG(FATAL) << "Fat locked object " << obj << " found during object copy";
192 break;
193 }
194 case LockWord::kThinLocked: {
195 LOG(FATAL) << "Thin locked object " << obj << " found during object copy";
196 break;
197 }
198 case LockWord::kUnlocked:
199 // No hash, don't need to save it.
200 break;
201 case LockWord::kHashCode:
202 saved_hashes_.push_back(std::make_pair(obj, lw.GetHashCode()));
203 break;
204 default:
205 LOG(FATAL) << "Unreachable.";
206 break;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700207 }
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700208 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700209 DCHECK(IsImageOffsetAssigned(object));
210}
211
212void ImageWriter::AssignImageOffset(mirror::Object* object) {
213 DCHECK(object != nullptr);
214 SetImageOffset(object, image_end_);
215 image_end_ += RoundUp(object->SizeOf(), 8); // 64-bit alignment
216 DCHECK_LT(image_end_, image_->Size());
217}
218
Ian Rogersef7d42f2014-01-06 12:55:46 -0800219bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700220 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700221 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700222}
223
Ian Rogersef7d42f2014-01-06 12:55:46 -0800224size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700225 DCHECK(object != nullptr);
226 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700227 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700228 size_t offset = lock_word.ForwardingAddress();
229 DCHECK_LT(offset, image_end_);
230 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700231}
232
Brian Carlstrom7940e442013-07-12 13:46:57 -0700233bool ImageWriter::AllocMemory() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700234 size_t length = RoundUp(Runtime::Current()->GetHeap()->GetTotalMemory(), kPageSize);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700235 std::string error_msg;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700236 image_.reset(MemMap::MapAnonymous("image writer image", NULL, length, PROT_READ | PROT_WRITE,
Ian Rogersef7d42f2014-01-06 12:55:46 -0800237 true, &error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700238 if (UNLIKELY(image_.get() == nullptr)) {
239 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700240 return false;
241 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700242
243 // Create the image bitmap.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700244 image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create("image bitmap", image_->Begin(),
245 length));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700246 if (image_bitmap_.get() == nullptr) {
247 LOG(ERROR) << "Failed to allocate memory for image bitmap";
248 return false;
249 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700250 return true;
251}
252
253void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700254 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700255 class_linker->VisitClassesWithoutClassesLock(ComputeLazyFieldsForClassesVisitor, NULL);
256}
257
258bool ImageWriter::ComputeLazyFieldsForClassesVisitor(Class* c, void* /*arg*/) {
Mathieu Chartierf8322842014-05-16 10:59:25 -0700259 Thread* self = Thread::Current();
260 StackHandleScope<1> hs(self);
261 mirror::Class::ComputeName(hs.NewHandle(c));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700262 return true;
263}
264
265void ImageWriter::ComputeEagerResolvedStringsCallback(Object* obj, void* arg) {
266 if (!obj->GetClass()->IsStringClass()) {
267 return;
268 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700269 mirror::String* string = obj->AsString();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700270 const uint16_t* utf16_string = string->GetCharArray()->GetData() + string->GetOffset();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700271 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
272 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
273 size_t dex_cache_count = class_linker->GetDexCacheCount();
274 for (size_t i = 0; i < dex_cache_count; ++i) {
275 DexCache* dex_cache = class_linker->GetDexCache(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700276 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers24c534d2013-11-14 00:15:00 -0800277 const DexFile::StringId* string_id;
278 if (UNLIKELY(string->GetLength() == 0)) {
279 string_id = dex_file.FindStringId("");
280 } else {
281 string_id = dex_file.FindStringId(utf16_string);
282 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700283 if (string_id != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700284 // This string occurs in this dex file, assign the dex cache entry.
285 uint32_t string_idx = dex_file.GetIndexForStringId(*string_id);
286 if (dex_cache->GetResolvedString(string_idx) == NULL) {
287 dex_cache->SetResolvedString(string_idx, string);
288 }
289 }
290 }
291}
292
Mathieu Chartier590fee92013-09-13 13:46:47 -0700293void ImageWriter::ComputeEagerResolvedStrings() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
294 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
295 Runtime::Current()->GetHeap()->VisitObjects(ComputeEagerResolvedStringsCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700296}
297
Ian Rogersef7d42f2014-01-06 12:55:46 -0800298bool ImageWriter::IsImageClass(Class* klass) {
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700299 std::string temp;
300 return compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700301}
302
303struct NonImageClasses {
304 ImageWriter* image_writer;
305 std::set<std::string>* non_image_classes;
306};
307
308void ImageWriter::PruneNonImageClasses() {
309 if (compiler_driver_.GetImageClasses() == NULL) {
310 return;
311 }
312 Runtime* runtime = Runtime::Current();
313 ClassLinker* class_linker = runtime->GetClassLinker();
314
315 // Make a list of classes we would like to prune.
316 std::set<std::string> non_image_classes;
317 NonImageClasses context;
318 context.image_writer = this;
319 context.non_image_classes = &non_image_classes;
320 class_linker->VisitClasses(NonImageClassesVisitor, &context);
321
322 // Remove the undesired classes from the class roots.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700323 for (const std::string& it : non_image_classes) {
Mathieu Chartiere05d1d52014-11-03 11:41:47 -0800324 bool result = class_linker->RemoveClass(it.c_str(), NULL);
325 DCHECK(result);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700326 }
327
328 // Clear references to removed classes from the DexCaches.
Brian Carlstromea46f952013-07-30 01:26:50 -0700329 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700330 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
331 size_t dex_cache_count = class_linker->GetDexCacheCount();
332 for (size_t idx = 0; idx < dex_cache_count; ++idx) {
333 DexCache* dex_cache = class_linker->GetDexCache(idx);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700334 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
335 Class* klass = dex_cache->GetResolvedType(i);
336 if (klass != NULL && !IsImageClass(klass)) {
337 dex_cache->SetResolvedType(i, NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700338 }
339 }
340 for (size_t i = 0; i < dex_cache->NumResolvedMethods(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700341 ArtMethod* method = dex_cache->GetResolvedMethod(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700342 if (method != NULL && !IsImageClass(method->GetDeclaringClass())) {
343 dex_cache->SetResolvedMethod(i, resolution_method);
344 }
345 }
346 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700347 ArtField* field = dex_cache->GetResolvedField(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700348 if (field != NULL && !IsImageClass(field->GetDeclaringClass())) {
349 dex_cache->SetResolvedField(i, NULL);
350 }
351 }
352 }
353}
354
355bool ImageWriter::NonImageClassesVisitor(Class* klass, void* arg) {
356 NonImageClasses* context = reinterpret_cast<NonImageClasses*>(arg);
357 if (!context->image_writer->IsImageClass(klass)) {
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700358 std::string temp;
359 context->non_image_classes->insert(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700360 }
361 return true;
362}
363
364void ImageWriter::CheckNonImageClassesRemoved()
365 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700366 if (compiler_driver_.GetImageClasses() != nullptr) {
367 gc::Heap* heap = Runtime::Current()->GetHeap();
368 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
369 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700370 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700371}
372
373void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
374 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700375 if (obj->IsClass()) {
376 Class* klass = obj->AsClass();
377 if (!image_writer->IsImageClass(klass)) {
378 image_writer->DumpImageClasses();
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700379 std::string temp;
380 CHECK(image_writer->IsImageClass(klass)) << klass->GetDescriptor(&temp)
Mathieu Chartier590fee92013-09-13 13:46:47 -0700381 << " " << PrettyDescriptor(klass);
382 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700383 }
384}
385
386void ImageWriter::DumpImageClasses() {
Ian Rogerscb6b0f32014-08-12 02:30:58 -0700387 const std::set<std::string>* image_classes = compiler_driver_.GetImageClasses();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700388 CHECK(image_classes != NULL);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700389 for (const std::string& image_class : *image_classes) {
390 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700391 }
392}
393
Mathieu Chartier590fee92013-09-13 13:46:47 -0700394void ImageWriter::CalculateObjectOffsets(Object* obj) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700395 DCHECK(obj != NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700396 // if it is a string, we want to intern it if its not interned.
397 if (obj->GetClass()->IsStringClass()) {
398 // we must be an interned string that was forward referenced and already assigned
Mathieu Chartier590fee92013-09-13 13:46:47 -0700399 if (IsImageOffsetAssigned(obj)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700400 DCHECK_EQ(obj, obj->AsString()->Intern());
401 return;
402 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700403 mirror::String* const interned = obj->AsString()->Intern();
404 if (obj != interned) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700405 if (!IsImageOffsetAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700406 // interned obj is after us, allocate its location early
Mathieu Chartier590fee92013-09-13 13:46:47 -0700407 AssignImageOffset(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700408 }
409 // point those looking for this object to the interned version.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700410 SetImageOffset(obj, GetImageOffset(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700411 return;
412 }
413 // else (obj == interned), nothing to do but fall through to the normal case
414 }
415
Mathieu Chartier590fee92013-09-13 13:46:47 -0700416 AssignImageOffset(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700417}
418
419ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
420 Runtime* runtime = Runtime::Current();
421 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700422 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700423 StackHandleScope<3> hs(self);
424 Handle<Class> object_array_class(hs.NewHandle(
425 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700426
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700427 // build an Object[] of all the DexCaches used in the source_space_.
428 // Since we can't hold the dex lock when allocating the dex_caches
429 // ObjectArray, we lock the dex lock twice, first to get the number
430 // of dex caches first and then lock it again to copy the dex
431 // caches. We check that the number of dex caches does not change.
432 size_t dex_cache_count;
433 {
434 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
435 dex_cache_count = class_linker->GetDexCacheCount();
436 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700437 Handle<ObjectArray<Object>> dex_caches(
438 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(),
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700439 dex_cache_count)));
440 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
441 {
442 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
443 CHECK_EQ(dex_cache_count, class_linker->GetDexCacheCount())
444 << "The number of dex caches changed.";
445 for (size_t i = 0; i < dex_cache_count; ++i) {
446 dex_caches->Set<false>(i, class_linker->GetDexCache(i));
447 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700448 }
449
450 // build an Object[] of the roots needed to restore the runtime
Ian Rogers700a4022014-05-19 16:49:03 -0700451 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700452 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100453 image_roots->Set<false>(ImageHeader::kResolutionMethod, runtime->GetResolutionMethod());
454 image_roots->Set<false>(ImageHeader::kImtConflictMethod, runtime->GetImtConflictMethod());
Mathieu Chartier1fb463e2014-10-23 16:48:06 -0700455 image_roots->Set<false>(ImageHeader::kImtUnimplementedMethod,
456 runtime->GetImtUnimplementedMethod());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100457 image_roots->Set<false>(ImageHeader::kDefaultImt, runtime->GetDefaultImt());
458 image_roots->Set<false>(ImageHeader::kCalleeSaveMethod,
459 runtime->GetCalleeSaveMethod(Runtime::kSaveAll));
460 image_roots->Set<false>(ImageHeader::kRefsOnlySaveMethod,
461 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly));
462 image_roots->Set<false>(ImageHeader::kRefsAndArgsSaveMethod,
463 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700464 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100465 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700466 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
467 CHECK(image_roots->Get(i) != NULL);
468 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700469 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700470}
471
Mathieu Chartier590fee92013-09-13 13:46:47 -0700472// Walk instance fields of the given Class. Separate function to allow recursion on the super
473// class.
474void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
475 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700476 StackHandleScope<1> hs(Thread::Current());
477 Handle<mirror::Class> h_class(hs.NewHandle(klass));
478 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700479 if (super != nullptr) {
480 WalkInstanceFields(obj, super);
481 }
482 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700483 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700484 for (size_t i = 0; i < num_reference_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700485 mirror::ArtField* field = h_class->GetInstanceField(i);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700486 MemberOffset field_offset = field->GetOffset();
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700487 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700488 if (value != nullptr) {
489 WalkFieldsInOrder(value);
490 }
491 }
492}
493
494// For an unvisited object, visit it then all its children found via fields.
495void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
496 if (!IsImageOffsetAssigned(obj)) {
497 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700498 StackHandleScope<2> hs(Thread::Current());
499 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
500 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700501 // visit the object itself.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700502 CalculateObjectOffsets(h_obj.Get());
503 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700504 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700505 if (h_obj->IsClass()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700506 size_t num_static_fields = klass->NumReferenceStaticFields();
507 for (size_t i = 0; i < num_static_fields; ++i) {
508 mirror::ArtField* field = klass->GetStaticField(i);
509 MemberOffset field_offset = field->GetOffset();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700510 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700511 if (value != nullptr) {
512 WalkFieldsInOrder(value);
513 }
514 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700515 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700516 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700517 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700518 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700519 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700520 mirror::Object* value = obj_array->Get(i);
521 if (value != nullptr) {
522 WalkFieldsInOrder(value);
523 }
524 }
525 }
526 }
527}
528
529void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
530 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
531 DCHECK(writer != nullptr);
532 writer->WalkFieldsInOrder(obj);
533}
534
Brian Carlstrom7940e442013-07-12 13:46:57 -0700535void ImageWriter::CalculateNewObjectOffsets(size_t oat_loaded_size, size_t oat_data_offset) {
536 CHECK_NE(0U, oat_loaded_size);
537 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700538 StackHandleScope<1> hs(self);
539 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(CreateImageRoots()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700540
541 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700542 DCHECK_EQ(0U, image_end_);
543
Mathieu Chartier31e89252013-08-28 11:29:12 -0700544 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -0700545 // know where image_roots is going to end up
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700546 image_end_ += RoundUp(sizeof(ImageHeader), 8); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -0700547
548 {
549 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700550 // TODO: Image spaces only?
Brian Carlstrom7940e442013-07-12 13:46:57 -0700551 const char* old = self->StartAssertNoThreadSuspension("ImageWriter");
Mathieu Chartier590fee92013-09-13 13:46:47 -0700552 DCHECK_LT(image_end_, image_->Size());
553 // Clear any pre-existing monitors which may have been in the monitor words.
554 heap->VisitObjects(WalkFieldsCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700555 self->EndAssertNoThreadSuspension(old);
556 }
557
558 const byte* oat_file_begin = image_begin_ + RoundUp(image_end_, kPageSize);
559 const byte* oat_file_end = oat_file_begin + oat_loaded_size;
560 oat_data_begin_ = oat_file_begin + oat_data_offset;
561 const byte* oat_data_end = oat_data_begin_ + oat_file_->Size();
562
Mathieu Chartier31e89252013-08-28 11:29:12 -0700563 // Return to write header at start of image with future location of image_roots. At this point,
564 // image_end_ is the size of the image (excluding bitmaps).
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700565 const size_t heap_bytes_per_bitmap_byte = kBitsPerByte * kObjectAlignment;
Mathieu Chartier12aeccd2013-11-13 15:52:06 -0800566 const size_t bitmap_bytes = RoundUp(image_end_, heap_bytes_per_bitmap_byte) /
567 heap_bytes_per_bitmap_byte;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800568 ImageHeader image_header(PointerToLowMemUInt32(image_begin_),
Mathieu Chartier31e89252013-08-28 11:29:12 -0700569 static_cast<uint32_t>(image_end_),
570 RoundUp(image_end_, kPageSize),
Mathieu Chartier12aeccd2013-11-13 15:52:06 -0800571 RoundUp(bitmap_bytes, kPageSize),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700572 PointerToLowMemUInt32(GetImageAddress(image_roots.Get())),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700573 oat_file_->GetOatHeader().GetChecksum(),
Ian Rogersef7d42f2014-01-06 12:55:46 -0800574 PointerToLowMemUInt32(oat_file_begin),
575 PointerToLowMemUInt32(oat_data_begin_),
576 PointerToLowMemUInt32(oat_data_end),
Igor Murashkin90ca5c02014-10-22 11:37:02 -0700577 PointerToLowMemUInt32(oat_file_end),
578 compile_pic_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700579 memcpy(image_->Begin(), &image_header, sizeof(image_header));
580
581 // Note that image_end_ is left at end of used space
582}
583
584void ImageWriter::CopyAndFixupObjects()
585 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
586 Thread* self = Thread::Current();
587 const char* old_cause = self->StartAssertNoThreadSuspension("ImageWriter");
588 gc::Heap* heap = Runtime::Current()->GetHeap();
589 // TODO: heap validation can't handle this fix up pass
590 heap->DisableObjectValidation();
591 // TODO: Image spaces only?
592 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700593 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
594 // Fix up the object previously had hash codes.
595 for (const std::pair<mirror::Object*, uint32_t>& hash_pair : saved_hashes_) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700596 hash_pair.first->SetLockWord(LockWord::FromHashCode(hash_pair.second), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700597 }
598 saved_hashes_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700599 self->EndAssertNoThreadSuspension(old_cause);
600}
601
Mathieu Chartier590fee92013-09-13 13:46:47 -0700602void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700603 DCHECK(obj != nullptr);
604 DCHECK(arg != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700605 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700606 // see GetLocalAddress for similar computation
607 size_t offset = image_writer->GetImageOffset(obj);
608 byte* dst = image_writer->image_->Begin() + offset;
609 const byte* src = reinterpret_cast<const byte*>(obj);
610 size_t n = obj->SizeOf();
611 DCHECK_LT(offset + n, image_writer->image_->Size());
612 memcpy(dst, src, n);
613 Object* copy = reinterpret_cast<Object*>(dst);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700614 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
615 // word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700616 copy->SetLockWord(LockWord(), false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700617 image_writer->FixupObject(obj, copy);
618}
619
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700620class FixupVisitor {
621 public:
622 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
623 }
624
625 void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
626 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -0700627 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700628 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
629 // image.
630 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700631 offset, image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700632 }
633
634 // java.lang.ref.Reference visitor.
635 void operator()(mirror::Class* /*klass*/, mirror::Reference* ref) const
636 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
637 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
638 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700639 mirror::Reference::ReferentOffset(), image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700640 }
641
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700642 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700643 ImageWriter* const image_writer_;
644 mirror::Object* const copy_;
645};
646
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700647class FixupClassVisitor FINAL : public FixupVisitor {
648 public:
649 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
650 }
651
652 void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
653 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
654 DCHECK(obj->IsClass());
655 FixupVisitor::operator()(obj, offset, false);
656
657 if (offset.Uint32Value() < mirror::Class::EmbeddedVTableOffset().Uint32Value()) {
658 return;
659 }
660 }
661
662 void operator()(mirror::Class* /*klass*/, mirror::Reference* ref) const
663 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
664 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
665 LOG(FATAL) << "Reference not expected here.";
666 }
667};
668
Ian Rogersef7d42f2014-01-06 12:55:46 -0800669void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700670 DCHECK(orig != nullptr);
671 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700672 if (kUseBakerOrBrooksReadBarrier) {
673 orig->AssertReadBarrierPointer();
674 if (kUseBrooksReadBarrier) {
675 // Note the address 'copy' isn't the same as the image address of 'orig'.
676 copy->SetReadBarrierPointer(GetImageAddress(orig));
677 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
678 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800679 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700680 if (orig->IsClass() && orig->AsClass()->ShouldHaveEmbeddedImtAndVTable()) {
681 FixupClassVisitor visitor(this, copy);
682 orig->VisitReferences<true /*visit class*/>(visitor, visitor);
683 } else {
684 FixupVisitor visitor(this, copy);
685 orig->VisitReferences<true /*visit class*/>(visitor, visitor);
686 }
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700687 if (orig->IsArtMethod<kVerifyNone>()) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800688 FixupMethod(orig->AsArtMethod<kVerifyNone>(), down_cast<ArtMethod*>(copy));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700689 }
690}
691
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700692const byte* ImageWriter::GetQuickCode(mirror::ArtMethod* method, bool* quick_is_interpreted) {
693 DCHECK(!method->IsResolutionMethod() && !method->IsImtConflictMethod() &&
Mathieu Chartier1fb463e2014-10-23 16:48:06 -0700694 !method->IsImtUnimplementedMethod() && !method->IsAbstract()) << PrettyMethod(method);
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700695
696 // Use original code if it exists. Otherwise, set the code pointer to the resolution
697 // trampoline.
698
699 // Quick entrypoint:
700 const byte* quick_code = GetOatAddress(method->GetQuickOatCodeOffset());
701 *quick_is_interpreted = false;
702 if (quick_code != nullptr &&
703 (!method->IsStatic() || method->IsConstructor() || method->GetDeclaringClass()->IsInitialized())) {
704 // We have code for a non-static or initialized method, just use the code.
705 } else if (quick_code == nullptr && method->IsNative() &&
706 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
707 // Non-static or initialized native method missing compiled code, use generic JNI version.
708 quick_code = GetOatAddress(quick_generic_jni_trampoline_offset_);
709 } else if (quick_code == nullptr && !method->IsNative()) {
710 // We don't have code at all for a non-native method, use the interpreter.
711 quick_code = GetOatAddress(quick_to_interpreter_bridge_offset_);
712 *quick_is_interpreted = true;
713 } else {
714 CHECK(!method->GetDeclaringClass()->IsInitialized());
715 // We have code for a static method, but need to go through the resolution stub for class
716 // initialization.
717 quick_code = GetOatAddress(quick_resolution_trampoline_offset_);
718 }
719 return quick_code;
720}
721
722const byte* ImageWriter::GetQuickEntryPoint(mirror::ArtMethod* method) {
723 // Calculate the quick entry point following the same logic as FixupMethod() below.
724 // The resolution method has a special trampoline to call.
Mathieu Chartier1fb463e2014-10-23 16:48:06 -0700725 Runtime* runtime = Runtime::Current();
726 if (UNLIKELY(method == runtime->GetResolutionMethod())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700727 return GetOatAddress(quick_resolution_trampoline_offset_);
Mathieu Chartier1fb463e2014-10-23 16:48:06 -0700728 } else if (UNLIKELY(method == runtime->GetImtConflictMethod() ||
729 method == runtime->GetImtUnimplementedMethod())) {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700730 return GetOatAddress(quick_imt_conflict_trampoline_offset_);
731 } else {
732 // We assume all methods have code. If they don't currently then we set them to the use the
733 // resolution trampoline. Abstract methods never have code and so we need to make sure their
734 // use results in an AbstractMethodError. We use the interpreter to achieve this.
735 if (UNLIKELY(method->IsAbstract())) {
736 return GetOatAddress(quick_to_interpreter_bridge_offset_);
737 } else {
738 bool quick_is_interpreted;
739 return GetQuickCode(method, &quick_is_interpreted);
740 }
741 }
742}
743
Ian Rogersef7d42f2014-01-06 12:55:46 -0800744void ImageWriter::FixupMethod(ArtMethod* orig, ArtMethod* copy) {
Ian Rogers848871b2013-08-05 10:56:33 -0700745 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
746 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -0700747
Ian Rogers848871b2013-08-05 10:56:33 -0700748 // The resolution method has a special trampoline to call.
Mathieu Chartier1fb463e2014-10-23 16:48:06 -0700749 Runtime* runtime = Runtime::Current();
750 if (UNLIKELY(orig == runtime->GetResolutionMethod())) {
Ian Rogers63bc11e2014-09-18 08:56:45 -0700751#if defined(ART_USE_PORTABLE_COMPILER)
Mathieu Chartier4e305412014-02-19 10:54:44 -0800752 copy->SetEntryPointFromPortableCompiledCode<kVerifyNone>(GetOatAddress(portable_resolution_trampoline_offset_));
Ian Rogers63bc11e2014-09-18 08:56:45 -0700753#endif
Mathieu Chartier4e305412014-02-19 10:54:44 -0800754 copy->SetEntryPointFromQuickCompiledCode<kVerifyNone>(GetOatAddress(quick_resolution_trampoline_offset_));
Mathieu Chartier1fb463e2014-10-23 16:48:06 -0700755 } else if (UNLIKELY(orig == runtime->GetImtConflictMethod() ||
756 orig == runtime->GetImtUnimplementedMethod())) {
Ian Rogers63bc11e2014-09-18 08:56:45 -0700757#if defined(ART_USE_PORTABLE_COMPILER)
Mathieu Chartier4e305412014-02-19 10:54:44 -0800758 copy->SetEntryPointFromPortableCompiledCode<kVerifyNone>(GetOatAddress(portable_imt_conflict_trampoline_offset_));
Ian Rogers63bc11e2014-09-18 08:56:45 -0700759#endif
Mathieu Chartier4e305412014-02-19 10:54:44 -0800760 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())) {
Ian Rogers63bc11e2014-09-18 08:56:45 -0700766#if defined(ART_USE_PORTABLE_COMPILER)
Mathieu Chartier4e305412014-02-19 10:54:44 -0800767 copy->SetEntryPointFromPortableCompiledCode<kVerifyNone>(GetOatAddress(portable_to_interpreter_bridge_offset_));
Ian Rogers63bc11e2014-09-18 08:56:45 -0700768#endif
Mathieu Chartier4e305412014-02-19 10:54:44 -0800769 copy->SetEntryPointFromQuickCompiledCode<kVerifyNone>(GetOatAddress(quick_to_interpreter_bridge_offset_));
770 copy->SetEntryPointFromInterpreter<kVerifyNone>(reinterpret_cast<EntryPointFromInterpreter*>
Ian Rogersef7d42f2014-01-06 12:55:46 -0800771 (const_cast<byte*>(GetOatAddress(interpreter_to_interpreter_bridge_offset_))));
Ian Rogers848871b2013-08-05 10:56:33 -0700772 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700773 bool quick_is_interpreted;
774 const byte* quick_code = GetQuickCode(orig, &quick_is_interpreted);
Sebastien Hertze1d07812014-05-21 15:44:09 +0200775 copy->SetEntryPointFromQuickCompiledCode<kVerifyNone>(quick_code);
776
777 // Portable entrypoint:
Sebastien Hertze1d07812014-05-21 15:44:09 +0200778 bool portable_is_interpreted = false;
Ian Rogers63bc11e2014-09-18 08:56:45 -0700779#if defined(ART_USE_PORTABLE_COMPILER)
780 const byte* portable_code = GetOatAddress(orig->GetPortableOatCodeOffset());
Sebastien Hertze1d07812014-05-21 15:44:09 +0200781 if (portable_code != nullptr &&
782 (!orig->IsStatic() || orig->IsConstructor() || orig->GetDeclaringClass()->IsInitialized())) {
783 // We have code for a non-static or initialized method, just use the code.
784 } else if (portable_code == nullptr && orig->IsNative() &&
785 (!orig->IsStatic() || orig->GetDeclaringClass()->IsInitialized())) {
786 // Non-static or initialized native method missing compiled code, use generic JNI version.
787 // TODO: generic JNI support for LLVM.
788 portable_code = GetOatAddress(portable_resolution_trampoline_offset_);
789 } else if (portable_code == nullptr && !orig->IsNative()) {
790 // We don't have code at all for a non-native method, use the interpreter.
791 portable_code = GetOatAddress(portable_to_interpreter_bridge_offset_);
792 portable_is_interpreted = true;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800793 } else {
Sebastien Hertze1d07812014-05-21 15:44:09 +0200794 CHECK(!orig->GetDeclaringClass()->IsInitialized());
795 // We have code for a static method, but need to go through the resolution stub for class
796 // initialization.
797 portable_code = GetOatAddress(portable_resolution_trampoline_offset_);
Ian Rogers848871b2013-08-05 10:56:33 -0700798 }
Sebastien Hertze1d07812014-05-21 15:44:09 +0200799 copy->SetEntryPointFromPortableCompiledCode<kVerifyNone>(portable_code);
Ian Rogers63bc11e2014-09-18 08:56:45 -0700800#endif
Sebastien Hertze1d07812014-05-21 15:44:09 +0200801 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -0700802 if (orig->IsNative()) {
803 // The native method's pointer is set to a stub to lookup via dlsym.
804 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartier4e305412014-02-19 10:54:44 -0800805 copy->SetNativeMethod<kVerifyNone>(GetOatAddress(jni_dlsym_lookup_offset_));
Ian Rogers848871b2013-08-05 10:56:33 -0700806 } else {
807 // Normal (non-abstract non-native) methods have various tables to relocate.
Ian Rogers848871b2013-08-05 10:56:33 -0700808 uint32_t native_gc_map_offset = orig->GetOatNativeGcMapOffset();
809 const byte* native_gc_map = GetOatAddress(native_gc_map_offset);
Mathieu Chartier4e305412014-02-19 10:54:44 -0800810 copy->SetNativeGcMap<kVerifyNone>(reinterpret_cast<const uint8_t*>(native_gc_map));
Ian Rogers848871b2013-08-05 10:56:33 -0700811 }
Sebastien Hertze1d07812014-05-21 15:44:09 +0200812
813 // Interpreter entrypoint:
814 // Set the interpreter entrypoint depending on whether there is compiled code or not.
815 uint32_t interpreter_code = (quick_is_interpreted && portable_is_interpreted)
816 ? interpreter_to_interpreter_bridge_offset_
817 : interpreter_to_compiled_code_bridge_offset_;
818 copy->SetEntryPointFromInterpreter<kVerifyNone>(
819 reinterpret_cast<EntryPointFromInterpreter*>(
820 const_cast<byte*>(GetOatAddress(interpreter_code))));
Ian Rogers848871b2013-08-05 10:56:33 -0700821 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700822 }
823}
824
Alex Lighta59dd802014-07-02 16:28:08 -0700825static OatHeader* GetOatHeaderFromElf(ElfFile* elf) {
826 Elf32_Shdr* data_sec = elf->FindSectionByName(".rodata");
827 if (data_sec == nullptr) {
828 return nullptr;
829 }
830 return reinterpret_cast<OatHeader*>(elf->Begin() + data_sec->sh_offset);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800831}
832
Alex Light53cb16b2014-06-12 11:26:29 -0700833void ImageWriter::PatchOatCodeAndMethods(File* elf_file) {
Alex Lighta59dd802014-07-02 16:28:08 -0700834 std::string error_msg;
835 std::unique_ptr<ElfFile> elf(ElfFile::Open(elf_file, PROT_READ|PROT_WRITE,
836 MAP_SHARED, &error_msg));
837 if (elf.get() == nullptr) {
838 LOG(FATAL) << "Unable patch oat file: " << error_msg;
839 return;
Alex Light53cb16b2014-06-12 11:26:29 -0700840 }
Alex Lighta59dd802014-07-02 16:28:08 -0700841 if (!ElfPatcher::Patch(&compiler_driver_, elf.get(), oat_file_,
842 reinterpret_cast<uintptr_t>(oat_data_begin_),
843 GetImageAddressCallback, reinterpret_cast<void*>(this),
844 &error_msg)) {
845 LOG(FATAL) << "unable to patch oat file: " << error_msg;
846 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700847 }
Alex Lighta59dd802014-07-02 16:28:08 -0700848 OatHeader* oat_header = GetOatHeaderFromElf(elf.get());
849 CHECK(oat_header != nullptr);
850 CHECK(oat_header->IsValid());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700851
Brian Carlstrom7940e442013-07-12 13:46:57 -0700852 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Alex Lighta59dd802014-07-02 16:28:08 -0700853 image_header->SetOatChecksum(oat_header->GetChecksum());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700854}
855
856} // namespace art