blob: acfa607f3900dd8405278dadb056f4e8dd5f25e3 [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "image_writer.h"
18
19#include <sys/stat.h>
20
Ian Rogers700a4022014-05-19 16:49:03 -070021#include <memory>
Brian Carlstrom7940e442013-07-12 13:46:57 -070022#include <vector>
23
24#include "base/logging.h"
25#include "base/unix_file/fd_file.h"
26#include "class_linker.h"
27#include "compiled_method.h"
28#include "dex_file-inl.h"
29#include "driver/compiler_driver.h"
Alex Light53cb16b2014-06-12 11:26:29 -070030#include "elf_file.h"
31#include "elf_utils.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070032#include "elf_writer.h"
33#include "gc/accounting/card_table-inl.h"
34#include "gc/accounting/heap_bitmap.h"
Mathieu Chartier31e89252013-08-28 11:29:12 -070035#include "gc/accounting/space_bitmap-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070036#include "gc/heap.h"
37#include "gc/space/large_object_space.h"
38#include "gc/space/space-inl.h"
39#include "globals.h"
40#include "image.h"
41#include "intern_table.h"
Mathieu Chartierad2541a2013-10-25 10:05:23 -070042#include "lock_word.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070043#include "mirror/art_field-inl.h"
44#include "mirror/art_method-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070045#include "mirror/array-inl.h"
46#include "mirror/class-inl.h"
47#include "mirror/class_loader.h"
48#include "mirror/dex_cache-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070049#include "mirror/object-inl.h"
50#include "mirror/object_array-inl.h"
Ian Rogersb0fa5dc2014-04-28 16:47:08 -070051#include "mirror/string-inl.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070052#include "oat.h"
53#include "oat_file.h"
54#include "object_utils.h"
55#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;
88 oat_file_ = OatFile::OpenWritable(oat_file.get(), oat_location, &error_msg);
89 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 Rogersef7d42f2014-01-06 12:55:46 -0800235 true, &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) {
Mathieu Chartierf8322842014-05-16 10:59:25 -0700297 return compiler_driver_.IsImageClass(klass->GetDescriptor().c_str());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700298}
299
300struct NonImageClasses {
301 ImageWriter* image_writer;
302 std::set<std::string>* non_image_classes;
303};
304
305void ImageWriter::PruneNonImageClasses() {
306 if (compiler_driver_.GetImageClasses() == NULL) {
307 return;
308 }
309 Runtime* runtime = Runtime::Current();
310 ClassLinker* class_linker = runtime->GetClassLinker();
311
312 // Make a list of classes we would like to prune.
313 std::set<std::string> non_image_classes;
314 NonImageClasses context;
315 context.image_writer = this;
316 context.non_image_classes = &non_image_classes;
317 class_linker->VisitClasses(NonImageClassesVisitor, &context);
318
319 // Remove the undesired classes from the class roots.
Mathieu Chartier02e25112013-08-14 16:14:24 -0700320 for (const std::string& it : non_image_classes) {
321 class_linker->RemoveClass(it.c_str(), NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700322 }
323
324 // Clear references to removed classes from the DexCaches.
Brian Carlstromea46f952013-07-30 01:26:50 -0700325 ArtMethod* resolution_method = runtime->GetResolutionMethod();
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700326 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
327 size_t dex_cache_count = class_linker->GetDexCacheCount();
328 for (size_t idx = 0; idx < dex_cache_count; ++idx) {
329 DexCache* dex_cache = class_linker->GetDexCache(idx);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700330 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
331 Class* klass = dex_cache->GetResolvedType(i);
332 if (klass != NULL && !IsImageClass(klass)) {
333 dex_cache->SetResolvedType(i, NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700334 }
335 }
336 for (size_t i = 0; i < dex_cache->NumResolvedMethods(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700337 ArtMethod* method = dex_cache->GetResolvedMethod(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700338 if (method != NULL && !IsImageClass(method->GetDeclaringClass())) {
339 dex_cache->SetResolvedMethod(i, resolution_method);
340 }
341 }
342 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
Brian Carlstromea46f952013-07-30 01:26:50 -0700343 ArtField* field = dex_cache->GetResolvedField(i);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700344 if (field != NULL && !IsImageClass(field->GetDeclaringClass())) {
345 dex_cache->SetResolvedField(i, NULL);
346 }
347 }
348 }
349}
350
351bool ImageWriter::NonImageClassesVisitor(Class* klass, void* arg) {
352 NonImageClasses* context = reinterpret_cast<NonImageClasses*>(arg);
353 if (!context->image_writer->IsImageClass(klass)) {
Mathieu Chartierf8322842014-05-16 10:59:25 -0700354 context->non_image_classes->insert(klass->GetDescriptor());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700355 }
356 return true;
357}
358
359void ImageWriter::CheckNonImageClassesRemoved()
360 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700361 if (compiler_driver_.GetImageClasses() != nullptr) {
362 gc::Heap* heap = Runtime::Current()->GetHeap();
363 ReaderMutexLock mu(Thread::Current(), *Locks::heap_bitmap_lock_);
364 heap->VisitObjects(CheckNonImageClassesRemovedCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700365 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700366}
367
368void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
369 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700370 if (obj->IsClass()) {
371 Class* klass = obj->AsClass();
372 if (!image_writer->IsImageClass(klass)) {
373 image_writer->DumpImageClasses();
Mathieu Chartierf8322842014-05-16 10:59:25 -0700374 CHECK(image_writer->IsImageClass(klass)) << klass->GetDescriptor()
Mathieu Chartier590fee92013-09-13 13:46:47 -0700375 << " " << PrettyDescriptor(klass);
376 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700377 }
378}
379
380void ImageWriter::DumpImageClasses() {
381 CompilerDriver::DescriptorSet* image_classes = compiler_driver_.GetImageClasses();
382 CHECK(image_classes != NULL);
Mathieu Chartier02e25112013-08-14 16:14:24 -0700383 for (const std::string& image_class : *image_classes) {
384 LOG(INFO) << " " << image_class;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700385 }
386}
387
Mathieu Chartier590fee92013-09-13 13:46:47 -0700388void ImageWriter::CalculateObjectOffsets(Object* obj) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700389 DCHECK(obj != NULL);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700390 // if it is a string, we want to intern it if its not interned.
391 if (obj->GetClass()->IsStringClass()) {
392 // we must be an interned string that was forward referenced and already assigned
Mathieu Chartier590fee92013-09-13 13:46:47 -0700393 if (IsImageOffsetAssigned(obj)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700394 DCHECK_EQ(obj, obj->AsString()->Intern());
395 return;
396 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700397 mirror::String* const interned = obj->AsString()->Intern();
398 if (obj != interned) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700399 if (!IsImageOffsetAssigned(interned)) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700400 // interned obj is after us, allocate its location early
Mathieu Chartier590fee92013-09-13 13:46:47 -0700401 AssignImageOffset(interned);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700402 }
403 // point those looking for this object to the interned version.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700404 SetImageOffset(obj, GetImageOffset(interned));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700405 return;
406 }
407 // else (obj == interned), nothing to do but fall through to the normal case
408 }
409
Mathieu Chartier590fee92013-09-13 13:46:47 -0700410 AssignImageOffset(obj);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700411}
412
413ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
414 Runtime* runtime = Runtime::Current();
415 ClassLinker* class_linker = runtime->GetClassLinker();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700416 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700417 StackHandleScope<3> hs(self);
418 Handle<Class> object_array_class(hs.NewHandle(
419 class_linker->FindSystemClass(self, "[Ljava/lang/Object;")));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700420
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700421 // build an Object[] of all the DexCaches used in the source_space_.
422 // Since we can't hold the dex lock when allocating the dex_caches
423 // ObjectArray, we lock the dex lock twice, first to get the number
424 // of dex caches first and then lock it again to copy the dex
425 // caches. We check that the number of dex caches does not change.
426 size_t dex_cache_count;
427 {
428 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
429 dex_cache_count = class_linker->GetDexCacheCount();
430 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700431 Handle<ObjectArray<Object>> dex_caches(
432 hs.NewHandle(ObjectArray<Object>::Alloc(self, object_array_class.Get(),
Hiroshi Yamauchie9e3e692014-06-24 14:31:37 -0700433 dex_cache_count)));
434 CHECK(dex_caches.Get() != nullptr) << "Failed to allocate a dex cache array.";
435 {
436 ReaderMutexLock mu(Thread::Current(), *class_linker->DexLock());
437 CHECK_EQ(dex_cache_count, class_linker->GetDexCacheCount())
438 << "The number of dex caches changed.";
439 for (size_t i = 0; i < dex_cache_count; ++i) {
440 dex_caches->Set<false>(i, class_linker->GetDexCache(i));
441 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700442 }
443
444 // build an Object[] of the roots needed to restore the runtime
Ian Rogers700a4022014-05-19 16:49:03 -0700445 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700446 ObjectArray<Object>::Alloc(self, object_array_class.Get(), ImageHeader::kImageRootsMax)));
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100447 image_roots->Set<false>(ImageHeader::kResolutionMethod, runtime->GetResolutionMethod());
448 image_roots->Set<false>(ImageHeader::kImtConflictMethod, runtime->GetImtConflictMethod());
449 image_roots->Set<false>(ImageHeader::kDefaultImt, runtime->GetDefaultImt());
450 image_roots->Set<false>(ImageHeader::kCalleeSaveMethod,
451 runtime->GetCalleeSaveMethod(Runtime::kSaveAll));
452 image_roots->Set<false>(ImageHeader::kRefsOnlySaveMethod,
453 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly));
454 image_roots->Set<false>(ImageHeader::kRefsAndArgsSaveMethod,
455 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs));
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700456 image_roots->Set<false>(ImageHeader::kDexCaches, dex_caches.Get());
Sebastien Hertzd2fe10a2014-01-15 10:20:56 +0100457 image_roots->Set<false>(ImageHeader::kClassRoots, class_linker->GetClassRoots());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700458 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
459 CHECK(image_roots->Get(i) != NULL);
460 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700461 return image_roots.Get();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700462}
463
Mathieu Chartier590fee92013-09-13 13:46:47 -0700464// Walk instance fields of the given Class. Separate function to allow recursion on the super
465// class.
466void ImageWriter::WalkInstanceFields(mirror::Object* obj, mirror::Class* klass) {
467 // Visit fields of parent classes first.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700468 StackHandleScope<1> hs(Thread::Current());
469 Handle<mirror::Class> h_class(hs.NewHandle(klass));
470 mirror::Class* super = h_class->GetSuperClass();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700471 if (super != nullptr) {
472 WalkInstanceFields(obj, super);
473 }
474 //
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700475 size_t num_reference_fields = h_class->NumReferenceInstanceFields();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700476 for (size_t i = 0; i < num_reference_fields; ++i) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700477 mirror::ArtField* field = h_class->GetInstanceField(i);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700478 MemberOffset field_offset = field->GetOffset();
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700479 mirror::Object* value = obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700480 if (value != nullptr) {
481 WalkFieldsInOrder(value);
482 }
483 }
484}
485
486// For an unvisited object, visit it then all its children found via fields.
487void ImageWriter::WalkFieldsInOrder(mirror::Object* obj) {
488 if (!IsImageOffsetAssigned(obj)) {
489 // Walk instance fields of all objects
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700490 StackHandleScope<2> hs(Thread::Current());
491 Handle<mirror::Object> h_obj(hs.NewHandle(obj));
492 Handle<mirror::Class> klass(hs.NewHandle(obj->GetClass()));
Mathieu Chartier590fee92013-09-13 13:46:47 -0700493 // visit the object itself.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700494 CalculateObjectOffsets(h_obj.Get());
495 WalkInstanceFields(h_obj.Get(), klass.Get());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700496 // Walk static fields of a Class.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700497 if (h_obj->IsClass()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700498 size_t num_static_fields = klass->NumReferenceStaticFields();
499 for (size_t i = 0; i < num_static_fields; ++i) {
500 mirror::ArtField* field = klass->GetStaticField(i);
501 MemberOffset field_offset = field->GetOffset();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700502 mirror::Object* value = h_obj->GetFieldObject<mirror::Object>(field_offset);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700503 if (value != nullptr) {
504 WalkFieldsInOrder(value);
505 }
506 }
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700507 } else if (h_obj->IsObjectArray()) {
Mathieu Chartier590fee92013-09-13 13:46:47 -0700508 // Walk elements of an object array.
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700509 int32_t length = h_obj->AsObjectArray<mirror::Object>()->GetLength();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700510 for (int32_t i = 0; i < length; i++) {
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700511 mirror::ObjectArray<mirror::Object>* obj_array = h_obj->AsObjectArray<mirror::Object>();
Mathieu Chartier590fee92013-09-13 13:46:47 -0700512 mirror::Object* value = obj_array->Get(i);
513 if (value != nullptr) {
514 WalkFieldsInOrder(value);
515 }
516 }
517 }
518 }
519}
520
521void ImageWriter::WalkFieldsCallback(mirror::Object* obj, void* arg) {
522 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
523 DCHECK(writer != nullptr);
524 writer->WalkFieldsInOrder(obj);
525}
526
Brian Carlstrom7940e442013-07-12 13:46:57 -0700527void ImageWriter::CalculateNewObjectOffsets(size_t oat_loaded_size, size_t oat_data_offset) {
528 CHECK_NE(0U, oat_loaded_size);
529 Thread* self = Thread::Current();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700530 StackHandleScope<1> hs(self);
531 Handle<ObjectArray<Object>> image_roots(hs.NewHandle(CreateImageRoots()));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700532
533 gc::Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700534 DCHECK_EQ(0U, image_end_);
535
Mathieu Chartier31e89252013-08-28 11:29:12 -0700536 // Leave space for the header, but do not write it yet, we need to
Brian Carlstrom7940e442013-07-12 13:46:57 -0700537 // know where image_roots is going to end up
Brian Carlstrom7934ac22013-07-26 10:54:15 -0700538 image_end_ += RoundUp(sizeof(ImageHeader), 8); // 64-bit-alignment
Brian Carlstrom7940e442013-07-12 13:46:57 -0700539
540 {
541 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700542 // TODO: Image spaces only?
Brian Carlstrom7940e442013-07-12 13:46:57 -0700543 const char* old = self->StartAssertNoThreadSuspension("ImageWriter");
Mathieu Chartier590fee92013-09-13 13:46:47 -0700544 DCHECK_LT(image_end_, image_->Size());
545 // Clear any pre-existing monitors which may have been in the monitor words.
546 heap->VisitObjects(WalkFieldsCallback, this);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700547 self->EndAssertNoThreadSuspension(old);
548 }
549
550 const byte* oat_file_begin = image_begin_ + RoundUp(image_end_, kPageSize);
551 const byte* oat_file_end = oat_file_begin + oat_loaded_size;
552 oat_data_begin_ = oat_file_begin + oat_data_offset;
553 const byte* oat_data_end = oat_data_begin_ + oat_file_->Size();
554
Mathieu Chartier31e89252013-08-28 11:29:12 -0700555 // Return to write header at start of image with future location of image_roots. At this point,
556 // image_end_ is the size of the image (excluding bitmaps).
Mathieu Chartiera8e8f9c2014-04-09 14:51:05 -0700557 const size_t heap_bytes_per_bitmap_byte = kBitsPerByte * kObjectAlignment;
Mathieu Chartier12aeccd2013-11-13 15:52:06 -0800558 const size_t bitmap_bytes = RoundUp(image_end_, heap_bytes_per_bitmap_byte) /
559 heap_bytes_per_bitmap_byte;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800560 ImageHeader image_header(PointerToLowMemUInt32(image_begin_),
Mathieu Chartier31e89252013-08-28 11:29:12 -0700561 static_cast<uint32_t>(image_end_),
562 RoundUp(image_end_, kPageSize),
Mathieu Chartier12aeccd2013-11-13 15:52:06 -0800563 RoundUp(bitmap_bytes, kPageSize),
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700564 PointerToLowMemUInt32(GetImageAddress(image_roots.Get())),
Brian Carlstrom7940e442013-07-12 13:46:57 -0700565 oat_file_->GetOatHeader().GetChecksum(),
Ian Rogersef7d42f2014-01-06 12:55:46 -0800566 PointerToLowMemUInt32(oat_file_begin),
567 PointerToLowMemUInt32(oat_data_begin_),
568 PointerToLowMemUInt32(oat_data_end),
569 PointerToLowMemUInt32(oat_file_end));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700570 memcpy(image_->Begin(), &image_header, sizeof(image_header));
571
572 // Note that image_end_ is left at end of used space
573}
574
575void ImageWriter::CopyAndFixupObjects()
576 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
577 Thread* self = Thread::Current();
578 const char* old_cause = self->StartAssertNoThreadSuspension("ImageWriter");
579 gc::Heap* heap = Runtime::Current()->GetHeap();
580 // TODO: heap validation can't handle this fix up pass
581 heap->DisableObjectValidation();
582 // TODO: Image spaces only?
583 WriterMutexLock mu(self, *Locks::heap_bitmap_lock_);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700584 heap->VisitObjects(CopyAndFixupObjectsCallback, this);
585 // Fix up the object previously had hash codes.
586 for (const std::pair<mirror::Object*, uint32_t>& hash_pair : saved_hashes_) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700587 hash_pair.first->SetLockWord(LockWord::FromHashCode(hash_pair.second), false);
Mathieu Chartier590fee92013-09-13 13:46:47 -0700588 }
589 saved_hashes_.clear();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700590 self->EndAssertNoThreadSuspension(old_cause);
591}
592
Mathieu Chartier590fee92013-09-13 13:46:47 -0700593void ImageWriter::CopyAndFixupObjectsCallback(Object* obj, void* arg) {
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700594 DCHECK(obj != nullptr);
595 DCHECK(arg != nullptr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700596 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700597 // see GetLocalAddress for similar computation
598 size_t offset = image_writer->GetImageOffset(obj);
599 byte* dst = image_writer->image_->Begin() + offset;
600 const byte* src = reinterpret_cast<const byte*>(obj);
601 size_t n = obj->SizeOf();
602 DCHECK_LT(offset + n, image_writer->image_->Size());
603 memcpy(dst, src, n);
604 Object* copy = reinterpret_cast<Object*>(dst);
Mathieu Chartierad2541a2013-10-25 10:05:23 -0700605 // Write in a hash code of objects which have inflated monitors or a hash code in their monitor
606 // word.
Mathieu Chartier4d7f61d2014-04-17 14:43:39 -0700607 copy->SetLockWord(LockWord(), false);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700608 image_writer->FixupObject(obj, copy);
609}
610
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700611class FixupVisitor {
612 public:
613 FixupVisitor(ImageWriter* image_writer, Object* copy) : image_writer_(image_writer), copy_(copy) {
614 }
615
616 void operator()(Object* obj, MemberOffset offset, bool /*is_static*/) const
617 EXCLUSIVE_LOCKS_REQUIRED(Locks::mutator_lock_, Locks::heap_bitmap_lock_) {
Hiroshi Yamauchi6e83c172014-05-01 21:25:41 -0700618 Object* ref = obj->GetFieldObject<Object, kVerifyNone>(offset);
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700619 // Use SetFieldObjectWithoutWriteBarrier to avoid card marking since we are writing to the
620 // image.
621 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700622 offset, image_writer_->GetImageAddress(ref));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700623 }
624
625 // java.lang.ref.Reference visitor.
626 void operator()(mirror::Class* /*klass*/, mirror::Reference* ref) const
627 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_)
628 EXCLUSIVE_LOCKS_REQUIRED(Locks::heap_bitmap_lock_) {
629 copy_->SetFieldObjectWithoutWriteBarrier<false, true, kVerifyNone>(
Ian Rogersb0fa5dc2014-04-28 16:47:08 -0700630 mirror::Reference::ReferentOffset(), image_writer_->GetImageAddress(ref->GetReferent()));
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700631 }
632
633 private:
634 ImageWriter* const image_writer_;
635 mirror::Object* const copy_;
636};
637
Ian Rogersef7d42f2014-01-06 12:55:46 -0800638void ImageWriter::FixupObject(Object* orig, Object* copy) {
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700639 DCHECK(orig != nullptr);
640 DCHECK(copy != nullptr);
Hiroshi Yamauchi624468c2014-03-31 15:14:47 -0700641 if (kUseBakerOrBrooksReadBarrier) {
642 orig->AssertReadBarrierPointer();
643 if (kUseBrooksReadBarrier) {
644 // Note the address 'copy' isn't the same as the image address of 'orig'.
645 copy->SetReadBarrierPointer(GetImageAddress(orig));
646 DCHECK_EQ(copy->GetReadBarrierPointer(), GetImageAddress(orig));
647 }
Hiroshi Yamauchi9d04a202014-01-31 13:35:49 -0800648 }
Mathieu Chartierb7ea3ac2014-03-24 16:54:46 -0700649 FixupVisitor visitor(this, copy);
650 orig->VisitReferences<true /*visit class*/>(visitor, visitor);
651 if (orig->IsArtMethod<kVerifyNone>()) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800652 FixupMethod(orig->AsArtMethod<kVerifyNone>(), down_cast<ArtMethod*>(copy));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700653 }
654}
655
Ian Rogersef7d42f2014-01-06 12:55:46 -0800656void ImageWriter::FixupMethod(ArtMethod* orig, ArtMethod* copy) {
Ian Rogers848871b2013-08-05 10:56:33 -0700657 // OatWriter replaces the code_ with an offset value. Here we re-adjust to a pointer relative to
658 // oat_begin_
Brian Carlstrom7940e442013-07-12 13:46:57 -0700659
Ian Rogers848871b2013-08-05 10:56:33 -0700660 // The resolution method has a special trampoline to call.
661 if (UNLIKELY(orig == Runtime::Current()->GetResolutionMethod())) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800662 copy->SetEntryPointFromPortableCompiledCode<kVerifyNone>(GetOatAddress(portable_resolution_trampoline_offset_));
663 copy->SetEntryPointFromQuickCompiledCode<kVerifyNone>(GetOatAddress(quick_resolution_trampoline_offset_));
Jeff Hao88474b42013-10-23 16:24:40 -0700664 } else if (UNLIKELY(orig == Runtime::Current()->GetImtConflictMethod())) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800665 copy->SetEntryPointFromPortableCompiledCode<kVerifyNone>(GetOatAddress(portable_imt_conflict_trampoline_offset_));
666 copy->SetEntryPointFromQuickCompiledCode<kVerifyNone>(GetOatAddress(quick_imt_conflict_trampoline_offset_));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700667 } else {
Ian Rogers848871b2013-08-05 10:56:33 -0700668 // We assume all methods have code. If they don't currently then we set them to the use the
669 // resolution trampoline. Abstract methods never have code and so we need to make sure their
670 // use results in an AbstractMethodError. We use the interpreter to achieve this.
671 if (UNLIKELY(orig->IsAbstract())) {
Mathieu Chartier4e305412014-02-19 10:54:44 -0800672 copy->SetEntryPointFromPortableCompiledCode<kVerifyNone>(GetOatAddress(portable_to_interpreter_bridge_offset_));
673 copy->SetEntryPointFromQuickCompiledCode<kVerifyNone>(GetOatAddress(quick_to_interpreter_bridge_offset_));
674 copy->SetEntryPointFromInterpreter<kVerifyNone>(reinterpret_cast<EntryPointFromInterpreter*>
Ian Rogersef7d42f2014-01-06 12:55:46 -0800675 (const_cast<byte*>(GetOatAddress(interpreter_to_interpreter_bridge_offset_))));
Ian Rogers848871b2013-08-05 10:56:33 -0700676 } else {
Ian Rogers848871b2013-08-05 10:56:33 -0700677 // Use original code if it exists. Otherwise, set the code pointer to the resolution
678 // trampoline.
Sebastien Hertze1d07812014-05-21 15:44:09 +0200679
680 // Quick entrypoint:
Ian Rogersef7d42f2014-01-06 12:55:46 -0800681 const byte* quick_code = GetOatAddress(orig->GetQuickOatCodeOffset());
Sebastien Hertze1d07812014-05-21 15:44:09 +0200682 bool quick_is_interpreted = false;
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800683 if (quick_code != nullptr &&
684 (!orig->IsStatic() || orig->IsConstructor() || orig->GetDeclaringClass()->IsInitialized())) {
685 // We have code for a non-static or initialized method, just use the code.
Ian Rogers1a570662014-03-12 01:02:21 -0700686 } else if (quick_code == nullptr && orig->IsNative() &&
687 (!orig->IsStatic() || orig->GetDeclaringClass()->IsInitialized())) {
688 // Non-static or initialized native method missing compiled code, use generic JNI version.
Sebastien Hertze1d07812014-05-21 15:44:09 +0200689 quick_code = GetOatAddress(quick_generic_jni_trampoline_offset_);
Brian Carlstrom2ec65202014-03-03 15:16:37 -0800690 } else if (quick_code == nullptr && !orig->IsNative()) {
691 // We don't have code at all for a non-native method, use the interpreter.
Sebastien Hertze1d07812014-05-21 15:44:09 +0200692 quick_code = GetOatAddress(quick_to_interpreter_bridge_offset_);
693 quick_is_interpreted = true;
Ian Rogers848871b2013-08-05 10:56:33 -0700694 } else {
Ian Rogers1a570662014-03-12 01:02:21 -0700695 CHECK(!orig->GetDeclaringClass()->IsInitialized());
696 // We have code for a static method, but need to go through the resolution stub for class
697 // initialization.
Sebastien Hertze1d07812014-05-21 15:44:09 +0200698 quick_code = GetOatAddress(quick_resolution_trampoline_offset_);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800699 }
Sebastien Hertze1d07812014-05-21 15:44:09 +0200700 copy->SetEntryPointFromQuickCompiledCode<kVerifyNone>(quick_code);
701
702 // Portable entrypoint:
Ian Rogersef7d42f2014-01-06 12:55:46 -0800703 const byte* portable_code = GetOatAddress(orig->GetPortableOatCodeOffset());
Sebastien Hertze1d07812014-05-21 15:44:09 +0200704 bool portable_is_interpreted = false;
705 if (portable_code != nullptr &&
706 (!orig->IsStatic() || orig->IsConstructor() || orig->GetDeclaringClass()->IsInitialized())) {
707 // We have code for a non-static or initialized method, just use the code.
708 } else if (portable_code == nullptr && orig->IsNative() &&
709 (!orig->IsStatic() || orig->GetDeclaringClass()->IsInitialized())) {
710 // Non-static or initialized native method missing compiled code, use generic JNI version.
711 // TODO: generic JNI support for LLVM.
712 portable_code = GetOatAddress(portable_resolution_trampoline_offset_);
713 } else if (portable_code == nullptr && !orig->IsNative()) {
714 // We don't have code at all for a non-native method, use the interpreter.
715 portable_code = GetOatAddress(portable_to_interpreter_bridge_offset_);
716 portable_is_interpreted = true;
Ian Rogersef7d42f2014-01-06 12:55:46 -0800717 } else {
Sebastien Hertze1d07812014-05-21 15:44:09 +0200718 CHECK(!orig->GetDeclaringClass()->IsInitialized());
719 // We have code for a static method, but need to go through the resolution stub for class
720 // initialization.
721 portable_code = GetOatAddress(portable_resolution_trampoline_offset_);
Ian Rogers848871b2013-08-05 10:56:33 -0700722 }
Sebastien Hertze1d07812014-05-21 15:44:09 +0200723 copy->SetEntryPointFromPortableCompiledCode<kVerifyNone>(portable_code);
724
725 // JNI entrypoint:
Ian Rogers848871b2013-08-05 10:56:33 -0700726 if (orig->IsNative()) {
727 // The native method's pointer is set to a stub to lookup via dlsym.
728 // Note this is not the code_ pointer, that is handled above.
Mathieu Chartier4e305412014-02-19 10:54:44 -0800729 copy->SetNativeMethod<kVerifyNone>(GetOatAddress(jni_dlsym_lookup_offset_));
Ian Rogers848871b2013-08-05 10:56:33 -0700730 } else {
731 // Normal (non-abstract non-native) methods have various tables to relocate.
Ian Rogers848871b2013-08-05 10:56:33 -0700732 uint32_t native_gc_map_offset = orig->GetOatNativeGcMapOffset();
733 const byte* native_gc_map = GetOatAddress(native_gc_map_offset);
Mathieu Chartier4e305412014-02-19 10:54:44 -0800734 copy->SetNativeGcMap<kVerifyNone>(reinterpret_cast<const uint8_t*>(native_gc_map));
Ian Rogers848871b2013-08-05 10:56:33 -0700735 }
Sebastien Hertze1d07812014-05-21 15:44:09 +0200736
737 // Interpreter entrypoint:
738 // Set the interpreter entrypoint depending on whether there is compiled code or not.
739 uint32_t interpreter_code = (quick_is_interpreted && portable_is_interpreted)
740 ? interpreter_to_interpreter_bridge_offset_
741 : interpreter_to_compiled_code_bridge_offset_;
742 copy->SetEntryPointFromInterpreter<kVerifyNone>(
743 reinterpret_cast<EntryPointFromInterpreter*>(
744 const_cast<byte*>(GetOatAddress(interpreter_code))));
Ian Rogers848871b2013-08-05 10:56:33 -0700745 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700746 }
747}
748
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800749static ArtMethod* GetTargetMethod(const CompilerDriver::CallPatchInformation* patch)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700750 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
751 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier0cd81352014-05-22 16:48:55 -0700752 StackHandleScope<1> hs(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700753 Handle<mirror::DexCache> dex_cache(
754 hs.NewHandle(class_linker->FindDexCache(*patch->GetTargetDexFile())));
Jeff Hao49161ce2014-03-12 11:05:25 -0700755 ArtMethod* method = class_linker->ResolveMethod(*patch->GetTargetDexFile(),
Brian Carlstromea46f952013-07-30 01:26:50 -0700756 patch->GetTargetMethodIdx(),
757 dex_cache,
Mathieu Chartier0cd81352014-05-22 16:48:55 -0700758 NullHandle<mirror::ClassLoader>(),
759 NullHandle<mirror::ArtMethod>(),
Brian Carlstromea46f952013-07-30 01:26:50 -0700760 patch->GetTargetInvokeType());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700761 CHECK(method != NULL)
Jeff Hao49161ce2014-03-12 11:05:25 -0700762 << patch->GetTargetDexFile()->GetLocation() << " " << patch->GetTargetMethodIdx();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700763 CHECK(!method->IsRuntimeMethod())
Jeff Hao49161ce2014-03-12 11:05:25 -0700764 << patch->GetTargetDexFile()->GetLocation() << " " << patch->GetTargetMethodIdx();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700765 CHECK(dex_cache->GetResolvedMethods()->Get(patch->GetTargetMethodIdx()) == method)
Jeff Hao49161ce2014-03-12 11:05:25 -0700766 << patch->GetTargetDexFile()->GetLocation() << " " << patch->GetReferrerMethodIdx() << " "
Brian Carlstrom7940e442013-07-12 13:46:57 -0700767 << PrettyMethod(dex_cache->GetResolvedMethods()->Get(patch->GetTargetMethodIdx())) << " "
768 << PrettyMethod(method);
769 return method;
770}
771
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800772static Class* GetTargetType(const CompilerDriver::TypePatchInformation* patch)
773 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
774 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700775 StackHandleScope<2> hs(Thread::Current());
776 Handle<mirror::DexCache> dex_cache(hs.NewHandle(class_linker->FindDexCache(patch->GetDexFile())));
Mathieu Chartier0cd81352014-05-22 16:48:55 -0700777 Class* klass = class_linker->ResolveType(patch->GetDexFile(), patch->GetTargetTypeIdx(),
778 dex_cache, NullHandle<mirror::ClassLoader>());
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800779 CHECK(klass != NULL)
780 << patch->GetDexFile().GetLocation() << " " << patch->GetTargetTypeIdx();
781 CHECK(dex_cache->GetResolvedTypes()->Get(patch->GetTargetTypeIdx()) == klass)
782 << patch->GetDexFile().GetLocation() << " " << patch->GetReferrerMethodIdx() << " "
783 << PrettyClass(dex_cache->GetResolvedTypes()->Get(patch->GetTargetTypeIdx())) << " "
784 << PrettyClass(klass);
785 return klass;
786}
787
Alex Light53cb16b2014-06-12 11:26:29 -0700788void ImageWriter::PatchOatCodeAndMethods(File* elf_file) {
789 std::vector<uintptr_t> patches;
790 std::set<uintptr_t> patches_set;
791 auto maybe_push = [&patches, &patches_set] (uintptr_t p) {
792 if (patches_set.find(p) == patches_set.end()) {
793 patches.push_back(p);
794 patches_set.insert(p);
795 }
796 };
797 const bool add_patches = compiler_driver_.GetCompilerOptions().GetIncludePatchInformation();
798 if (add_patches) {
Alex Lighteefbe392014-07-08 09:53:18 -0700799 // TODO if we are adding patches the resulting ELF file might have a potentially rather large
800 // amount of free space where patches might have been placed. We should adjust the ELF file to
801 // get rid of this excess space.
Alex Light53cb16b2014-06-12 11:26:29 -0700802 patches.reserve(compiler_driver_.GetCodeToPatch().size() +
803 compiler_driver_.GetMethodsToPatch().size() +
804 compiler_driver_.GetClassesToPatch().size());
805 }
806 uintptr_t loc = 0;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700807 Thread* self = Thread::Current();
808 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
809 const char* old_cause = self->StartAssertNoThreadSuspension("ImageWriter");
810
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800811 typedef std::vector<const CompilerDriver::CallPatchInformation*> CallPatches;
812 const CallPatches& code_to_patch = compiler_driver_.GetCodeToPatch();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700813 for (size_t i = 0; i < code_to_patch.size(); i++) {
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800814 const CompilerDriver::CallPatchInformation* patch = code_to_patch[i];
Brian Carlstromea46f952013-07-30 01:26:50 -0700815 ArtMethod* target = GetTargetMethod(patch);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800816 uintptr_t quick_code = reinterpret_cast<uintptr_t>(class_linker->GetQuickOatCodeFor(target));
Mathieu Chartier57d27332014-05-29 10:19:19 -0700817 DCHECK_NE(quick_code, 0U) << PrettyMethod(target);
Ian Rogersef7d42f2014-01-06 12:55:46 -0800818 uintptr_t code_base = reinterpret_cast<uintptr_t>(&oat_file_->GetOatHeader());
819 uintptr_t code_offset = quick_code - code_base;
Mathieu Chartier57d27332014-05-29 10:19:19 -0700820 bool is_quick_offset = false;
821 if (quick_code == reinterpret_cast<uintptr_t>(GetQuickToInterpreterBridge())) {
822 is_quick_offset = true;
Mathieu Chartierd8a737a2014-05-30 16:44:47 +0000823 code_offset = quick_to_interpreter_bridge_offset_;
Mathieu Chartier57d27332014-05-29 10:19:19 -0700824 } else if (quick_code ==
825 reinterpret_cast<uintptr_t>(class_linker->GetQuickGenericJniTrampoline())) {
826 CHECK(target->IsNative());
827 is_quick_offset = true;
Mathieu Chartierd8a737a2014-05-30 16:44:47 +0000828 code_offset = quick_generic_jni_trampoline_offset_;
Mathieu Chartier57d27332014-05-29 10:19:19 -0700829 }
830 uintptr_t value;
Mark Mendell55d0eac2014-02-06 11:02:52 -0800831 if (patch->IsRelative()) {
832 // value to patch is relative to the location being patched
833 const void* quick_oat_code =
834 class_linker->GetQuickOatCodeFor(patch->GetDexFile(),
835 patch->GetReferrerClassDefIdx(),
836 patch->GetReferrerMethodIdx());
Mathieu Chartier57d27332014-05-29 10:19:19 -0700837 if (is_quick_offset) {
Mathieu Chartier57d27332014-05-29 10:19:19 -0700838 // If its a quick offset it means that we are doing a relative patch from the class linker
839 // oat_file to the image writer oat_file so we need to adjust the quick oat code to be the
840 // one in the image writer oat_file.
Mathieu Chartierd8a737a2014-05-30 16:44:47 +0000841 quick_code = PointerToLowMemUInt32(GetOatAddress(code_offset));
Mathieu Chartier57d27332014-05-29 10:19:19 -0700842 quick_oat_code =
843 reinterpret_cast<const void*>(reinterpret_cast<uintptr_t>(quick_oat_code) +
844 reinterpret_cast<uintptr_t>(oat_data_begin_) - code_base);
845 }
Mark Mendell55d0eac2014-02-06 11:02:52 -0800846 uintptr_t base = reinterpret_cast<uintptr_t>(quick_oat_code);
847 uintptr_t patch_location = base + patch->GetLiteralOffset();
Mathieu Chartier57d27332014-05-29 10:19:19 -0700848 value = quick_code - patch_location + patch->RelativeOffset();
Mark Mendell55d0eac2014-02-06 11:02:52 -0800849 } else {
Mathieu Chartierd8a737a2014-05-30 16:44:47 +0000850 value = PointerToLowMemUInt32(GetOatAddress(code_offset));
Mark Mendell55d0eac2014-02-06 11:02:52 -0800851 }
Alex Light53cb16b2014-06-12 11:26:29 -0700852 SetPatchLocation(patch, value, &loc);
853 if (add_patches && !patch->AsCall()->IsRelative()) {
854 maybe_push(loc);
855 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700856 }
857
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800858 const CallPatches& methods_to_patch = compiler_driver_.GetMethodsToPatch();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700859 for (size_t i = 0; i < methods_to_patch.size(); i++) {
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800860 const CompilerDriver::CallPatchInformation* patch = methods_to_patch[i];
Brian Carlstromea46f952013-07-30 01:26:50 -0700861 ArtMethod* target = GetTargetMethod(patch);
Alex Light53cb16b2014-06-12 11:26:29 -0700862 SetPatchLocation(patch, PointerToLowMemUInt32(GetImageAddress(target)), &loc);
863 if (add_patches && !patch->AsCall()->IsRelative()) {
864 maybe_push(loc);
865 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700866 }
867
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800868 const std::vector<const CompilerDriver::TypePatchInformation*>& classes_to_patch =
869 compiler_driver_.GetClassesToPatch();
870 for (size_t i = 0; i < classes_to_patch.size(); i++) {
871 const CompilerDriver::TypePatchInformation* patch = classes_to_patch[i];
872 Class* target = GetTargetType(patch);
Alex Light53cb16b2014-06-12 11:26:29 -0700873 SetPatchLocation(patch, PointerToLowMemUInt32(GetImageAddress(target)), &loc);
874 if (add_patches) {
875 maybe_push(loc);
876 }
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800877 }
878
Brian Carlstrom7940e442013-07-12 13:46:57 -0700879 // Update the image header with the new checksum after patching
880 ImageHeader* image_header = reinterpret_cast<ImageHeader*>(image_->Begin());
881 image_header->SetOatChecksum(oat_file_->GetOatHeader().GetChecksum());
882 self->EndAssertNoThreadSuspension(old_cause);
Alex Light53cb16b2014-06-12 11:26:29 -0700883
884 // Update the ElfFiles SHT_OAT_PATCH section to include the patches.
885 if (add_patches) {
886 std::string err;
887 // TODO we are mapping in the contents of this file twice. We should be able
888 // to do it only once, which would be better.
889 std::unique_ptr<ElfFile> file(ElfFile::Open(elf_file, true, false, &err));
890 if (file == nullptr) {
891 LOG(ERROR) << err;
892 }
893 Elf32_Shdr* shdr = file->FindSectionByName(".oat_patches");
894 if (shdr != nullptr) {
Alex Lighteefbe392014-07-08 09:53:18 -0700895 CHECK_EQ(shdr, file->FindSectionByType(SHT_OAT_PATCH))
Alex Light53cb16b2014-06-12 11:26:29 -0700896 << "Incorrect type for .oat_patches section";
897 CHECK_LE(patches.size() * sizeof(uintptr_t), shdr->sh_size)
898 << "We got more patches than anticipated";
899 CHECK_LE(reinterpret_cast<uintptr_t>(file->Begin()) + shdr->sh_offset + shdr->sh_size,
900 reinterpret_cast<uintptr_t>(file->End())) << "section is too large";
901 CHECK(shdr == &file->GetSectionHeader(file->GetSectionHeaderNum() - 1) ||
902 shdr->sh_offset + shdr->sh_size <= (shdr + 1)->sh_offset)
903 << "Section overlaps onto next section";
904 // It's mmap'd so we can just memcpy.
905 memcpy(file->Begin() + shdr->sh_offset, patches.data(), patches.size()*sizeof(uintptr_t));
Alex Lighteefbe392014-07-08 09:53:18 -0700906 // TODO We should fill in the newly empty space between the last patch and the start of the
907 // next section by moving the following sections down if possible.
Alex Light53cb16b2014-06-12 11:26:29 -0700908 shdr->sh_size = patches.size() * sizeof(uintptr_t);
909 } else {
910 LOG(ERROR) << "Unable to find section header for SHT_OAT_PATCH";
911 }
912 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700913}
914
Alex Light53cb16b2014-06-12 11:26:29 -0700915void ImageWriter::SetPatchLocation(const CompilerDriver::PatchInformation* patch, uint32_t value,
916 uintptr_t* patched_ptr) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700917 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogersef7d42f2014-01-06 12:55:46 -0800918 const void* quick_oat_code = class_linker->GetQuickOatCodeFor(patch->GetDexFile(),
919 patch->GetReferrerClassDefIdx(),
920 patch->GetReferrerMethodIdx());
Brian Carlstrom7940e442013-07-12 13:46:57 -0700921 OatHeader& oat_header = const_cast<OatHeader&>(oat_file_->GetOatHeader());
922 // TODO: make this Thumb2 specific
Ian Rogersef7d42f2014-01-06 12:55:46 -0800923 uint8_t* base = reinterpret_cast<uint8_t*>(reinterpret_cast<uintptr_t>(quick_oat_code) & ~0x1);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700924 uint32_t* patch_location = reinterpret_cast<uint32_t*>(base + patch->GetLiteralOffset());
Mathieu Chartier590fee92013-09-13 13:46:47 -0700925 if (kIsDebugBuild) {
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800926 if (patch->IsCall()) {
927 const CompilerDriver::CallPatchInformation* cpatch = patch->AsCall();
Jeff Hao49161ce2014-03-12 11:05:25 -0700928 const DexFile::MethodId& id = cpatch->GetTargetDexFile()->GetMethodId(cpatch->GetTargetMethodIdx());
Andreas Gampe2da88232014-02-27 12:26:20 -0800929 uint32_t expected = reinterpret_cast<uintptr_t>(&id) & 0xFFFFFFFF;
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800930 uint32_t actual = *patch_location;
931 CHECK(actual == expected || actual == value) << std::hex
932 << "actual=" << actual
933 << "expected=" << expected
934 << "value=" << value;
935 }
936 if (patch->IsType()) {
937 const CompilerDriver::TypePatchInformation* tpatch = patch->AsType();
938 const DexFile::TypeId& id = tpatch->GetDexFile().GetTypeId(tpatch->GetTargetTypeIdx());
Andreas Gampe2da88232014-02-27 12:26:20 -0800939 uint32_t expected = reinterpret_cast<uintptr_t>(&id) & 0xFFFFFFFF;
Hiroshi Yamauchibe1ca552014-01-15 11:46:48 -0800940 uint32_t actual = *patch_location;
941 CHECK(actual == expected || actual == value) << std::hex
942 << "actual=" << actual
943 << "expected=" << expected
944 << "value=" << value;
945 }
Mathieu Chartier590fee92013-09-13 13:46:47 -0700946 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700947 *patch_location = value;
948 oat_header.UpdateChecksum(patch_location, sizeof(value));
Alex Light53cb16b2014-06-12 11:26:29 -0700949
950 uintptr_t loc = reinterpret_cast<uintptr_t>(patch_location) -
951 (reinterpret_cast<uintptr_t>(oat_file_->Begin()) + oat_header.GetExecutableOffset());
952 CHECK_GT(reinterpret_cast<uintptr_t>(patch_location),
953 reinterpret_cast<uintptr_t>(oat_file_->Begin()) + oat_header.GetExecutableOffset());
954 CHECK_LT(loc, oat_file_->Size() - oat_header.GetExecutableOffset());
955
956 *patched_ptr = loc;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700957}
958
959} // namespace art