blob: adaeebc22d29c0fd5f28415a0af834fc791a09d0 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
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 */
Brian Carlstromdb4d5402011-08-09 12:18:28 -070016
17#include "image_writer.h"
18
19#include <sys/mman.h>
Elliott Hughes90a33692011-08-30 13:27:07 -070020
Brian Carlstromdb4d5402011-08-09 12:18:28 -070021#include <vector>
22
Elliott Hughes90a33692011-08-30 13:27:07 -070023#include "UniquePtr.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070024#include "class_linker.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070025#include "class_loader.h"
Brian Carlstromae826982011-11-09 01:33:42 -080026#include "compiled_method.h"
Brian Carlstromf5822582012-03-19 22:34:31 -070027#include "compiler.h"
Elliott Hughes90a33692011-08-30 13:27:07 -070028#include "dex_cache.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070029#include "file.h"
30#include "globals.h"
31#include "heap.h"
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070032#include "image.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070033#include "intern_table.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070034#include "logging.h"
35#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080036#include "object_utils.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070037#include "runtime.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070038#include "space.h"
39#include "utils.h"
40
41namespace art {
42
Brian Carlstroma004aa92012-02-08 18:05:09 -080043bool ImageWriter::Write(const std::string& image_filename,
Ian Rogers30fab402012-01-23 15:43:46 -080044 uintptr_t image_begin,
Brian Carlstromae826982011-11-09 01:33:42 -080045 const std::string& oat_filename,
Brian Carlstromf5822582012-03-19 22:34:31 -070046 const std::string& oat_location,
47 const Compiler& compiler) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080048 CHECK(!image_filename.empty());
Brian Carlstromaded5f72011-10-07 17:15:04 -070049
Ian Rogers30fab402012-01-23 15:43:46 -080050 CHECK_NE(image_begin, 0U);
51 image_begin_ = reinterpret_cast<byte*>(image_begin);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070052
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080053 Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstromfddf6f62012-03-15 16:56:45 -070054 source_space_ = heap->GetAllocSpace();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070055
Brian Carlstromae826982011-11-09 01:33:42 -080056 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
57 const std::vector<DexCache*>& all_dex_caches = class_linker->GetDexCaches();
58 for (size_t i = 0; i < all_dex_caches.size(); i++) {
59 DexCache* dex_cache = all_dex_caches[i];
60 if (InSourceSpace(dex_cache)) {
61 dex_caches_.insert(dex_cache);
62 }
63 }
64
Brian Carlstromf5822582012-03-19 22:34:31 -070065 oat_file_ = OatFile::Open(oat_filename, oat_location, NULL, true);
66 if (oat_file_ == NULL) {
Brian Carlstrome24fa612011-09-29 00:53:55 -070067 LOG(ERROR) << "Failed to open oat file " << oat_filename;
68 return false;
69 }
Elliott Hughesb25c3f62012-03-26 16:35:06 -070070 class_linker->RegisterOatFile(*oat_file_);
Brian Carlstrome24fa612011-09-29 00:53:55 -070071
Ian Rogersd857b632012-02-06 20:42:33 -080072 PruneNonImageClasses(); // Remove junk
73 ComputeLazyFieldsForImageClasses(); // Add useful information
Ian Rogersd1f1bf02012-02-26 16:59:20 -080074 ComputeEagerResolvedStrings();
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080075 heap->CollectGarbage(false); // Remove garbage
76 heap->GetAllocSpace()->Trim(); // Trim size of source_space
Brian Carlstromae826982011-11-09 01:33:42 -080077 if (!AllocMemory()) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -070078 return false;
79 }
Brian Carlstromae826982011-11-09 01:33:42 -080080#ifndef NDEBUG
81 CheckNonImageClassesRemoved();
82#endif
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080083 heap->DisableCardMarking();
Brian Carlstromdb4d5402011-08-09 12:18:28 -070084 CalculateNewObjectOffsets();
85 CopyAndFixupObjects();
Brian Carlstromf5822582012-03-19 22:34:31 -070086 PatchOatCodeAndMethods(compiler);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -070087
Brian Carlstroma004aa92012-02-08 18:05:09 -080088 UniquePtr<File> file(OS::OpenFile(image_filename.c_str(), true));
Elliott Hughes90a33692011-08-30 13:27:07 -070089 if (file.get() == NULL) {
Brian Carlstrome24fa612011-09-29 00:53:55 -070090 LOG(ERROR) << "Failed to open image file " << image_filename;
Brian Carlstromdb4d5402011-08-09 12:18:28 -070091 return false;
92 }
Ian Rogers30fab402012-01-23 15:43:46 -080093 bool success = file->WriteFully(image_->Begin(), image_end_);
Brian Carlstrome24fa612011-09-29 00:53:55 -070094 if (!success) {
95 PLOG(ERROR) << "Failed to write image file " << image_filename;
96 return false;
97 }
98 return true;
Brian Carlstromdb4d5402011-08-09 12:18:28 -070099}
100
Brian Carlstromae826982011-11-09 01:33:42 -0800101bool ImageWriter::AllocMemory() {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700102 size_t size = source_space_->Size();
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700103 int prot = PROT_READ | PROT_WRITE;
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700104 size_t length = RoundUp(size, kPageSize);
Brian Carlstrom89521892011-12-07 22:05:07 -0800105 image_.reset(MemMap::MapAnonymous("image-writer-image", NULL, length, prot));
Elliott Hughes90a33692011-08-30 13:27:07 -0700106 if (image_.get() == NULL) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700107 LOG(ERROR) << "Failed to allocate memory for image file generation";
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700108 return false;
109 }
110 return true;
111}
112
Ian Rogersd418eda2012-01-30 12:14:28 -0800113void ImageWriter::ComputeLazyFieldsForImageClasses() {
114 Runtime* runtime = Runtime::Current();
115 ClassLinker* class_linker = runtime->GetClassLinker();
116 class_linker->VisitClasses(ComputeLazyFieldsForClassesVisitor, NULL);
117}
118
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700119bool ImageWriter::ComputeLazyFieldsForClassesVisitor(Class* c, void* /*arg*/) {
120 c->ComputeName();
Ian Rogersd418eda2012-01-30 12:14:28 -0800121 return true;
122}
123
Ian Rogersd1f1bf02012-02-26 16:59:20 -0800124void ImageWriter::ComputeEagerResolvedStringsCallback(Object* obj, void* arg) {
125 if (!obj->GetClass()->IsStringClass()) {
126 return;
127 }
128 String* string = obj->AsString();
129 std::string utf8_string(string->ToModifiedUtf8());
130 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
131 ClassLinker* linker = Runtime::Current()->GetClassLinker();
132 typedef Set::const_iterator CacheIt; // TODO: C++0x auto
133 for (CacheIt it = writer->dex_caches_.begin(), end = writer->dex_caches_.end(); it != end; ++it) {
134 DexCache* dex_cache = *it;
135 const DexFile& dex_file = linker->FindDexFile(dex_cache);
136 const DexFile::StringId* string_id = dex_file.FindStringId(utf8_string);
137 if (string_id != NULL) {
138 // This string occurs in this dex file, assign the dex cache entry.
139 uint32_t string_idx = dex_file.GetIndexForStringId(*string_id);
140 if (dex_cache->GetResolvedString(string_idx) == NULL) {
141 dex_cache->SetResolvedString(string_idx, string);
142 }
143 }
144 }
145}
146
147void ImageWriter::ComputeEagerResolvedStrings() {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800148 HeapBitmap* heap_bitmap = Runtime::Current()->GetHeap()->GetLiveBits();
Ian Rogersd1f1bf02012-02-26 16:59:20 -0800149 DCHECK(heap_bitmap != NULL);
150 heap_bitmap->Walk(ComputeEagerResolvedStringsCallback, this); // TODO: add Space-limited Walk
151}
152
Brian Carlstromae826982011-11-09 01:33:42 -0800153bool ImageWriter::IsImageClass(const Class* klass) {
154 if (image_classes_ == NULL) {
155 return true;
156 }
157 while (klass->IsArrayClass()) {
158 klass = klass->GetComponentType();
159 }
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800160 if (klass->IsPrimitive()) {
Brian Carlstromae826982011-11-09 01:33:42 -0800161 return true;
162 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800163 const std::string descriptor(ClassHelper(klass).GetDescriptor());
Brian Carlstromae826982011-11-09 01:33:42 -0800164 return image_classes_->find(descriptor) != image_classes_->end();
165}
166
167
168struct NonImageClasses {
169 ImageWriter* image_writer;
170 std::set<std::string>* non_image_classes;
171};
172
173void ImageWriter::PruneNonImageClasses() {
174 if (image_classes_ == NULL) {
175 return;
176 }
177 Runtime* runtime = Runtime::Current();
178 ClassLinker* class_linker = runtime->GetClassLinker();
179
180 std::set<std::string> non_image_classes;
181 NonImageClasses context;
182 context.image_writer = this;
183 context.non_image_classes = &non_image_classes;
184 class_linker->VisitClasses(NonImageClassesVisitor, &context);
185
186 typedef std::set<std::string>::const_iterator ClassIt; // TODO: C++0x auto
187 for (ClassIt it = non_image_classes.begin(), end = non_image_classes.end(); it != end; ++it) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800188 class_linker->RemoveClass((*it).c_str(), NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800189 }
190
Ian Rogers19846512012-02-24 11:42:47 -0800191 Method* resolution_method = runtime->GetResolutionMethod();
Brian Carlstromae826982011-11-09 01:33:42 -0800192 typedef Set::const_iterator CacheIt; // TODO: C++0x auto
193 for (CacheIt it = dex_caches_.begin(), end = dex_caches_.end(); it != end; ++it) {
194 DexCache* dex_cache = *it;
195 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
196 Class* klass = dex_cache->GetResolvedType(i);
197 if (klass != NULL && !IsImageClass(klass)) {
198 dex_cache->SetResolvedType(i, NULL);
199 dex_cache->GetInitializedStaticStorage()->Set(i, NULL);
200 }
201 }
202 for (size_t i = 0; i < dex_cache->NumResolvedMethods(); i++) {
203 Method* method = dex_cache->GetResolvedMethod(i);
204 if (method != NULL && !IsImageClass(method->GetDeclaringClass())) {
Ian Rogers19846512012-02-24 11:42:47 -0800205 dex_cache->SetResolvedMethod(i, resolution_method);
Brian Carlstromae826982011-11-09 01:33:42 -0800206 }
207 }
208 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
209 Field* field = dex_cache->GetResolvedField(i);
210 if (field != NULL && !IsImageClass(field->GetDeclaringClass())) {
211 dex_cache->SetResolvedField(i, NULL);
212 }
213 }
214 }
215}
216
217bool ImageWriter::NonImageClassesVisitor(Class* klass, void* arg) {
218 NonImageClasses* context = reinterpret_cast<NonImageClasses*>(arg);
219 if (!context->image_writer->IsImageClass(klass)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800220 context->non_image_classes->insert(ClassHelper(klass).GetDescriptor());
Brian Carlstromae826982011-11-09 01:33:42 -0800221 }
222 return true;
223}
224
225void ImageWriter::CheckNonImageClassesRemoved() {
226 if (image_classes_ == NULL) {
227 return;
228 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800229 Runtime::Current()->GetHeap()->GetLiveBits()->Walk(CheckNonImageClassesRemovedCallback, this);
Brian Carlstromae826982011-11-09 01:33:42 -0800230}
231
232void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
233 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
234 if (!obj->IsClass()) {
235 return;
236 }
237 Class* klass = obj->AsClass();
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800238 if (!image_writer->IsImageClass(klass)) {
239 image_writer->DumpImageClasses();
240 CHECK(image_writer->IsImageClass(klass)) << ClassHelper(klass).GetDescriptor()
241 << " " << PrettyDescriptor(klass);
242 }
243}
244
245void ImageWriter::DumpImageClasses() {
246 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
247 for (It it = image_classes_->begin(), end = image_classes_->end(); it != end; ++it) {
248 LOG(INFO) << " " << *it;
249 }
Brian Carlstromae826982011-11-09 01:33:42 -0800250}
251
Brian Carlstrom78128a62011-09-15 17:21:19 -0700252void ImageWriter::CalculateNewObjectOffsetsCallback(Object* obj, void* arg) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700253 DCHECK(obj != NULL);
254 DCHECK(arg != NULL);
255 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700256 if (!image_writer->InSourceSpace(obj)) {
257 return;
258 }
Brian Carlstromc74255f2011-09-11 22:47:39 -0700259
260 // if it is a string, we want to intern it if its not interned.
Elliott Hughesdbb40792011-11-18 17:05:22 -0800261 if (obj->GetClass()->IsStringClass()) {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700262 // we must be an interned string that was forward referenced and already assigned
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800263 if (image_writer->IsImageOffsetAssigned(obj)) {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700264 DCHECK_EQ(obj, obj->AsString()->Intern());
265 return;
266 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700267 SirtRef<String> interned(obj->AsString()->Intern());
268 if (obj != interned.get()) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800269 if (!image_writer->IsImageOffsetAssigned(interned.get())) {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700270 // interned obj is after us, allocate its location early
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700271 image_writer->AssignImageOffset(interned.get());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700272 }
273 // point those looking for this object to the interned version.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800274 image_writer->SetImageOffset(obj, image_writer->GetImageOffset(interned.get()));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700275 return;
276 }
277 // else (obj == interned), nothing to do but fall through to the normal case
278 }
279
280 image_writer->AssignImageOffset(obj);
Brian Carlstrom4e777d42011-08-15 13:53:52 -0700281}
282
Brian Carlstrome24fa612011-09-29 00:53:55 -0700283ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
Brian Carlstrom16192862011-09-12 17:50:06 -0700284 Runtime* runtime = Runtime::Current();
285 ClassLinker* class_linker = runtime->GetClassLinker();
286 Class* object_array_class = class_linker->FindSystemClass("[Ljava/lang/Object;");
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700287
288 // build an Object[] of all the DexCaches used in the source_space_
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700289 ObjectArray<Object>* dex_caches = ObjectArray<Object>::Alloc(object_array_class,
Brian Carlstromae826982011-11-09 01:33:42 -0800290 dex_caches_.size());
291 int i = 0;
292 typedef Set::const_iterator It; // TODO: C++0x auto
293 for (It it = dex_caches_.begin(), end = dex_caches_.end(); it != end; ++it, ++i) {
294 dex_caches->Set(i, *it);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700295 }
296
297 // build an Object[] of the roots needed to restore the runtime
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700298 SirtRef<ObjectArray<Object> > image_roots(
299 ObjectArray<Object>::Alloc(object_array_class, ImageHeader::kImageRootsMax));
Ian Rogers169c9a72011-11-13 20:13:17 -0800300 image_roots->Set(ImageHeader::kJniStubArray, runtime->GetJniDlsymLookupStub());
Brian Carlstrome24fa612011-09-29 00:53:55 -0700301 image_roots->Set(ImageHeader::kAbstractMethodErrorStubArray,
302 runtime->GetAbstractMethodErrorStubArray());
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700303 image_roots->Set(ImageHeader::kStaticResolutionStubArray,
304 runtime->GetResolutionStubArray(Runtime::kStaticMethod));
305 image_roots->Set(ImageHeader::kUnknownMethodResolutionStubArray,
306 runtime->GetResolutionStubArray(Runtime::kUnknownMethod));
Ian Rogers19846512012-02-24 11:42:47 -0800307 image_roots->Set(ImageHeader::kResolutionMethod, runtime->GetResolutionMethod());
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700308 image_roots->Set(ImageHeader::kCalleeSaveMethod,
309 runtime->GetCalleeSaveMethod(Runtime::kSaveAll));
310 image_roots->Set(ImageHeader::kRefsOnlySaveMethod,
311 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly));
312 image_roots->Set(ImageHeader::kRefsAndArgsSaveMethod,
313 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs));
Brian Carlstrome24fa612011-09-29 00:53:55 -0700314 image_roots->Set(ImageHeader::kOatLocation,
315 String::AllocFromModifiedUtf8(oat_file_->GetLocation().c_str()));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700316 image_roots->Set(ImageHeader::kDexCaches,
317 dex_caches);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700318 image_roots->Set(ImageHeader::kClassRoots,
319 class_linker->GetClassRoots());
Brian Carlstrome24fa612011-09-29 00:53:55 -0700320 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
321 CHECK(image_roots->Get(i) != NULL);
322 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700323 return image_roots.get();
Brian Carlstrom16192862011-09-12 17:50:06 -0700324}
325
Brian Carlstrom4e777d42011-08-15 13:53:52 -0700326void ImageWriter::CalculateNewObjectOffsets() {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700327 SirtRef<ObjectArray<Object> > image_roots(CreateImageRoots());
Brian Carlstrom16192862011-09-12 17:50:06 -0700328
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800329 HeapBitmap* heap_bitmap = Runtime::Current()->GetHeap()->GetLiveBits();
Brian Carlstrom4e777d42011-08-15 13:53:52 -0700330 DCHECK(heap_bitmap != NULL);
Ian Rogers30fab402012-01-23 15:43:46 -0800331 DCHECK_EQ(0U, image_end_);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700332
Brian Carlstrom16192862011-09-12 17:50:06 -0700333 // leave space for the header, but do not write it yet, we need to
334 // know where image_roots is going to end up
Ian Rogers30fab402012-01-23 15:43:46 -0800335 image_end_ += RoundUp(sizeof(ImageHeader), 8); // 64-bit-alignment
Brian Carlstroma663ea52011-08-19 23:33:41 -0700336
Ian Rogers1351b672012-02-24 12:22:57 -0800337 heap_bitmap->InOrderWalk(CalculateNewObjectOffsetsCallback, this); // TODO: add Space-limited Walk
Ian Rogers30fab402012-01-23 15:43:46 -0800338 DCHECK_LT(image_end_, image_->Size());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700339
Brian Carlstrome24fa612011-09-29 00:53:55 -0700340 // Note that image_top_ is left at end of used space
Ian Rogers30fab402012-01-23 15:43:46 -0800341 oat_begin_ = image_begin_ + RoundUp(image_end_, kPageSize);
342 const byte* oat_limit = oat_begin_ + oat_file_->Size();
Brian Carlstrome24fa612011-09-29 00:53:55 -0700343
Brian Carlstrom16192862011-09-12 17:50:06 -0700344 // return to write header at start of image with future location of image_roots
Ian Rogers30fab402012-01-23 15:43:46 -0800345 ImageHeader image_header(reinterpret_cast<uint32_t>(image_begin_),
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700346 reinterpret_cast<uint32_t>(GetImageAddress(image_roots.get())),
Brian Carlstrome24fa612011-09-29 00:53:55 -0700347 oat_file_->GetOatHeader().GetChecksum(),
Ian Rogers30fab402012-01-23 15:43:46 -0800348 reinterpret_cast<uint32_t>(oat_begin_),
Brian Carlstrome24fa612011-09-29 00:53:55 -0700349 reinterpret_cast<uint32_t>(oat_limit));
Ian Rogers30fab402012-01-23 15:43:46 -0800350 memcpy(image_->Begin(), &image_header, sizeof(image_header));
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700351}
352
353void ImageWriter::CopyAndFixupObjects() {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800354 Heap* heap = Runtime::Current()->GetHeap();
355 HeapBitmap* heap_bitmap = heap->GetLiveBits();
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700356 DCHECK(heap_bitmap != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700357 // TODO: heap validation can't handle this fix up pass
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800358 heap->DisableObjectValidation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700359 heap_bitmap->Walk(CopyAndFixupObjectsCallback, this); // TODO: add Space-limited Walk
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700360}
361
Brian Carlstrom78128a62011-09-15 17:21:19 -0700362void ImageWriter::CopyAndFixupObjectsCallback(Object* object, void* arg) {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700363 DCHECK(object != NULL);
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700364 DCHECK(arg != NULL);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700365 const Object* obj = object;
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700366 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700367 if (!image_writer->InSourceSpace(object)) {
368 return;
369 }
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700370
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700371 // see GetLocalAddress for similar computation
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700372 size_t offset = image_writer->GetImageOffset(obj);
Ian Rogers30fab402012-01-23 15:43:46 -0800373 byte* dst = image_writer->image_->Begin() + offset;
Brian Carlstrom4873d462011-08-21 15:23:39 -0700374 const byte* src = reinterpret_cast<const byte*>(obj);
Elliott Hughes04b63fd2011-08-16 09:40:10 -0700375 size_t n = obj->SizeOf();
Ian Rogers30fab402012-01-23 15:43:46 -0800376 DCHECK_LT(offset + n, image_writer->image_->Size());
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700377 memcpy(dst, src, n);
378 Object* copy = reinterpret_cast<Object*>(dst);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800379 copy->monitor_ = 0; // We may have inflated the lock during compilation.
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700380 image_writer->FixupObject(obj, copy);
381}
382
Brian Carlstrom4873d462011-08-21 15:23:39 -0700383void ImageWriter::FixupObject(const Object* orig, Object* copy) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700384 DCHECK(orig != NULL);
385 DCHECK(copy != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700386 copy->SetClass(down_cast<Class*>(GetImageAddress(orig->GetClass())));
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700387 // TODO: special case init of pointers to malloc data (or removal of these pointers)
388 if (orig->IsClass()) {
389 FixupClass(orig->AsClass(), down_cast<Class*>(copy));
390 } else if (orig->IsObjectArray()) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700391 FixupObjectArray(orig->AsObjectArray<Object>(), down_cast<ObjectArray<Object>*>(copy));
Brian Carlstrom16192862011-09-12 17:50:06 -0700392 } else if (orig->IsMethod()) {
393 FixupMethod(orig->AsMethod(), down_cast<Method*>(copy));
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700394 } else {
395 FixupInstanceFields(orig, copy);
396 }
397}
398
Brian Carlstrom4873d462011-08-21 15:23:39 -0700399void ImageWriter::FixupClass(const Class* orig, Class* copy) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700400 FixupInstanceFields(orig, copy);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700401 FixupStaticFields(orig, copy);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700402}
403
Brian Carlstrom4873d462011-08-21 15:23:39 -0700404void ImageWriter::FixupMethod(const Method* orig, Method* copy) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700405 FixupInstanceFields(orig, copy);
Brian Carlstrome24fa612011-09-29 00:53:55 -0700406
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700407 // OatWriter replaces the code_ and invoke_stub_ with offset values.
Ian Rogers30fab402012-01-23 15:43:46 -0800408 // Here we readjust to a pointer relative to oat_begin_
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700409
410 // Every type of method can have an invoke stub
411 uint32_t invoke_stub_offset = orig->GetOatInvokeStubOffset();
Brian Carlstromae826982011-11-09 01:33:42 -0800412 const byte* invoke_stub = GetOatAddress(invoke_stub_offset);
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700413 copy->invoke_stub_ = reinterpret_cast<const Method::InvokeStub*>(invoke_stub);
414
415 if (orig->IsAbstract()) {
416 // Abstract methods are pointed to a stub that will throw AbstractMethodError if they are called
417 ByteArray* orig_ame_stub_array_ = Runtime::Current()->GetAbstractMethodErrorStubArray();
418 ByteArray* copy_ame_stub_array_ = down_cast<ByteArray*>(GetImageAddress(orig_ame_stub_array_));
419 copy->code_ = copy_ame_stub_array_->GetData();
420 return;
421 }
422
Ian Rogers19846512012-02-24 11:42:47 -0800423 if (orig == Runtime::Current()->GetResolutionMethod()) {
424 // The resolution stub's code points at the unknown resolution trampoline
425 ByteArray* orig_res_stub_array_ =
426 Runtime::Current()->GetResolutionStubArray(Runtime::kUnknownMethod);
427 CHECK(orig->GetCode() == orig_res_stub_array_->GetData());
428 ByteArray* copy_res_stub_array_ = down_cast<ByteArray*>(GetImageAddress(orig_res_stub_array_));
429 copy->code_ = copy_res_stub_array_->GetData();
430 return;
431 }
432
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700433 // Non-abstract methods typically have code
434 uint32_t code_offset = orig->GetOatCodeOffset();
Ian Rogers19846512012-02-24 11:42:47 -0800435 const byte* code = NULL;
436 if (orig->IsStatic()) {
437 // Static methods may point at the resolution trampoline stub
438 ByteArray* orig_res_stub_array_ =
439 Runtime::Current()->GetResolutionStubArray(Runtime::kStaticMethod);
440 if (reinterpret_cast<int8_t*>(code_offset) == orig_res_stub_array_->GetData()) {
441 ByteArray* copy_res_stub_array_ = down_cast<ByteArray*>(GetImageAddress(orig_res_stub_array_));
442 code = reinterpret_cast<const byte*>(copy_res_stub_array_->GetData());
443 }
444 }
445 if (code == NULL) {
446 code = GetOatAddress(code_offset);
447 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700448 copy->code_ = code;
449
Brian Carlstrom16192862011-09-12 17:50:06 -0700450 if (orig->IsNative()) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700451 // The native method's pointer is directed to a stub to lookup via dlsym.
452 // Note this is not the code_ pointer, that is handled above.
Ian Rogers169c9a72011-11-13 20:13:17 -0800453 ByteArray* orig_jni_stub_array_ = Runtime::Current()->GetJniDlsymLookupStub();
Brian Carlstrom16192862011-09-12 17:50:06 -0700454 ByteArray* copy_jni_stub_array_ = down_cast<ByteArray*>(GetImageAddress(orig_jni_stub_array_));
455 copy->native_method_ = copy_jni_stub_array_->GetData();
456 } else {
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700457 // normal (non-abstract non-native) methods have mapping tables to relocate
458 uint32_t mapping_table_off = orig->GetOatMappingTableOffset();
Brian Carlstromae826982011-11-09 01:33:42 -0800459 const byte* mapping_table = GetOatAddress(mapping_table_off);
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700460 copy->mapping_table_ = reinterpret_cast<const uint32_t*>(mapping_table);
461
462 uint32_t vmap_table_offset = orig->GetOatVmapTableOffset();
Brian Carlstromae826982011-11-09 01:33:42 -0800463 const byte* vmap_table = GetOatAddress(vmap_table_offset);
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700464 copy->vmap_table_ = reinterpret_cast<const uint16_t*>(vmap_table);
Brian Carlstrome7d856b2012-01-11 18:10:55 -0800465
466 uint32_t gc_map_offset = orig->GetOatGcMapOffset();
467 const byte* gc_map = GetOatAddress(gc_map_offset);
468 copy->gc_map_ = reinterpret_cast<const uint8_t*>(gc_map);
Brian Carlstrom16192862011-09-12 17:50:06 -0700469 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700470}
471
Brian Carlstrom4873d462011-08-21 15:23:39 -0700472void ImageWriter::FixupObjectArray(const ObjectArray<Object>* orig, ObjectArray<Object>* copy) {
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700473 for (int32_t i = 0; i < orig->GetLength(); ++i) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700474 const Object* element = orig->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700475 copy->SetWithoutChecks(i, GetImageAddress(element));
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700476 }
477}
478
Brian Carlstrom4873d462011-08-21 15:23:39 -0700479void ImageWriter::FixupInstanceFields(const Object* orig, Object* copy) {
480 DCHECK(orig != NULL);
481 DCHECK(copy != NULL);
482 Class* klass = orig->GetClass();
483 DCHECK(klass != NULL);
484 FixupFields(orig,
485 copy,
486 klass->GetReferenceInstanceOffsets(),
487 false);
488}
489
490void ImageWriter::FixupStaticFields(const Class* orig, Class* copy) {
491 DCHECK(orig != NULL);
492 DCHECK(copy != NULL);
493 FixupFields(orig,
494 copy,
495 orig->GetReferenceStaticOffsets(),
496 true);
497}
498
499void ImageWriter::FixupFields(const Object* orig,
500 Object* copy,
501 uint32_t ref_offsets,
502 bool is_static) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700503 if (ref_offsets != CLASS_WALK_SUPER) {
504 // Found a reference offset bitmap. Fixup the specified offsets.
505 while (ref_offsets != 0) {
506 size_t right_shift = CLZ(ref_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700507 MemberOffset byte_offset = CLASS_OFFSET_FROM_CLZ(right_shift);
508 const Object* ref = orig->GetFieldObject<const Object*>(byte_offset, false);
509 copy->SetFieldObject(byte_offset, GetImageAddress(ref), false);
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700510 ref_offsets &= ~(CLASS_HIGH_BIT >> right_shift);
511 }
512 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700513 // There is no reference offset bitmap. In the non-static case,
514 // walk up the class inheritance hierarchy and find reference
515 // offsets the hard way. In the static case, just consider this
516 // class.
517 for (const Class *klass = is_static ? orig->AsClass() : orig->GetClass();
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700518 klass != NULL;
Brian Carlstrom4873d462011-08-21 15:23:39 -0700519 klass = is_static ? NULL : klass->GetSuperClass()) {
520 size_t num_reference_fields = (is_static
521 ? klass->NumReferenceStaticFields()
522 : klass->NumReferenceInstanceFields());
523 for (size_t i = 0; i < num_reference_fields; ++i) {
524 Field* field = (is_static
525 ? klass->GetStaticField(i)
526 : klass->GetInstanceField(i));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700527 MemberOffset field_offset = field->GetOffset();
528 const Object* ref = orig->GetFieldObject<const Object*>(field_offset, false);
529 copy->SetFieldObject(field_offset, GetImageAddress(ref), false);
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700530 }
531 }
532 }
533}
534
Brian Carlstromf5822582012-03-19 22:34:31 -0700535static Method* GetReferrerMethod(const Compiler::PatchInformation* patch) {
536 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
537 Method* method = class_linker->ResolveMethod(patch->GetDexFile(),
538 patch->GetReferrerMethodIdx(),
539 patch->GetDexCache(),
540 NULL,
541 patch->GetReferrerIsDirect());
542 CHECK(method != NULL)
543 << patch->GetDexFile().GetLocation() << " " << patch->GetReferrerMethodIdx();
Brian Carlstrom0637e272012-03-20 01:07:52 -0700544 CHECK(!method->IsRuntimeMethod())
545 << patch->GetDexFile().GetLocation() << " " << patch->GetReferrerMethodIdx();
546 CHECK(patch->GetDexCache()->GetResolvedMethods()->Get(patch->GetReferrerMethodIdx()) == method)
547 << patch->GetDexFile().GetLocation() << " " << patch->GetReferrerMethodIdx() << " "
548 << PrettyMethod(patch->GetDexCache()->GetResolvedMethods()->Get(patch->GetReferrerMethodIdx())) << " "
549 << PrettyMethod(method);
Brian Carlstromf5822582012-03-19 22:34:31 -0700550 return method;
551}
552
553static Method* GetTargetMethod(const Compiler::PatchInformation* patch) {
554 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
555 Method* method = class_linker->ResolveMethod(patch->GetDexFile(),
556 patch->GetTargetMethodIdx(),
557 patch->GetDexCache(),
558 NULL,
559 patch->GetTargetIsDirect());
560 CHECK(method != NULL)
561 << patch->GetDexFile().GetLocation() << " " << patch->GetTargetMethodIdx();
Brian Carlstrom0637e272012-03-20 01:07:52 -0700562 CHECK(!method->IsRuntimeMethod())
563 << patch->GetDexFile().GetLocation() << " " << patch->GetTargetMethodIdx();
564 CHECK(patch->GetDexCache()->GetResolvedMethods()->Get(patch->GetTargetMethodIdx()) == method)
565 << patch->GetDexFile().GetLocation() << " " << patch->GetReferrerMethodIdx() << " "
566 << PrettyMethod(patch->GetDexCache()->GetResolvedMethods()->Get(patch->GetTargetMethodIdx())) << " "
567 << PrettyMethod(method);
Brian Carlstromf5822582012-03-19 22:34:31 -0700568 return method;
569}
570
571void ImageWriter::PatchOatCodeAndMethods(const Compiler& compiler) {
572 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
573
574 const std::vector<const Compiler::PatchInformation*>& code_to_patch = compiler.GetCodeToPatch();
575 for (size_t i = 0; i < code_to_patch.size(); i++) {
576 const Compiler::PatchInformation* patch = code_to_patch[i];
577 Method* target = GetTargetMethod(patch);
578 uint32_t code = reinterpret_cast<uint32_t>(class_linker->GetOatCodeFor(target));
579 uint32_t code_base = reinterpret_cast<uint32_t>(&oat_file_->GetOatHeader());
580 uint32_t code_offset = code - code_base;
581 SetPatchLocation(patch, reinterpret_cast<uint32_t>(GetOatAddress(code_offset)));
582 }
583
584 const std::vector<const Compiler::PatchInformation*>& methods_to_patch
585 = compiler.GetMethodsToPatch();
586 for (size_t i = 0; i < methods_to_patch.size(); i++) {
587 const Compiler::PatchInformation* patch = methods_to_patch[i];
588 Method* target = GetTargetMethod(patch);
589 SetPatchLocation(patch, reinterpret_cast<uint32_t>(GetImageAddress(target)));
590 }
591}
592
593void ImageWriter::SetPatchLocation(const Compiler::PatchInformation* patch, uint32_t value) {
594 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
595 Method* method = GetReferrerMethod(patch);
596 // Goodbye const, we are about to modify some code.
597 void* code = const_cast<void*>(class_linker->GetOatCodeFor(method));
598 // TODO: make this Thumb2 specific
599 uint8_t* base = reinterpret_cast<uint8_t*>(reinterpret_cast<uint32_t>(code) & ~0x1);
600 uint32_t* patch_location = reinterpret_cast<uint32_t*>(base + patch->GetLiteralOffset());
601#ifndef NDEBUG
602 const DexFile::MethodId& id = patch->GetDexFile().GetMethodId(patch->GetTargetMethodIdx());
603 uint32_t expected = reinterpret_cast<uint32_t>(&id);
604 uint32_t actual = *patch_location;
605 CHECK(actual == expected || actual == value) << std::hex
606 << "actual=" << actual
607 << "expected=" << expected
608 << "value=" << value;
609#endif
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700610 *patch_location = value;
Brian Carlstromf5822582012-03-19 22:34:31 -0700611}
612
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700613} // namespace art