blob: 9c9cdf270002ae83d7b597a5c8b97fd7d802e3fb [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,
74 const std::string& oat_location) {
75 CHECK(!image_filename.empty());
76
77 CHECK_NE(image_begin, 0U);
78 image_begin_ = reinterpret_cast<byte*>(image_begin);
79
80 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -070081
Ian Rogers700a4022014-05-19 16:49:03 -070082 std::unique_ptr<File> oat_file(OS::OpenFileReadWrite(oat_filename.c_str()));
Brian Carlstrom7940e442013-07-12 13:46:57 -070083 if (oat_file.get() == NULL) {
84 LOG(ERROR) << "Failed to open oat file " << oat_filename << " for " << oat_location;
85 return false;
86 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -070087 std::string error_msg;
Alex Lighta59dd802014-07-02 16:28:08 -070088 oat_file_ = OatFile::OpenReadable(oat_file.get(), oat_location, &error_msg);
Ian Rogers8d31bbd2013-10-13 10:44:14 -070089 if (oat_file_ == nullptr) {
90 LOG(ERROR) << "Failed to open writable oat file " << oat_filename << " for " << oat_location
91 << ": " << error_msg;
Brian Carlstromc50d8e12013-07-23 22:35:16 -070092 return false;
93 }
Ian Rogers8d31bbd2013-10-13 10:44:14 -070094 CHECK_EQ(class_linker->RegisterOatFile(oat_file_), oat_file_);
Brian Carlstrom7940e442013-07-12 13:46:57 -070095
Ian Rogers848871b2013-08-05 10:56:33 -070096 interpreter_to_interpreter_bridge_offset_ =
97 oat_file_->GetOatHeader().GetInterpreterToInterpreterBridgeOffset();
98 interpreter_to_compiled_code_bridge_offset_ =
99 oat_file_->GetOatHeader().GetInterpreterToCompiledCodeBridgeOffset();
100
101 jni_dlsym_lookup_offset_ = oat_file_->GetOatHeader().GetJniDlsymLookupOffset();
102
Jeff Hao88474b42013-10-23 16:24:40 -0700103 portable_imt_conflict_trampoline_offset_ =
104 oat_file_->GetOatHeader().GetPortableImtConflictTrampolineOffset();
Ian Rogers848871b2013-08-05 10:56:33 -0700105 portable_resolution_trampoline_offset_ =
106 oat_file_->GetOatHeader().GetPortableResolutionTrampolineOffset();
107 portable_to_interpreter_bridge_offset_ =
108 oat_file_->GetOatHeader().GetPortableToInterpreterBridgeOffset();
109
Andreas Gampe2da88232014-02-27 12:26:20 -0800110 quick_generic_jni_trampoline_offset_ =
111 oat_file_->GetOatHeader().GetQuickGenericJniTrampolineOffset();
Jeff Hao88474b42013-10-23 16:24:40 -0700112 quick_imt_conflict_trampoline_offset_ =
113 oat_file_->GetOatHeader().GetQuickImtConflictTrampolineOffset();
Ian Rogers848871b2013-08-05 10:56:33 -0700114 quick_resolution_trampoline_offset_ =
115 oat_file_->GetOatHeader().GetQuickResolutionTrampolineOffset();
116 quick_to_interpreter_bridge_offset_ =
117 oat_file_->GetOatHeader().GetQuickToInterpreterBridgeOffset();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700118 {
119 Thread::Current()->TransitionFromSuspendedToRunnable();
120 PruneNonImageClasses(); // Remove junk
121 ComputeLazyFieldsForImageClasses(); // Add useful information
122 ComputeEagerResolvedStrings();
123 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
124 }
125 gc::Heap* heap = Runtime::Current()->GetHeap();
126 heap->CollectGarbage(false); // Remove garbage.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700127
128 if (!AllocMemory()) {
129 return false;
130 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700131
132 if (kIsDebugBuild) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700133 ScopedObjectAccess soa(Thread::Current());
134 CheckNonImageClassesRemoved();
135 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700136
Brian Carlstrom7940e442013-07-12 13:46:57 -0700137 Thread::Current()->TransitionFromSuspendedToRunnable();
138 size_t oat_loaded_size = 0;
139 size_t oat_data_offset = 0;
140 ElfWriter::GetOatElfInformation(oat_file.get(), oat_loaded_size, oat_data_offset);
141 CalculateNewObjectOffsets(oat_loaded_size, oat_data_offset);
142 CopyAndFixupObjects();
Alex Light53cb16b2014-06-12 11:26:29 -0700143
144 PatchOatCodeAndMethods(oat_file.get());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700145 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
146
Ian Rogers700a4022014-05-19 16:49:03 -0700147 std::unique_ptr<File> image_file(OS::CreateEmptyFile(image_filename.c_str()));
Mathieu Chartier31e89252013-08-28 11:29:12 -0700148 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700149 if (image_file.get() == NULL) {
150 LOG(ERROR) << "Failed to open image file " << image_filename;
151 return false;
152 }
153 if (fchmod(image_file->Fd(), 0644) != 0) {
154 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
155 return EXIT_FAILURE;
156 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700157
158 // Write out the image.
159 CHECK_EQ(image_end_, image_header->GetImageSize());
160 if (!image_file->WriteFully(image_->Begin(), image_end_)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700161 PLOG(ERROR) << "Failed to write image file " << image_filename;
162 return false;
163 }
Mathieu Chartier31e89252013-08-28 11:29:12 -0700164
165 // Write out the image bitmap at the page aligned start of the image end.
166 CHECK_ALIGNED(image_header->GetImageBitmapOffset(), kPageSize);
167 if (!image_file->Write(reinterpret_cast<char*>(image_bitmap_->Begin()),
168 image_header->GetImageBitmapSize(),
169 image_header->GetImageBitmapOffset())) {
170 PLOG(ERROR) << "Failed to write image file " << image_filename;
171 return false;
172 }
173
Brian Carlstrom7940e442013-07-12 13:46:57 -0700174 return true;
175}
176
Mathieu Chartier590fee92013-09-13 13:46:47 -0700177void ImageWriter::SetImageOffset(mirror::Object* object, size_t offset) {
178 DCHECK(object != nullptr);
179 DCHECK_NE(offset, 0U);
180 DCHECK(!IsImageOffsetAssigned(object));
181 mirror::Object* obj = reinterpret_cast<mirror::Object*>(image_->Begin() + offset);
182 DCHECK_ALIGNED(obj, kObjectAlignment);
183 image_bitmap_->Set(obj);
184 // Before we stomp over the lock word, save the hash code for later.
185 Monitor::Deflate(Thread::Current(), object);;
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700186 LockWord lw(object->GetLockWord(false));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700187 switch (lw.GetState()) {
188 case LockWord::kFatLocked: {
189 LOG(FATAL) << "Fat locked object " << obj << " found during object copy";
190 break;
191 }
192 case LockWord::kThinLocked: {
193 LOG(FATAL) << "Thin locked object " << obj << " found during object copy";
194 break;
195 }
196 case LockWord::kUnlocked:
197 // No hash, don't need to save it.
198 break;
199 case LockWord::kHashCode:
200 saved_hashes_.push_back(std::make_pair(obj, lw.GetHashCode()));
201 break;
202 default:
203 LOG(FATAL) << "Unreachable.";
204 break;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700205 }
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700206 object->SetLockWord(LockWord::FromForwardingAddress(offset), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700207 DCHECK(IsImageOffsetAssigned(object));
208}
209
210void ImageWriter::AssignImageOffset(mirror::Object* object) {
211 DCHECK(object != nullptr);
212 SetImageOffset(object, image_end_);
213 image_end_ += RoundUp(object->SizeOf(), 8); // 64-bit alignment
214 DCHECK_LT(image_end_, image_->Size());
215}
216
Ian Rogersef7d42f2014-01-06 12:55:46 -0800217bool ImageWriter::IsImageOffsetAssigned(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700218 DCHECK(object != nullptr);
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700219 return object->GetLockWord(false).GetState() == LockWord::kForwardingAddress;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700220}
221
Ian Rogersef7d42f2014-01-06 12:55:46 -0800222size_t ImageWriter::GetImageOffset(mirror::Object* object) const {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700223 DCHECK(object != nullptr);
224 DCHECK(IsImageOffsetAssigned(object));
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700225 LockWord lock_word = object->GetLockWord(false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700226 size_t offset = lock_word.ForwardingAddress();
227 DCHECK_LT(offset, image_end_);
228 return offset;
Mathieu Chartier31e89252013-08-28 11:29:12 -0700229}
230
Brian Carlstrom7940e442013-07-12 13:46:57 -0700231bool ImageWriter::AllocMemory() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700232 size_t length = RoundUp(Runtime::Current()->GetHeap()->GetTotalMemory(), kPageSize);
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700233 std::string error_msg;
Mathieu Chartier590fee92013-09-13 13:46:47 -0700234 image_.reset(MemMap::MapAnonymous("image writer image", NULL, length, PROT_READ | PROT_WRITE,
Ian Rogers3cd86d62014-08-14 08:53:12 -0700235 false, &error_msg));
Ian Rogers8d31bbd2013-10-13 10:44:14 -0700236 if (UNLIKELY(image_.get() == nullptr)) {
237 LOG(ERROR) << "Failed to allocate memory for image file generation: " << error_msg;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700238 return false;
239 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700240
241 // Create the image bitmap.
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700242 image_bitmap_.reset(gc::accounting::ContinuousSpaceBitmap::Create("image bitmap", image_->Begin(),
243 length));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700244 if (image_bitmap_.get() == nullptr) {
245 LOG(ERROR) << "Failed to allocate memory for image bitmap";
246 return false;
247 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700248 return true;
249}
250
251void ImageWriter::ComputeLazyFieldsForImageClasses() {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700252 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700253 class_linker->VisitClassesWithoutClassesLock(ComputeLazyFieldsForClassesVisitor, NULL);
254}
255
256bool ImageWriter::ComputeLazyFieldsForClassesVisitor(Class* c, void* /*arg*/) {
Mathieu Chartierf8322842014-05-16 10:59:25 -0700257 Thread* self = Thread::Current();
258 StackHandleScope<1> hs(self);
259 mirror::Class::ComputeName(hs.NewHandle(c));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700260 return true;
261}
262
263void ImageWriter::ComputeEagerResolvedStringsCallback(Object* obj, void* arg) {
264 if (!obj->GetClass()->IsStringClass()) {
265 return;
266 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700267 mirror::String* string = obj->AsString();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700268 const uint16_t* utf16_string = string->GetCharArray()->GetData() + string->GetOffset();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700269 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
270 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
271 size_t dex_cache_count = class_linker->GetDexCacheCount();
272 for (size_t i = 0; i < dex_cache_count; ++i) {
273 DexCache* dex_cache = class_linker->GetDexCache(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700274 const DexFile& dex_file = *dex_cache->GetDexFile();
Ian Rogers24c534d2013-11-14 00:15:00 -0800275 const DexFile::StringId* string_id;
276 if (UNLIKELY(string->GetLength() == 0)) {
277 string_id = dex_file.FindStringId("");
278 } else {
279 string_id = dex_file.FindStringId(utf16_string);
280 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700281 if (string_id != nullptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700282 // This string occurs in this dex file, assign the dex cache entry.
283 uint32_t string_idx = dex_file.GetIndexForStringId(*string_id);
284 if (dex_cache->GetResolvedString(string_idx) == NULL) {
285 dex_cache->SetResolvedString(string_idx, string);
286 }
287 }
288 }
289}
290
Mathieu Chartier590fee92013-09-13 13:46:47 -0700291void ImageWriter::ComputeEagerResolvedStrings() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
292 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
293 Runtime::Current()->GetHeap()->VisitObjects(ComputeEagerResolvedStringsCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700294}
295
Ian Rogersef7d42f2014-01-06 12:55:46 -0800296bool ImageWriter::IsImageClass(Class* klass) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700297 std::string temp;
298 return compiler_driver_.IsImageClass(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700299}
300
301struct NonImageClasses {
302 ImageWriter* image_writer;
303 std::set<std::string>* non_image_classes;
304};
305
306void ImageWriter::PruneNonImageClasses() {
307 if (compiler_driver_.GetImageClasses() == NULL) {
308 return;
309 }
310 Runtime* runtime = Runtime::Current();
311 ClassLinker* class_linker = runtime->GetClassLinker();
312
313 // Make a list of classes we would like to prune.
314 std::set<std::string> non_image_classes;
315 NonImageClasses context;
316 context.image_writer = this;
317 context.non_image_classes = &non_image_classes;
318 class_linker->VisitClasses(NonImageClassesVisitor, &context);
319
320 // Remove the undesired classes from the class roots.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700321 for (const std::string& it : non_image_classes) {
322 class_linker->RemoveClass(it.c_str(), NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700323 }
324
325 // Clear references to removed classes from the DexCaches.
Brian Carlstromea46f952013-07-30 01:26:50 -0700326 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700327 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
328 size_t dex_cache_count = class_linker->GetDexCacheCount();
329 for (size_t idx = 0; idx < dex_cache_count; ++idx) {
330 DexCache* dex_cache = class_linker->GetDexCache(idx);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700331 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
332 Class* klass = dex_cache->GetResolvedType(i);
333 if (klass != NULL && !IsImageClass(klass)) {
334 dex_cache->SetResolvedType(i, NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700335 }
336 }
337 for (size_t i = 0; i < dex_cache->NumResolvedMethods(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700338 ArtMethod* method = dex_cache->GetResolvedMethod(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700339 if (method != NULL && !IsImageClass(method->GetDeclaringClass())) {
340 dex_cache->SetResolvedMethod(i, resolution_method);
341 }
342 }
343 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700344 ArtField* field = dex_cache->GetResolvedField(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700345 if (field != NULL && !IsImageClass(field->GetDeclaringClass())) {
346 dex_cache->SetResolvedField(i, NULL);
347 }
348 }
349 }
350}
351
352bool ImageWriter::NonImageClassesVisitor(Class* klass, void* arg) {
353 NonImageClasses* context = reinterpret_cast<NonImageClasses*>(arg);
354 if (!context->image_writer->IsImageClass(klass)) {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700355 std::string temp;
356 context->non_image_classes->insert(klass->GetDescriptor(&temp));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700357 }
358 return true;
359}
360
361void ImageWriter::CheckNonImageClassesRemoved()
362 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700363 if (compiler_driver_.GetImageClasses() != nullptr) {
364 gc::Heap* heap = Runtime::Current()->GetHeap();
365 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
366 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700367 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700368}
369
370void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
371 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700372 if (obj->IsClass()) {
373 Class* klass = obj->AsClass();
374 if (!image_writer->IsImageClass(klass)) {
375 image_writer->DumpImageClasses();
Ian Rogers1ff3c982014-08-12 02:30:58 -0700376 std::string temp;
377 CHECK(image_writer->IsImageClass(klass)) << klass->GetDescriptor(&temp)
Mathieu Chartier590fee92013-09-13 13:46:47 -0700378 << " " << PrettyDescriptor(klass);
379 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700380 }
381}
382
383void ImageWriter::DumpImageClasses() {
Ian Rogers1ff3c982014-08-12 02:30:58 -0700384 const std::set<std::string>* image_classes = compiler_driver_.GetImageClasses();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700385 CHECK(image_classes != NULL);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700386 for (const std::string& image_class : *image_classes) {
387 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700388 }
389}
390
Mathieu Chartier590fee92013-09-13 13:46:47 -0700391void ImageWriter::CalculateObjectOffsets(Object* obj) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700392 DCHECK(obj != NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700393 // if it is a string, we want to intern it if its not interned.
394 if (obj->GetClass()->IsStringClass()) {
395 // we must be an interned string that was forward referenced and already assigned
Mathieu Chartier590fee92013-09-13 13:46:47 -0700396 if (IsImageOffsetAssigned(obj)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700397 DCHECK_EQ(obj, obj->AsString()->Intern());
398 return;
399 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700400 mirror::String* const interned = obj->AsString()->Intern();
401 if (obj != interned) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700402 if (!IsImageOffsetAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700403 // interned obj is after us, allocate its location early
Mathieu Chartier590fee92013-09-13 13:46:47 -0700404 AssignImageOffset(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700405 }
406 // point those looking for this object to the interned version.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700407 SetImageOffset(obj, GetImageOffset(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700408 return;
409 }
410 // else (obj == interned), nothing to do but fall through to the normal case
411 }
412
Mathieu Chartier590fee92013-09-13 13:46:47 -0700413 AssignImageOffset(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700414}
415
416ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
417 Runtime* runtime = Runtime::Current();
418 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700419 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700420 StackHandleScope<3> hs(self);
421 Handle<Class> object_array_class(hs.NewHandle(
422 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700423
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700424 // build an Object[] of all the DexCaches used in the source_space_.
425 // Since we can't hold the dex lock when allocating the dex_caches
426 // ObjectArray, we lock the dex lock twice, first to get the number
427 // of dex caches first and then lock it again to copy the dex
428 // caches. We check that the number of dex caches does not change.
429 size_t dex_cache_count;
430 {
431 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
432 dex_cache_count = class_linker->GetDexCacheCount();
433 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700434 Handle<ObjectArray<Object>> dex_caches(
435 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(),
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700436 dex_cache_count)));
437 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
438 {
439 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
440 CHECK_EQ(dex_cache_count, class_linker->GetDexCacheCount())
441 << "The number of dex caches changed.";
442 for (size_t i = 0; i < dex_cache_count; ++i) {
443 dex_caches->Set<false>(i, class_linker->GetDexCache(i));
444 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700445 }
446
447 // build an Object[] of the roots needed to restore the runtime
Ian Rogers700a4022014-05-19 16:49:03 -0700448 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700449 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100450 image_roots->Set<false>(ImageHeader::kResolutionMethod, runtime->GetResolutionMethod());
451 image_roots->Set<false>(ImageHeader::kImtConflictMethod, runtime->GetImtConflictMethod());
452 image_roots->Set<false>(ImageHeader::kDefaultImt, runtime->GetDefaultImt());
453 image_roots->Set<false>(ImageHeader::kCalleeSaveMethod,
454 runtime->GetCalleeSaveMethod(Runtime::kSaveAll));
455 image_roots->Set<false>(ImageHeader::kRefsOnlySaveMethod,
456 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly));
457 image_roots->Set<false>(ImageHeader::kRefsAndArgsSaveMethod,
458 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700459 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100460 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700461 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
462 CHECK(image_roots->Get(i) != NULL);
463 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700464 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700465}
466
Mathieu Chartier590fee92013-09-13 13:46:47 -0700467// Walk instance fields of the given Class. Separate function to allow recursion on the super
468// class.
469void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
470 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700471 StackHandleScope<1> hs(Thread::Current());
472 Handle<mirror::Class> h_class(hs.NewHandle(klass));
473 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700474 if (super != nullptr) {
475 WalkInstanceFields(obj, super);
476 }
477 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700478 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700479 for (size_t i = 0; i < num_reference_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700480 mirror::ArtField* field = h_class->GetInstanceField(i);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700481 MemberOffset field_offset = field->GetOffset();
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700482 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700483 if (value != nullptr) {
484 WalkFieldsInOrder(value);
485 }
486 }
487}
488
489// For an unvisited object, visit it then all its children found via fields.
490void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
491 if (!IsImageOffsetAssigned(obj)) {
492 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700493 StackHandleScope<2> hs(Thread::Current());
494 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
495 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700496 // visit the object itself.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700497 CalculateObjectOffsets(h_obj.Get());
498 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700499 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700500 if (h_obj->IsClass()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700501 size_t num_static_fields = klass->NumReferenceStaticFields();
502 for (size_t i = 0; i < num_static_fields; ++i) {
503 mirror::ArtField* field = klass->GetStaticField(i);
504 MemberOffset field_offset = field->GetOffset();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700505 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700506 if (value != nullptr) {
507 WalkFieldsInOrder(value);
508 }
509 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700510 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700511 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700512 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700513 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700514 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700515 mirror::Object* value = obj_array->Get(i);
516 if (value != nullptr) {
517 WalkFieldsInOrder(value);
518 }
519 }
520 }
521 }
522}
523
524void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
525 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
526 DCHECK(writer != nullptr);
527 writer->WalkFieldsInOrder(obj);
528}
529
Brian Carlstrom7940e442013-07-12 13:46:57 -0700530void ImageWriter::CalculateNewObjectOffsets(size_t oat_loaded_size, size_t oat_data_offset) {
531 CHECK_NE(0U, oat_loaded_size);
532 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700533 StackHandleScope<1> hs(self);
534 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(CreateImageRoots()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700535
536 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700537 DCHECK_EQ(0U, image_end_);
538
Mathieu Chartier31e89252013-08-28 11:29:12 -0700539 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -0700540 // know where image_roots is going to end up
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700541 image_end_ += RoundUp(sizeof(ImageHeader), 8); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -0700542
543 {
544 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700545 // TODO: Image spaces only?
Brian Carlstrom7940e442013-07-12 13:46:57 -0700546 const char* old = self->StartAssertNoThreadSuspension("ImageWriter");
Mathieu Chartier590fee92013-09-13 13:46:47 -0700547 DCHECK_LT(image_end_, image_->Size());
548 // Clear any pre-existing monitors which may have been in the monitor words.
549 heap->VisitObjects(WalkFieldsCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700550 self->EndAssertNoThreadSuspension(old);
551 }
552
553 const byte* oat_file_begin = image_begin_ + RoundUp(image_end_, kPageSize);
554 const byte* oat_file_end = oat_file_begin + oat_loaded_size;
555 oat_data_begin_ = oat_file_begin + oat_data_offset;
556 const byte* oat_data_end = oat_data_begin_ + oat_file_->Size();
557
Mathieu Chartier31e89252013-08-28 11:29:12 -0700558 // Return to write header at start of image with future location of image_roots. At this point,
559 // image_end_ is the size of the image (excluding bitmaps).
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700560 const size_t heap_bytes_per_bitmap_byte = kBitsPerByte * kObjectAlignment;
Mathieu Chartier12aeccd2013-11-13 15:52:06 -0800561 const size_t bitmap_bytes = RoundUp(image_end_, heap_bytes_per_bitmap_byte) /
562 heap_bytes_per_bitmap_byte;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800563 ImageHeader image_header(PointerToLowMemUInt32(image_begin_),
Mathieu Chartier31e89252013-08-28 11:29:12 -0700564 static_cast<uint32_t>(image_end_),
565 RoundUp(image_end_, kPageSize),
Mathieu Chartier12aeccd2013-11-13 15:52:06 -0800566 RoundUp(bitmap_bytes, kPageSize),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700567 PointerToLowMemUInt32(GetImageAddress(image_roots.Get())),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700568 oat_file_->GetOatHeader().GetChecksum(),
Ian Rogersef7d42f2014-01-06 12:55:46 -0800569 PointerToLowMemUInt32(oat_file_begin),
570 PointerToLowMemUInt32(oat_data_begin_),
571 PointerToLowMemUInt32(oat_data_end),
572 PointerToLowMemUInt32(oat_file_end));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700573 memcpy(image_->Begin(), &image_header, sizeof(image_header));
574
575 // Note that image_end_ is left at end of used space
576}
577
578void ImageWriter::CopyAndFixupObjects()
579 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
580 Thread* self = Thread::Current();
581 const char* old_cause = self->StartAssertNoThreadSuspension("ImageWriter");
582 gc::Heap* heap = Runtime::Current()->GetHeap();
583 // TODO: heap validation can't handle this fix up pass
584 heap->DisableObjectValidation();
585 // TODO: Image spaces only?
586 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700587 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
588 // Fix up the object previously had hash codes.
589 for (const std::pair<mirror::Object*, uint32_t>& hash_pair : saved_hashes_) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700590 hash_pair.first->SetLockWord(LockWord::FromHashCode(hash_pair.second), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700591 }
592 saved_hashes_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700593 self->EndAssertNoThreadSuspension(old_cause);
594}
595
Mathieu Chartier590fee92013-09-13 13:46:47 -0700596void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700597 DCHECK(obj != nullptr);
598 DCHECK(arg != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700599 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700600 // see GetLocalAddress for similar computation
601 size_t offset = image_writer->GetImageOffset(obj);
602 byte* dst = image_writer->image_->Begin() + offset;
603 const byte* src = reinterpret_cast<const byte*>(obj);
604 size_t n = obj->SizeOf();
605 DCHECK_LT(offset + n, image_writer->image_->Size());
606 memcpy(dst, src, n);
607 Object* copy = reinterpret_cast<Object*>(dst);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700608 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
609 // word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700610 copy->SetLockWord(LockWord(), false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700611 image_writer->FixupObject(obj, copy);
612}
613
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700614class FixupVisitor {
615 public:
616 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
617 }
618
619 void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
620 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -0700621 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700622 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
623 // image.
624 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700625 offset, image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700626 }
627
628 // java.lang.ref.Reference visitor.
629 void operator()(mirror::Class* /*klass*/, mirror::Reference* ref) const
630 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
631 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
632 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700633 mirror::Reference::ReferentOffset(), image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700634 }
635
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700636 protected:
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700637 ImageWriter* const image_writer_;
638 mirror::Object* const copy_;
639};
640
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700641class FixupClassVisitor FINAL : public FixupVisitor {
642 public:
643 FixupClassVisitor(ImageWriter* image_writer, Object* copy) : FixupVisitor(image_writer, copy) {
644 }
645
646 void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
647 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
648 DCHECK(obj->IsClass());
649 FixupVisitor::operator()(obj, offset, false);
650
651 if (offset.Uint32Value() < mirror::Class::EmbeddedVTableOffset().Uint32Value()) {
652 return;
653 }
654 }
655
656 void operator()(mirror::Class* /*klass*/, mirror::Reference* ref) const
657 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
658 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
659 LOG(FATAL) << "Reference not expected here.";
660 }
661};
662
Ian Rogersef7d42f2014-01-06 12:55:46 -0800663void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700664 DCHECK(orig != nullptr);
665 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700666 if (kUseBakerOrBrooksReadBarrier) {
667 orig->AssertReadBarrierPointer();
668 if (kUseBrooksReadBarrier) {
669 // Note the address 'copy' isn't the same as the image address of 'orig'.
670 copy->SetReadBarrierPointer(GetImageAddress(orig));
671 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
672 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800673 }
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700674 if (orig->IsClass() && orig->AsClass()->ShouldHaveEmbeddedImtAndVTable()) {
675 FixupClassVisitor visitor(this, copy);
676 orig->VisitReferences<true /*visit class*/>(visitor, visitor);
677 } else {
678 FixupVisitor visitor(this, copy);
679 orig->VisitReferences<true /*visit class*/>(visitor, visitor);
680 }
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700681 if (orig->IsArtMethod<kVerifyNone>()) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800682 FixupMethod(orig->AsArtMethod<kVerifyNone>(), down_cast<ArtMethod*>(copy));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700683 }
684}
685
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700686const byte* ImageWriter::GetQuickCode(mirror::ArtMethod* method, bool* quick_is_interpreted) {
687 DCHECK(!method->IsResolutionMethod() && !method->IsImtConflictMethod() &&
688 !method->IsAbstract()) << PrettyMethod(method);
689
690 // Use original code if it exists. Otherwise, set the code pointer to the resolution
691 // trampoline.
692
693 // Quick entrypoint:
694 const byte* quick_code = GetOatAddress(method->GetQuickOatCodeOffset());
695 *quick_is_interpreted = false;
696 if (quick_code != nullptr &&
697 (!method->IsStatic() || method->IsConstructor() || method->GetDeclaringClass()->IsInitialized())) {
698 // We have code for a non-static or initialized method, just use the code.
699 } else if (quick_code == nullptr && method->IsNative() &&
700 (!method->IsStatic() || method->GetDeclaringClass()->IsInitialized())) {
701 // Non-static or initialized native method missing compiled code, use generic JNI version.
702 quick_code = GetOatAddress(quick_generic_jni_trampoline_offset_);
703 } else if (quick_code == nullptr && !method->IsNative()) {
704 // We don't have code at all for a non-native method, use the interpreter.
705 quick_code = GetOatAddress(quick_to_interpreter_bridge_offset_);
706 *quick_is_interpreted = true;
707 } else {
708 CHECK(!method->GetDeclaringClass()->IsInitialized());
709 // We have code for a static method, but need to go through the resolution stub for class
710 // initialization.
711 quick_code = GetOatAddress(quick_resolution_trampoline_offset_);
712 }
713 return quick_code;
714}
715
716const byte* ImageWriter::GetQuickEntryPoint(mirror::ArtMethod* method) {
717 // Calculate the quick entry point following the same logic as FixupMethod() below.
718 // The resolution method has a special trampoline to call.
719 if (UNLIKELY(method == Runtime::Current()->GetResolutionMethod())) {
720 return GetOatAddress(quick_resolution_trampoline_offset_);
721 } else if (UNLIKELY(method == Runtime::Current()->GetImtConflictMethod())) {
722 return GetOatAddress(quick_imt_conflict_trampoline_offset_);
723 } else {
724 // We assume all methods have code. If they don't currently then we set them to the use the
725 // resolution trampoline. Abstract methods never have code and so we need to make sure their
726 // use results in an AbstractMethodError. We use the interpreter to achieve this.
727 if (UNLIKELY(method->IsAbstract())) {
728 return GetOatAddress(quick_to_interpreter_bridge_offset_);
729 } else {
730 bool quick_is_interpreted;
731 return GetQuickCode(method, &quick_is_interpreted);
732 }
733 }
734}
735
Ian Rogersef7d42f2014-01-06 12:55:46 -0800736void ImageWriter::FixupMethod(ArtMethod* orig, ArtMethod* copy) {
Ian Rogers848871b2013-08-05 10:56:33 -0700737 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
738 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -0700739
Ian Rogers848871b2013-08-05 10:56:33 -0700740 // The resolution method has a special trampoline to call.
741 if (UNLIKELY(orig == Runtime::Current()->GetResolutionMethod())) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800742 copy->SetEntryPointFromPortableCompiledCode<kVerifyNone>(GetOatAddress(portable_resolution_trampoline_offset_));
743 copy->SetEntryPointFromQuickCompiledCode<kVerifyNone>(GetOatAddress(quick_resolution_trampoline_offset_));
Jeff Hao88474b42013-10-23 16:24:40 -0700744 } else if (UNLIKELY(orig == Runtime::Current()->GetImtConflictMethod())) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800745 copy->SetEntryPointFromPortableCompiledCode<kVerifyNone>(GetOatAddress(portable_imt_conflict_trampoline_offset_));
746 copy->SetEntryPointFromQuickCompiledCode<kVerifyNone>(GetOatAddress(quick_imt_conflict_trampoline_offset_));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700747 } else {
Ian Rogers848871b2013-08-05 10:56:33 -0700748 // We assume all methods have code. If they don't currently then we set them to the use the
749 // resolution trampoline. Abstract methods never have code and so we need to make sure their
750 // use results in an AbstractMethodError. We use the interpreter to achieve this.
751 if (UNLIKELY(orig->IsAbstract())) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800752 copy->SetEntryPointFromPortableCompiledCode<kVerifyNone>(GetOatAddress(portable_to_interpreter_bridge_offset_));
753 copy->SetEntryPointFromQuickCompiledCode<kVerifyNone>(GetOatAddress(quick_to_interpreter_bridge_offset_));
754 copy->SetEntryPointFromInterpreter<kVerifyNone>(reinterpret_cast<EntryPointFromInterpreter*>
Ian Rogersef7d42f2014-01-06 12:55:46 -0800755 (const_cast<byte*>(GetOatAddress(interpreter_to_interpreter_bridge_offset_))));
Ian Rogers848871b2013-08-05 10:56:33 -0700756 } else {
Mingyao Yang98d1cc82014-05-15 17:02:16 -0700757 bool quick_is_interpreted;
758 const byte* quick_code = GetQuickCode(orig, &quick_is_interpreted);
Sebastien Hertze1d07812014-05-21 15:44:09 +0200759 copy->SetEntryPointFromQuickCompiledCode<kVerifyNone>(quick_code);
760
761 // Portable entrypoint:
Ian Rogersef7d42f2014-01-06 12:55:46 -0800762 const byte* portable_code = GetOatAddress(orig->GetPortableOatCodeOffset());
Sebastien Hertze1d07812014-05-21 15:44:09 +0200763 bool portable_is_interpreted = false;
764 if (portable_code != nullptr &&
765 (!orig->IsStatic() || orig->IsConstructor() || orig->GetDeclaringClass()->IsInitialized())) {
766 // We have code for a non-static or initialized method, just use the code.
767 } else if (portable_code == nullptr && orig->IsNative() &&
768 (!orig->IsStatic() || orig->GetDeclaringClass()->IsInitialized())) {
769 // Non-static or initialized native method missing compiled code, use generic JNI version.
770 // TODO: generic JNI support for LLVM.
771 portable_code = GetOatAddress(portable_resolution_trampoline_offset_);
772 } else if (portable_code == nullptr && !orig->IsNative()) {
773 // We don't have code at all for a non-native method, use the interpreter.
774 portable_code = GetOatAddress(portable_to_interpreter_bridge_offset_);
775 portable_is_interpreted = true;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800776 } else {
Sebastien Hertze1d07812014-05-21 15:44:09 +0200777 CHECK(!orig->GetDeclaringClass()->IsInitialized());
778 // We have code for a static method, but need to go through the resolution stub for class
779 // initialization.
780 portable_code = GetOatAddress(portable_resolution_trampoline_offset_);
Ian Rogers848871b2013-08-05 10:56:33 -0700781 }
Sebastien Hertze1d07812014-05-21 15:44:09 +0200782 copy->SetEntryPointFromPortableCompiledCode<kVerifyNone>(portable_code);
783
784 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -0700785 if (orig->IsNative()) {
786 // The native method's pointer is set to a stub to lookup via dlsym.
787 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartier4e305412014-02-19 10:54:44 -0800788 copy->SetNativeMethod<kVerifyNone>(GetOatAddress(jni_dlsym_lookup_offset_));
Ian Rogers848871b2013-08-05 10:56:33 -0700789 } else {
790 // Normal (non-abstract non-native) methods have various tables to relocate.
Ian Rogers848871b2013-08-05 10:56:33 -0700791 uint32_t native_gc_map_offset = orig->GetOatNativeGcMapOffset();
792 const byte* native_gc_map = GetOatAddress(native_gc_map_offset);
Mathieu Chartier4e305412014-02-19 10:54:44 -0800793 copy->SetNativeGcMap<kVerifyNone>(reinterpret_cast<const uint8_t*>(native_gc_map));
Ian Rogers848871b2013-08-05 10:56:33 -0700794 }
Sebastien Hertze1d07812014-05-21 15:44:09 +0200795
796 // Interpreter entrypoint:
797 // Set the interpreter entrypoint depending on whether there is compiled code or not.
798 uint32_t interpreter_code = (quick_is_interpreted && portable_is_interpreted)
799 ? interpreter_to_interpreter_bridge_offset_
800 : interpreter_to_compiled_code_bridge_offset_;
801 copy->SetEntryPointFromInterpreter<kVerifyNone>(
802 reinterpret_cast<EntryPointFromInterpreter*>(
803 const_cast<byte*>(GetOatAddress(interpreter_code))));
Ian Rogers848871b2013-08-05 10:56:33 -0700804 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700805 }
806}
807
Alex Lighta59dd802014-07-02 16:28:08 -0700808static OatHeader* GetOatHeaderFromElf(ElfFile* elf) {
809 Elf32_Shdr* data_sec = elf->FindSectionByName(".rodata");
810 if (data_sec == nullptr) {
811 return nullptr;
812 }
813 return reinterpret_cast<OatHeader*>(elf->Begin() + data_sec->sh_offset);
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800814}
815
Alex Light53cb16b2014-06-12 11:26:29 -0700816void ImageWriter::PatchOatCodeAndMethods(File* elf_file) {
Alex Lighta59dd802014-07-02 16:28:08 -0700817 std::string error_msg;
818 std::unique_ptr<ElfFile> elf(ElfFile::Open(elf_file, PROT_READ|PROT_WRITE,
819 MAP_SHARED, &error_msg));
820 if (elf.get() == nullptr) {
821 LOG(FATAL) << "Unable patch oat file: " << error_msg;
822 return;
Alex Light53cb16b2014-06-12 11:26:29 -0700823 }
Alex Lighta59dd802014-07-02 16:28:08 -0700824 if (!ElfPatcher::Patch(&compiler_driver_, elf.get(), oat_file_,
825 reinterpret_cast<uintptr_t>(oat_data_begin_),
826 GetImageAddressCallback, reinterpret_cast<void*>(this),
827 &error_msg)) {
828 LOG(FATAL) << "unable to patch oat file: " << error_msg;
829 return;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700830 }
Alex Lighta59dd802014-07-02 16:28:08 -0700831 OatHeader* oat_header = GetOatHeaderFromElf(elf.get());
832 CHECK(oat_header != nullptr);
833 CHECK(oat_header->IsValid());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700834
Brian Carlstrom7940e442013-07-12 13:46:57 -0700835 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
Alex Lighta59dd802014-07-02 16:28:08 -0700836 image_header->SetOatChecksum(oat_header->GetChecksum());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700837}
838
839} // namespace art