blob: d1328c15e5e2e8cf4ea0671c60926b669afe9fcd [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>
Brian Carlstrom6cd40e52012-05-03 14:15:11 -070020#include <sys/stat.h>
Elliott Hughes90a33692011-08-30 13:27:07 -070021
Brian Carlstromdb4d5402011-08-09 12:18:28 -070022#include <vector>
23
Elliott Hughes90a33692011-08-30 13:27:07 -070024#include "UniquePtr.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070025#include "class_linker.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070026#include "class_loader.h"
Brian Carlstromae826982011-11-09 01:33:42 -080027#include "compiled_method.h"
Brian Carlstromf5822582012-03-19 22:34:31 -070028#include "compiler.h"
Elliott Hughes90a33692011-08-30 13:27:07 -070029#include "dex_cache.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070030#include "file.h"
31#include "globals.h"
32#include "heap.h"
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070033#include "image.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070034#include "intern_table.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070035#include "logging.h"
Logan Chien0c717dd2012-03-28 18:31:07 +080036#include "oat_file.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070037#include "object.h"
Ian Rogers6d4d9fc2011-11-30 16:24:48 -080038#include "object_utils.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070039#include "runtime.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070040#include "space.h"
41#include "utils.h"
42
43namespace art {
44
Brian Carlstroma004aa92012-02-08 18:05:09 -080045bool ImageWriter::Write(const std::string& image_filename,
Ian Rogers30fab402012-01-23 15:43:46 -080046 uintptr_t image_begin,
Brian Carlstromae826982011-11-09 01:33:42 -080047 const std::string& oat_filename,
Brian Carlstromf5822582012-03-19 22:34:31 -070048 const std::string& oat_location,
49 const Compiler& compiler) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080050 CHECK(!image_filename.empty());
Brian Carlstromaded5f72011-10-07 17:15:04 -070051
Ian Rogers30fab402012-01-23 15:43:46 -080052 CHECK_NE(image_begin, 0U);
53 image_begin_ = reinterpret_cast<byte*>(image_begin);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070054
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080055 Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstromfddf6f62012-03-15 16:56:45 -070056 source_space_ = heap->GetAllocSpace();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070057
Brian Carlstromae826982011-11-09 01:33:42 -080058 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
59 const std::vector<DexCache*>& all_dex_caches = class_linker->GetDexCaches();
60 for (size_t i = 0; i < all_dex_caches.size(); i++) {
61 DexCache* dex_cache = all_dex_caches[i];
62 if (InSourceSpace(dex_cache)) {
63 dex_caches_.insert(dex_cache);
64 }
65 }
66
Logan Chien0c717dd2012-03-28 18:31:07 +080067 oat_file_ = OatFile::Open(oat_filename, oat_location, NULL,
68 OatFile::kRelocNone, true);
Brian Carlstromf5822582012-03-19 22:34:31 -070069 if (oat_file_ == NULL) {
Brian Carlstrome24fa612011-09-29 00:53:55 -070070 LOG(ERROR) << "Failed to open oat file " << oat_filename;
71 return false;
72 }
Elliott Hughesb25c3f62012-03-26 16:35:06 -070073 class_linker->RegisterOatFile(*oat_file_);
Brian Carlstrome24fa612011-09-29 00:53:55 -070074
Ian Rogersd857b632012-02-06 20:42:33 -080075 PruneNonImageClasses(); // Remove junk
76 ComputeLazyFieldsForImageClasses(); // Add useful information
Ian Rogersd1f1bf02012-02-26 16:59:20 -080077 ComputeEagerResolvedStrings();
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080078 heap->CollectGarbage(false); // Remove garbage
79 heap->GetAllocSpace()->Trim(); // Trim size of source_space
Brian Carlstromae826982011-11-09 01:33:42 -080080 if (!AllocMemory()) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -070081 return false;
82 }
Brian Carlstromae826982011-11-09 01:33:42 -080083#ifndef NDEBUG
84 CheckNonImageClassesRemoved();
85#endif
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080086 heap->DisableCardMarking();
Brian Carlstromdb4d5402011-08-09 12:18:28 -070087 CalculateNewObjectOffsets();
88 CopyAndFixupObjects();
Brian Carlstromf5822582012-03-19 22:34:31 -070089 PatchOatCodeAndMethods(compiler);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -070090
Brian Carlstroma004aa92012-02-08 18:05:09 -080091 UniquePtr<File> file(OS::OpenFile(image_filename.c_str(), true));
Elliott Hughes90a33692011-08-30 13:27:07 -070092 if (file.get() == NULL) {
Brian Carlstrome24fa612011-09-29 00:53:55 -070093 LOG(ERROR) << "Failed to open image file " << image_filename;
Brian Carlstromdb4d5402011-08-09 12:18:28 -070094 return false;
95 }
Brian Carlstrom6cd40e52012-05-03 14:15:11 -070096 if (fchmod(file->Fd(), 0644) != 0) {
97 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
98 return EXIT_FAILURE;
99 }
Ian Rogers30fab402012-01-23 15:43:46 -0800100 bool success = file->WriteFully(image_->Begin(), image_end_);
Brian Carlstrome24fa612011-09-29 00:53:55 -0700101 if (!success) {
102 PLOG(ERROR) << "Failed to write image file " << image_filename;
103 return false;
104 }
105 return true;
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700106}
107
Brian Carlstromae826982011-11-09 01:33:42 -0800108bool ImageWriter::AllocMemory() {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700109 size_t size = source_space_->Size();
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700110 int prot = PROT_READ | PROT_WRITE;
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700111 size_t length = RoundUp(size, kPageSize);
Brian Carlstrom89521892011-12-07 22:05:07 -0800112 image_.reset(MemMap::MapAnonymous("image-writer-image", NULL, length, prot));
Elliott Hughes90a33692011-08-30 13:27:07 -0700113 if (image_.get() == NULL) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700114 LOG(ERROR) << "Failed to allocate memory for image file generation";
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700115 return false;
116 }
117 return true;
118}
119
Ian Rogersd418eda2012-01-30 12:14:28 -0800120void ImageWriter::ComputeLazyFieldsForImageClasses() {
121 Runtime* runtime = Runtime::Current();
122 ClassLinker* class_linker = runtime->GetClassLinker();
123 class_linker->VisitClasses(ComputeLazyFieldsForClassesVisitor, NULL);
124}
125
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700126bool ImageWriter::ComputeLazyFieldsForClassesVisitor(Class* c, void* /*arg*/) {
127 c->ComputeName();
Ian Rogersd418eda2012-01-30 12:14:28 -0800128 return true;
129}
130
Ian Rogersd1f1bf02012-02-26 16:59:20 -0800131void ImageWriter::ComputeEagerResolvedStringsCallback(Object* obj, void* arg) {
132 if (!obj->GetClass()->IsStringClass()) {
133 return;
134 }
135 String* string = obj->AsString();
136 std::string utf8_string(string->ToModifiedUtf8());
137 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
138 ClassLinker* linker = Runtime::Current()->GetClassLinker();
139 typedef Set::const_iterator CacheIt; // TODO: C++0x auto
140 for (CacheIt it = writer->dex_caches_.begin(), end = writer->dex_caches_.end(); it != end; ++it) {
141 DexCache* dex_cache = *it;
142 const DexFile& dex_file = linker->FindDexFile(dex_cache);
143 const DexFile::StringId* string_id = dex_file.FindStringId(utf8_string);
144 if (string_id != NULL) {
145 // This string occurs in this dex file, assign the dex cache entry.
146 uint32_t string_idx = dex_file.GetIndexForStringId(*string_id);
147 if (dex_cache->GetResolvedString(string_idx) == NULL) {
148 dex_cache->SetResolvedString(string_idx, string);
149 }
150 }
151 }
152}
153
154void ImageWriter::ComputeEagerResolvedStrings() {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800155 HeapBitmap* heap_bitmap = Runtime::Current()->GetHeap()->GetLiveBits();
Ian Rogersd1f1bf02012-02-26 16:59:20 -0800156 DCHECK(heap_bitmap != NULL);
157 heap_bitmap->Walk(ComputeEagerResolvedStringsCallback, this); // TODO: add Space-limited Walk
158}
159
Brian Carlstromae826982011-11-09 01:33:42 -0800160bool ImageWriter::IsImageClass(const Class* klass) {
161 if (image_classes_ == NULL) {
162 return true;
163 }
164 while (klass->IsArrayClass()) {
165 klass = klass->GetComponentType();
166 }
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800167 if (klass->IsPrimitive()) {
Brian Carlstromae826982011-11-09 01:33:42 -0800168 return true;
169 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800170 const std::string descriptor(ClassHelper(klass).GetDescriptor());
Brian Carlstromae826982011-11-09 01:33:42 -0800171 return image_classes_->find(descriptor) != image_classes_->end();
172}
173
174
175struct NonImageClasses {
176 ImageWriter* image_writer;
177 std::set<std::string>* non_image_classes;
178};
179
180void ImageWriter::PruneNonImageClasses() {
181 if (image_classes_ == NULL) {
182 return;
183 }
184 Runtime* runtime = Runtime::Current();
185 ClassLinker* class_linker = runtime->GetClassLinker();
186
187 std::set<std::string> non_image_classes;
188 NonImageClasses context;
189 context.image_writer = this;
190 context.non_image_classes = &non_image_classes;
191 class_linker->VisitClasses(NonImageClassesVisitor, &context);
192
193 typedef std::set<std::string>::const_iterator ClassIt; // TODO: C++0x auto
194 for (ClassIt it = non_image_classes.begin(), end = non_image_classes.end(); it != end; ++it) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800195 class_linker->RemoveClass((*it).c_str(), NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800196 }
197
Ian Rogers19846512012-02-24 11:42:47 -0800198 Method* resolution_method = runtime->GetResolutionMethod();
Brian Carlstromae826982011-11-09 01:33:42 -0800199 typedef Set::const_iterator CacheIt; // TODO: C++0x auto
200 for (CacheIt it = dex_caches_.begin(), end = dex_caches_.end(); it != end; ++it) {
201 DexCache* dex_cache = *it;
202 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
203 Class* klass = dex_cache->GetResolvedType(i);
204 if (klass != NULL && !IsImageClass(klass)) {
205 dex_cache->SetResolvedType(i, NULL);
206 dex_cache->GetInitializedStaticStorage()->Set(i, NULL);
207 }
208 }
209 for (size_t i = 0; i < dex_cache->NumResolvedMethods(); i++) {
210 Method* method = dex_cache->GetResolvedMethod(i);
211 if (method != NULL && !IsImageClass(method->GetDeclaringClass())) {
Ian Rogers19846512012-02-24 11:42:47 -0800212 dex_cache->SetResolvedMethod(i, resolution_method);
Brian Carlstromae826982011-11-09 01:33:42 -0800213 }
214 }
215 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
216 Field* field = dex_cache->GetResolvedField(i);
217 if (field != NULL && !IsImageClass(field->GetDeclaringClass())) {
218 dex_cache->SetResolvedField(i, NULL);
219 }
220 }
221 }
222}
223
224bool ImageWriter::NonImageClassesVisitor(Class* klass, void* arg) {
225 NonImageClasses* context = reinterpret_cast<NonImageClasses*>(arg);
226 if (!context->image_writer->IsImageClass(klass)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800227 context->non_image_classes->insert(ClassHelper(klass).GetDescriptor());
Brian Carlstromae826982011-11-09 01:33:42 -0800228 }
229 return true;
230}
231
232void ImageWriter::CheckNonImageClassesRemoved() {
233 if (image_classes_ == NULL) {
234 return;
235 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800236 Runtime::Current()->GetHeap()->GetLiveBits()->Walk(CheckNonImageClassesRemovedCallback, this);
Brian Carlstromae826982011-11-09 01:33:42 -0800237}
238
239void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
240 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
241 if (!obj->IsClass()) {
242 return;
243 }
244 Class* klass = obj->AsClass();
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800245 if (!image_writer->IsImageClass(klass)) {
246 image_writer->DumpImageClasses();
247 CHECK(image_writer->IsImageClass(klass)) << ClassHelper(klass).GetDescriptor()
248 << " " << PrettyDescriptor(klass);
249 }
250}
251
252void ImageWriter::DumpImageClasses() {
253 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
254 for (It it = image_classes_->begin(), end = image_classes_->end(); it != end; ++it) {
255 LOG(INFO) << " " << *it;
256 }
Brian Carlstromae826982011-11-09 01:33:42 -0800257}
258
Brian Carlstrom78128a62011-09-15 17:21:19 -0700259void ImageWriter::CalculateNewObjectOffsetsCallback(Object* obj, void* arg) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700260 DCHECK(obj != NULL);
261 DCHECK(arg != NULL);
262 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700263 if (!image_writer->InSourceSpace(obj)) {
264 return;
265 }
Brian Carlstromc74255f2011-09-11 22:47:39 -0700266
267 // if it is a string, we want to intern it if its not interned.
Elliott Hughesdbb40792011-11-18 17:05:22 -0800268 if (obj->GetClass()->IsStringClass()) {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700269 // we must be an interned string that was forward referenced and already assigned
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800270 if (image_writer->IsImageOffsetAssigned(obj)) {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700271 DCHECK_EQ(obj, obj->AsString()->Intern());
272 return;
273 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700274 SirtRef<String> interned(obj->AsString()->Intern());
275 if (obj != interned.get()) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800276 if (!image_writer->IsImageOffsetAssigned(interned.get())) {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700277 // interned obj is after us, allocate its location early
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700278 image_writer->AssignImageOffset(interned.get());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700279 }
280 // point those looking for this object to the interned version.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800281 image_writer->SetImageOffset(obj, image_writer->GetImageOffset(interned.get()));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700282 return;
283 }
284 // else (obj == interned), nothing to do but fall through to the normal case
285 }
286
287 image_writer->AssignImageOffset(obj);
Brian Carlstrom4e777d42011-08-15 13:53:52 -0700288}
289
Brian Carlstrome24fa612011-09-29 00:53:55 -0700290ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
Brian Carlstrom16192862011-09-12 17:50:06 -0700291 Runtime* runtime = Runtime::Current();
292 ClassLinker* class_linker = runtime->GetClassLinker();
293 Class* object_array_class = class_linker->FindSystemClass("[Ljava/lang/Object;");
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700294
295 // build an Object[] of all the DexCaches used in the source_space_
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700296 ObjectArray<Object>* dex_caches = ObjectArray<Object>::Alloc(object_array_class,
Brian Carlstromae826982011-11-09 01:33:42 -0800297 dex_caches_.size());
298 int i = 0;
299 typedef Set::const_iterator It; // TODO: C++0x auto
300 for (It it = dex_caches_.begin(), end = dex_caches_.end(); it != end; ++it, ++i) {
301 dex_caches->Set(i, *it);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700302 }
303
304 // build an Object[] of the roots needed to restore the runtime
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700305 SirtRef<ObjectArray<Object> > image_roots(
306 ObjectArray<Object>::Alloc(object_array_class, ImageHeader::kImageRootsMax));
Ian Rogers169c9a72011-11-13 20:13:17 -0800307 image_roots->Set(ImageHeader::kJniStubArray, runtime->GetJniDlsymLookupStub());
Brian Carlstrome24fa612011-09-29 00:53:55 -0700308 image_roots->Set(ImageHeader::kAbstractMethodErrorStubArray,
309 runtime->GetAbstractMethodErrorStubArray());
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700310 image_roots->Set(ImageHeader::kStaticResolutionStubArray,
311 runtime->GetResolutionStubArray(Runtime::kStaticMethod));
312 image_roots->Set(ImageHeader::kUnknownMethodResolutionStubArray,
313 runtime->GetResolutionStubArray(Runtime::kUnknownMethod));
Ian Rogers19846512012-02-24 11:42:47 -0800314 image_roots->Set(ImageHeader::kResolutionMethod, runtime->GetResolutionMethod());
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700315 image_roots->Set(ImageHeader::kCalleeSaveMethod,
316 runtime->GetCalleeSaveMethod(Runtime::kSaveAll));
317 image_roots->Set(ImageHeader::kRefsOnlySaveMethod,
318 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly));
319 image_roots->Set(ImageHeader::kRefsAndArgsSaveMethod,
320 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs));
Brian Carlstrome24fa612011-09-29 00:53:55 -0700321 image_roots->Set(ImageHeader::kOatLocation,
322 String::AllocFromModifiedUtf8(oat_file_->GetLocation().c_str()));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700323 image_roots->Set(ImageHeader::kDexCaches,
324 dex_caches);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700325 image_roots->Set(ImageHeader::kClassRoots,
326 class_linker->GetClassRoots());
Brian Carlstrome24fa612011-09-29 00:53:55 -0700327 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
328 CHECK(image_roots->Get(i) != NULL);
329 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700330 return image_roots.get();
Brian Carlstrom16192862011-09-12 17:50:06 -0700331}
332
Brian Carlstrom4e777d42011-08-15 13:53:52 -0700333void ImageWriter::CalculateNewObjectOffsets() {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700334 SirtRef<ObjectArray<Object> > image_roots(CreateImageRoots());
Brian Carlstrom16192862011-09-12 17:50:06 -0700335
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800336 HeapBitmap* heap_bitmap = Runtime::Current()->GetHeap()->GetLiveBits();
Brian Carlstrom4e777d42011-08-15 13:53:52 -0700337 DCHECK(heap_bitmap != NULL);
Ian Rogers30fab402012-01-23 15:43:46 -0800338 DCHECK_EQ(0U, image_end_);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700339
Brian Carlstrom16192862011-09-12 17:50:06 -0700340 // leave space for the header, but do not write it yet, we need to
341 // know where image_roots is going to end up
Ian Rogers30fab402012-01-23 15:43:46 -0800342 image_end_ += RoundUp(sizeof(ImageHeader), 8); // 64-bit-alignment
Brian Carlstroma663ea52011-08-19 23:33:41 -0700343
Ian Rogers1351b672012-02-24 12:22:57 -0800344 heap_bitmap->InOrderWalk(CalculateNewObjectOffsetsCallback, this); // TODO: add Space-limited Walk
Ian Rogers30fab402012-01-23 15:43:46 -0800345 DCHECK_LT(image_end_, image_->Size());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700346
Brian Carlstrome24fa612011-09-29 00:53:55 -0700347 // Note that image_top_ is left at end of used space
Ian Rogers30fab402012-01-23 15:43:46 -0800348 oat_begin_ = image_begin_ + RoundUp(image_end_, kPageSize);
349 const byte* oat_limit = oat_begin_ + oat_file_->Size();
Brian Carlstrome24fa612011-09-29 00:53:55 -0700350
Brian Carlstrom16192862011-09-12 17:50:06 -0700351 // return to write header at start of image with future location of image_roots
Ian Rogers30fab402012-01-23 15:43:46 -0800352 ImageHeader image_header(reinterpret_cast<uint32_t>(image_begin_),
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700353 reinterpret_cast<uint32_t>(GetImageAddress(image_roots.get())),
Brian Carlstrome24fa612011-09-29 00:53:55 -0700354 oat_file_->GetOatHeader().GetChecksum(),
Ian Rogers30fab402012-01-23 15:43:46 -0800355 reinterpret_cast<uint32_t>(oat_begin_),
Brian Carlstrome24fa612011-09-29 00:53:55 -0700356 reinterpret_cast<uint32_t>(oat_limit));
Ian Rogers30fab402012-01-23 15:43:46 -0800357 memcpy(image_->Begin(), &image_header, sizeof(image_header));
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700358}
359
360void ImageWriter::CopyAndFixupObjects() {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800361 Heap* heap = Runtime::Current()->GetHeap();
362 HeapBitmap* heap_bitmap = heap->GetLiveBits();
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700363 DCHECK(heap_bitmap != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700364 // TODO: heap validation can't handle this fix up pass
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800365 heap->DisableObjectValidation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700366 heap_bitmap->Walk(CopyAndFixupObjectsCallback, this); // TODO: add Space-limited Walk
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700367}
368
Brian Carlstrom78128a62011-09-15 17:21:19 -0700369void ImageWriter::CopyAndFixupObjectsCallback(Object* object, void* arg) {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700370 DCHECK(object != NULL);
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700371 DCHECK(arg != NULL);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700372 const Object* obj = object;
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700373 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700374 if (!image_writer->InSourceSpace(object)) {
375 return;
376 }
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700377
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700378 // see GetLocalAddress for similar computation
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700379 size_t offset = image_writer->GetImageOffset(obj);
Ian Rogers30fab402012-01-23 15:43:46 -0800380 byte* dst = image_writer->image_->Begin() + offset;
Brian Carlstrom4873d462011-08-21 15:23:39 -0700381 const byte* src = reinterpret_cast<const byte*>(obj);
Elliott Hughes04b63fd2011-08-16 09:40:10 -0700382 size_t n = obj->SizeOf();
Ian Rogers30fab402012-01-23 15:43:46 -0800383 DCHECK_LT(offset + n, image_writer->image_->Size());
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700384 memcpy(dst, src, n);
385 Object* copy = reinterpret_cast<Object*>(dst);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800386 copy->monitor_ = 0; // We may have inflated the lock during compilation.
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700387 image_writer->FixupObject(obj, copy);
388}
389
Brian Carlstrom4873d462011-08-21 15:23:39 -0700390void ImageWriter::FixupObject(const Object* orig, Object* copy) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700391 DCHECK(orig != NULL);
392 DCHECK(copy != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700393 copy->SetClass(down_cast<Class*>(GetImageAddress(orig->GetClass())));
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700394 // TODO: special case init of pointers to malloc data (or removal of these pointers)
395 if (orig->IsClass()) {
396 FixupClass(orig->AsClass(), down_cast<Class*>(copy));
397 } else if (orig->IsObjectArray()) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700398 FixupObjectArray(orig->AsObjectArray<Object>(), down_cast<ObjectArray<Object>*>(copy));
Brian Carlstrom16192862011-09-12 17:50:06 -0700399 } else if (orig->IsMethod()) {
400 FixupMethod(orig->AsMethod(), down_cast<Method*>(copy));
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700401 } else {
402 FixupInstanceFields(orig, copy);
403 }
404}
405
Brian Carlstrom4873d462011-08-21 15:23:39 -0700406void ImageWriter::FixupClass(const Class* orig, Class* copy) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700407 FixupInstanceFields(orig, copy);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700408 FixupStaticFields(orig, copy);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700409}
410
Brian Carlstrom4873d462011-08-21 15:23:39 -0700411void ImageWriter::FixupMethod(const Method* orig, Method* copy) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700412 FixupInstanceFields(orig, copy);
Brian Carlstrome24fa612011-09-29 00:53:55 -0700413
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700414 // OatWriter replaces the code_ and invoke_stub_ with offset values.
Ian Rogers30fab402012-01-23 15:43:46 -0800415 // Here we readjust to a pointer relative to oat_begin_
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700416
417 // Every type of method can have an invoke stub
418 uint32_t invoke_stub_offset = orig->GetOatInvokeStubOffset();
Brian Carlstromae826982011-11-09 01:33:42 -0800419 const byte* invoke_stub = GetOatAddress(invoke_stub_offset);
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700420 copy->invoke_stub_ = reinterpret_cast<const Method::InvokeStub*>(invoke_stub);
421
422 if (orig->IsAbstract()) {
423 // Abstract methods are pointed to a stub that will throw AbstractMethodError if they are called
424 ByteArray* orig_ame_stub_array_ = Runtime::Current()->GetAbstractMethodErrorStubArray();
425 ByteArray* copy_ame_stub_array_ = down_cast<ByteArray*>(GetImageAddress(orig_ame_stub_array_));
426 copy->code_ = copy_ame_stub_array_->GetData();
427 return;
428 }
429
Ian Rogers19846512012-02-24 11:42:47 -0800430 if (orig == Runtime::Current()->GetResolutionMethod()) {
431 // The resolution stub's code points at the unknown resolution trampoline
432 ByteArray* orig_res_stub_array_ =
433 Runtime::Current()->GetResolutionStubArray(Runtime::kUnknownMethod);
434 CHECK(orig->GetCode() == orig_res_stub_array_->GetData());
435 ByteArray* copy_res_stub_array_ = down_cast<ByteArray*>(GetImageAddress(orig_res_stub_array_));
436 copy->code_ = copy_res_stub_array_->GetData();
437 return;
438 }
439
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700440 // Non-abstract methods typically have code
441 uint32_t code_offset = orig->GetOatCodeOffset();
Ian Rogers19846512012-02-24 11:42:47 -0800442 const byte* code = NULL;
443 if (orig->IsStatic()) {
444 // Static methods may point at the resolution trampoline stub
445 ByteArray* orig_res_stub_array_ =
446 Runtime::Current()->GetResolutionStubArray(Runtime::kStaticMethod);
447 if (reinterpret_cast<int8_t*>(code_offset) == orig_res_stub_array_->GetData()) {
448 ByteArray* copy_res_stub_array_ = down_cast<ByteArray*>(GetImageAddress(orig_res_stub_array_));
449 code = reinterpret_cast<const byte*>(copy_res_stub_array_->GetData());
450 }
451 }
452 if (code == NULL) {
453 code = GetOatAddress(code_offset);
454 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700455 copy->code_ = code;
456
Brian Carlstrom16192862011-09-12 17:50:06 -0700457 if (orig->IsNative()) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700458 // The native method's pointer is directed to a stub to lookup via dlsym.
459 // Note this is not the code_ pointer, that is handled above.
Ian Rogers169c9a72011-11-13 20:13:17 -0800460 ByteArray* orig_jni_stub_array_ = Runtime::Current()->GetJniDlsymLookupStub();
Brian Carlstrom16192862011-09-12 17:50:06 -0700461 ByteArray* copy_jni_stub_array_ = down_cast<ByteArray*>(GetImageAddress(orig_jni_stub_array_));
462 copy->native_method_ = copy_jni_stub_array_->GetData();
463 } else {
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700464 // normal (non-abstract non-native) methods have mapping tables to relocate
465 uint32_t mapping_table_off = orig->GetOatMappingTableOffset();
Brian Carlstromae826982011-11-09 01:33:42 -0800466 const byte* mapping_table = GetOatAddress(mapping_table_off);
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700467 copy->mapping_table_ = reinterpret_cast<const uint32_t*>(mapping_table);
468
469 uint32_t vmap_table_offset = orig->GetOatVmapTableOffset();
Brian Carlstromae826982011-11-09 01:33:42 -0800470 const byte* vmap_table = GetOatAddress(vmap_table_offset);
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700471 copy->vmap_table_ = reinterpret_cast<const uint16_t*>(vmap_table);
Brian Carlstrome7d856b2012-01-11 18:10:55 -0800472
473 uint32_t gc_map_offset = orig->GetOatGcMapOffset();
474 const byte* gc_map = GetOatAddress(gc_map_offset);
475 copy->gc_map_ = reinterpret_cast<const uint8_t*>(gc_map);
Brian Carlstrom16192862011-09-12 17:50:06 -0700476 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700477}
478
Brian Carlstrom4873d462011-08-21 15:23:39 -0700479void ImageWriter::FixupObjectArray(const ObjectArray<Object>* orig, ObjectArray<Object>* copy) {
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700480 for (int32_t i = 0; i < orig->GetLength(); ++i) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700481 const Object* element = orig->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700482 copy->SetWithoutChecks(i, GetImageAddress(element));
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700483 }
484}
485
Brian Carlstrom4873d462011-08-21 15:23:39 -0700486void ImageWriter::FixupInstanceFields(const Object* orig, Object* copy) {
487 DCHECK(orig != NULL);
488 DCHECK(copy != NULL);
489 Class* klass = orig->GetClass();
490 DCHECK(klass != NULL);
491 FixupFields(orig,
492 copy,
493 klass->GetReferenceInstanceOffsets(),
494 false);
495}
496
497void ImageWriter::FixupStaticFields(const Class* orig, Class* copy) {
498 DCHECK(orig != NULL);
499 DCHECK(copy != NULL);
500 FixupFields(orig,
501 copy,
502 orig->GetReferenceStaticOffsets(),
503 true);
504}
505
506void ImageWriter::FixupFields(const Object* orig,
507 Object* copy,
508 uint32_t ref_offsets,
509 bool is_static) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700510 if (ref_offsets != CLASS_WALK_SUPER) {
511 // Found a reference offset bitmap. Fixup the specified offsets.
512 while (ref_offsets != 0) {
513 size_t right_shift = CLZ(ref_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700514 MemberOffset byte_offset = CLASS_OFFSET_FROM_CLZ(right_shift);
515 const Object* ref = orig->GetFieldObject<const Object*>(byte_offset, false);
516 copy->SetFieldObject(byte_offset, GetImageAddress(ref), false);
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700517 ref_offsets &= ~(CLASS_HIGH_BIT >> right_shift);
518 }
519 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700520 // There is no reference offset bitmap. In the non-static case,
521 // walk up the class inheritance hierarchy and find reference
522 // offsets the hard way. In the static case, just consider this
523 // class.
524 for (const Class *klass = is_static ? orig->AsClass() : orig->GetClass();
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700525 klass != NULL;
Brian Carlstrom4873d462011-08-21 15:23:39 -0700526 klass = is_static ? NULL : klass->GetSuperClass()) {
527 size_t num_reference_fields = (is_static
528 ? klass->NumReferenceStaticFields()
529 : klass->NumReferenceInstanceFields());
530 for (size_t i = 0; i < num_reference_fields; ++i) {
531 Field* field = (is_static
532 ? klass->GetStaticField(i)
533 : klass->GetInstanceField(i));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700534 MemberOffset field_offset = field->GetOffset();
535 const Object* ref = orig->GetFieldObject<const Object*>(field_offset, false);
536 copy->SetFieldObject(field_offset, GetImageAddress(ref), false);
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700537 }
538 }
539 }
540}
541
Brian Carlstromf5822582012-03-19 22:34:31 -0700542static Method* GetReferrerMethod(const Compiler::PatchInformation* patch) {
543 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
544 Method* method = class_linker->ResolveMethod(patch->GetDexFile(),
545 patch->GetReferrerMethodIdx(),
546 patch->GetDexCache(),
547 NULL,
548 patch->GetReferrerIsDirect());
549 CHECK(method != NULL)
550 << patch->GetDexFile().GetLocation() << " " << patch->GetReferrerMethodIdx();
Brian Carlstrom0637e272012-03-20 01:07:52 -0700551 CHECK(!method->IsRuntimeMethod())
552 << patch->GetDexFile().GetLocation() << " " << patch->GetReferrerMethodIdx();
553 CHECK(patch->GetDexCache()->GetResolvedMethods()->Get(patch->GetReferrerMethodIdx()) == method)
554 << patch->GetDexFile().GetLocation() << " " << patch->GetReferrerMethodIdx() << " "
555 << PrettyMethod(patch->GetDexCache()->GetResolvedMethods()->Get(patch->GetReferrerMethodIdx())) << " "
556 << PrettyMethod(method);
Brian Carlstromf5822582012-03-19 22:34:31 -0700557 return method;
558}
559
560static Method* GetTargetMethod(const Compiler::PatchInformation* patch) {
561 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
562 Method* method = class_linker->ResolveMethod(patch->GetDexFile(),
563 patch->GetTargetMethodIdx(),
564 patch->GetDexCache(),
565 NULL,
566 patch->GetTargetIsDirect());
567 CHECK(method != NULL)
568 << patch->GetDexFile().GetLocation() << " " << patch->GetTargetMethodIdx();
Brian Carlstrom0637e272012-03-20 01:07:52 -0700569 CHECK(!method->IsRuntimeMethod())
570 << patch->GetDexFile().GetLocation() << " " << patch->GetTargetMethodIdx();
571 CHECK(patch->GetDexCache()->GetResolvedMethods()->Get(patch->GetTargetMethodIdx()) == method)
572 << patch->GetDexFile().GetLocation() << " " << patch->GetReferrerMethodIdx() << " "
573 << PrettyMethod(patch->GetDexCache()->GetResolvedMethods()->Get(patch->GetTargetMethodIdx())) << " "
574 << PrettyMethod(method);
Brian Carlstromf5822582012-03-19 22:34:31 -0700575 return method;
576}
577
578void ImageWriter::PatchOatCodeAndMethods(const Compiler& compiler) {
579 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
580
581 const std::vector<const Compiler::PatchInformation*>& code_to_patch = compiler.GetCodeToPatch();
582 for (size_t i = 0; i < code_to_patch.size(); i++) {
583 const Compiler::PatchInformation* patch = code_to_patch[i];
584 Method* target = GetTargetMethod(patch);
585 uint32_t code = reinterpret_cast<uint32_t>(class_linker->GetOatCodeFor(target));
586 uint32_t code_base = reinterpret_cast<uint32_t>(&oat_file_->GetOatHeader());
587 uint32_t code_offset = code - code_base;
588 SetPatchLocation(patch, reinterpret_cast<uint32_t>(GetOatAddress(code_offset)));
589 }
590
591 const std::vector<const Compiler::PatchInformation*>& methods_to_patch
592 = compiler.GetMethodsToPatch();
593 for (size_t i = 0; i < methods_to_patch.size(); i++) {
594 const Compiler::PatchInformation* patch = methods_to_patch[i];
595 Method* target = GetTargetMethod(patch);
596 SetPatchLocation(patch, reinterpret_cast<uint32_t>(GetImageAddress(target)));
597 }
598}
599
600void ImageWriter::SetPatchLocation(const Compiler::PatchInformation* patch, uint32_t value) {
601 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
602 Method* method = GetReferrerMethod(patch);
603 // Goodbye const, we are about to modify some code.
604 void* code = const_cast<void*>(class_linker->GetOatCodeFor(method));
605 // TODO: make this Thumb2 specific
606 uint8_t* base = reinterpret_cast<uint8_t*>(reinterpret_cast<uint32_t>(code) & ~0x1);
607 uint32_t* patch_location = reinterpret_cast<uint32_t*>(base + patch->GetLiteralOffset());
608#ifndef NDEBUG
609 const DexFile::MethodId& id = patch->GetDexFile().GetMethodId(patch->GetTargetMethodIdx());
610 uint32_t expected = reinterpret_cast<uint32_t>(&id);
611 uint32_t actual = *patch_location;
612 CHECK(actual == expected || actual == value) << std::hex
613 << "actual=" << actual
614 << "expected=" << expected
615 << "value=" << value;
616#endif
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700617 *patch_location = value;
Brian Carlstromf5822582012-03-19 22:34:31 -0700618}
619
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700620} // namespace art