blob: 589d3d730fd9f0ef408592d5abd72c8c977cc407 [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
Brian Carlstrom6cd40e52012-05-03 14:15:11 -070019#include <sys/stat.h>
Elliott Hughes90a33692011-08-30 13:27:07 -070020
Brian Carlstromdb4d5402011-08-09 12:18:28 -070021#include <vector>
22
Brian Carlstroma663ea52011-08-19 23:33:41 -070023#include "class_linker.h"
Brian Carlstrom1f870082011-08-23 16:02:11 -070024#include "class_loader.h"
Brian Carlstromae826982011-11-09 01:33:42 -080025#include "compiled_method.h"
Brian Carlstromf5822582012-03-19 22:34:31 -070026#include "compiler.h"
Elliott Hughes90a33692011-08-30 13:27:07 -070027#include "dex_cache.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070028#include "file.h"
29#include "globals.h"
30#include "heap.h"
Brian Carlstrom4a289ed2011-08-16 17:17:49 -070031#include "image.h"
Brian Carlstroma663ea52011-08-19 23:33:41 -070032#include "intern_table.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070033#include "logging.h"
Logan Chien0c717dd2012-03-28 18:31:07 +080034#include "oat_file.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070035#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"
Elliott Hughesa168c832012-06-12 15:34:20 -070039#include "UniquePtr.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070040#include "utils.h"
41
42namespace art {
43
Brian Carlstroma004aa92012-02-08 18:05:09 -080044bool ImageWriter::Write(const std::string& image_filename,
Ian Rogers30fab402012-01-23 15:43:46 -080045 uintptr_t image_begin,
Brian Carlstromae826982011-11-09 01:33:42 -080046 const std::string& oat_filename,
Brian Carlstromf5822582012-03-19 22:34:31 -070047 const std::string& oat_location,
48 const Compiler& compiler) {
Brian Carlstroma004aa92012-02-08 18:05:09 -080049 CHECK(!image_filename.empty());
Brian Carlstromaded5f72011-10-07 17:15:04 -070050
Ian Rogers30fab402012-01-23 15:43:46 -080051 CHECK_NE(image_begin, 0U);
52 image_begin_ = reinterpret_cast<byte*>(image_begin);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070053
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080054 Heap* heap = Runtime::Current()->GetHeap();
Brian Carlstromfddf6f62012-03-15 16:56:45 -070055 source_space_ = heap->GetAllocSpace();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -070056
Brian Carlstromae826982011-11-09 01:33:42 -080057 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
58 const std::vector<DexCache*>& all_dex_caches = class_linker->GetDexCaches();
59 for (size_t i = 0; i < all_dex_caches.size(); i++) {
60 DexCache* dex_cache = all_dex_caches[i];
61 if (InSourceSpace(dex_cache)) {
62 dex_caches_.insert(dex_cache);
63 }
64 }
65
Logan Chien0c717dd2012-03-28 18:31:07 +080066 oat_file_ = OatFile::Open(oat_filename, oat_location, NULL,
67 OatFile::kRelocNone, true);
Brian Carlstromf5822582012-03-19 22:34:31 -070068 if (oat_file_ == NULL) {
Brian Carlstrome24fa612011-09-29 00:53:55 -070069 LOG(ERROR) << "Failed to open oat file " << oat_filename;
70 return false;
71 }
Elliott Hughesb25c3f62012-03-26 16:35:06 -070072 class_linker->RegisterOatFile(*oat_file_);
Brian Carlstrome24fa612011-09-29 00:53:55 -070073
Ian Rogersd857b632012-02-06 20:42:33 -080074 PruneNonImageClasses(); // Remove junk
75 ComputeLazyFieldsForImageClasses(); // Add useful information
Ian Rogersd1f1bf02012-02-26 16:59:20 -080076 ComputeEagerResolvedStrings();
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080077 heap->CollectGarbage(false); // Remove garbage
78 heap->GetAllocSpace()->Trim(); // Trim size of source_space
Brian Carlstromae826982011-11-09 01:33:42 -080079 if (!AllocMemory()) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -070080 return false;
81 }
Brian Carlstromae826982011-11-09 01:33:42 -080082#ifndef NDEBUG
83 CheckNonImageClassesRemoved();
84#endif
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080085 heap->DisableCardMarking();
Brian Carlstromdb4d5402011-08-09 12:18:28 -070086 CalculateNewObjectOffsets();
87 CopyAndFixupObjects();
Brian Carlstromf5822582012-03-19 22:34:31 -070088 PatchOatCodeAndMethods(compiler);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -070089
Brian Carlstroma004aa92012-02-08 18:05:09 -080090 UniquePtr<File> file(OS::OpenFile(image_filename.c_str(), true));
Elliott Hughes90a33692011-08-30 13:27:07 -070091 if (file.get() == NULL) {
Brian Carlstrome24fa612011-09-29 00:53:55 -070092 LOG(ERROR) << "Failed to open image file " << image_filename;
Brian Carlstromdb4d5402011-08-09 12:18:28 -070093 return false;
94 }
Brian Carlstrom6cd40e52012-05-03 14:15:11 -070095 if (fchmod(file->Fd(), 0644) != 0) {
96 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
97 return EXIT_FAILURE;
98 }
Ian Rogers30fab402012-01-23 15:43:46 -080099 bool success = file->WriteFully(image_->Begin(), image_end_);
Brian Carlstrome24fa612011-09-29 00:53:55 -0700100 if (!success) {
101 PLOG(ERROR) << "Failed to write image file " << image_filename;
102 return false;
103 }
104 return true;
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700105}
106
Brian Carlstromae826982011-11-09 01:33:42 -0800107bool ImageWriter::AllocMemory() {
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700108 size_t size = source_space_->Size();
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700109 int prot = PROT_READ | PROT_WRITE;
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700110 size_t length = RoundUp(size, kPageSize);
Brian Carlstrom89521892011-12-07 22:05:07 -0800111 image_.reset(MemMap::MapAnonymous("image-writer-image", NULL, length, prot));
Elliott Hughes90a33692011-08-30 13:27:07 -0700112 if (image_.get() == NULL) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700113 LOG(ERROR) << "Failed to allocate memory for image file generation";
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700114 return false;
115 }
116 return true;
117}
118
Ian Rogersd418eda2012-01-30 12:14:28 -0800119void ImageWriter::ComputeLazyFieldsForImageClasses() {
120 Runtime* runtime = Runtime::Current();
121 ClassLinker* class_linker = runtime->GetClassLinker();
122 class_linker->VisitClasses(ComputeLazyFieldsForClassesVisitor, NULL);
123}
124
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700125bool ImageWriter::ComputeLazyFieldsForClassesVisitor(Class* c, void* /*arg*/) {
126 c->ComputeName();
Ian Rogersd418eda2012-01-30 12:14:28 -0800127 return true;
128}
129
Ian Rogersd1f1bf02012-02-26 16:59:20 -0800130void ImageWriter::ComputeEagerResolvedStringsCallback(Object* obj, void* arg) {
131 if (!obj->GetClass()->IsStringClass()) {
132 return;
133 }
134 String* string = obj->AsString();
135 std::string utf8_string(string->ToModifiedUtf8());
136 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
137 ClassLinker* linker = Runtime::Current()->GetClassLinker();
138 typedef Set::const_iterator CacheIt; // TODO: C++0x auto
139 for (CacheIt it = writer->dex_caches_.begin(), end = writer->dex_caches_.end(); it != end; ++it) {
140 DexCache* dex_cache = *it;
141 const DexFile& dex_file = linker->FindDexFile(dex_cache);
142 const DexFile::StringId* string_id = dex_file.FindStringId(utf8_string);
143 if (string_id != NULL) {
144 // This string occurs in this dex file, assign the dex cache entry.
145 uint32_t string_idx = dex_file.GetIndexForStringId(*string_id);
146 if (dex_cache->GetResolvedString(string_idx) == NULL) {
147 dex_cache->SetResolvedString(string_idx, string);
148 }
149 }
150 }
151}
152
153void ImageWriter::ComputeEagerResolvedStrings() {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800154 HeapBitmap* heap_bitmap = Runtime::Current()->GetHeap()->GetLiveBits();
Ian Rogersd1f1bf02012-02-26 16:59:20 -0800155 DCHECK(heap_bitmap != NULL);
156 heap_bitmap->Walk(ComputeEagerResolvedStringsCallback, this); // TODO: add Space-limited Walk
157}
158
Brian Carlstromae826982011-11-09 01:33:42 -0800159bool ImageWriter::IsImageClass(const Class* klass) {
160 if (image_classes_ == NULL) {
161 return true;
162 }
163 while (klass->IsArrayClass()) {
164 klass = klass->GetComponentType();
165 }
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800166 if (klass->IsPrimitive()) {
Brian Carlstromae826982011-11-09 01:33:42 -0800167 return true;
168 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800169 const std::string descriptor(ClassHelper(klass).GetDescriptor());
Brian Carlstromae826982011-11-09 01:33:42 -0800170 return image_classes_->find(descriptor) != image_classes_->end();
171}
172
173
174struct NonImageClasses {
175 ImageWriter* image_writer;
176 std::set<std::string>* non_image_classes;
177};
178
179void ImageWriter::PruneNonImageClasses() {
180 if (image_classes_ == NULL) {
181 return;
182 }
183 Runtime* runtime = Runtime::Current();
184 ClassLinker* class_linker = runtime->GetClassLinker();
185
186 std::set<std::string> non_image_classes;
187 NonImageClasses context;
188 context.image_writer = this;
189 context.non_image_classes = &non_image_classes;
190 class_linker->VisitClasses(NonImageClassesVisitor, &context);
191
192 typedef std::set<std::string>::const_iterator ClassIt; // TODO: C++0x auto
193 for (ClassIt it = non_image_classes.begin(), end = non_image_classes.end(); it != end; ++it) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800194 class_linker->RemoveClass((*it).c_str(), NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800195 }
196
Ian Rogers19846512012-02-24 11:42:47 -0800197 Method* resolution_method = runtime->GetResolutionMethod();
Brian Carlstromae826982011-11-09 01:33:42 -0800198 typedef Set::const_iterator CacheIt; // TODO: C++0x auto
199 for (CacheIt it = dex_caches_.begin(), end = dex_caches_.end(); it != end; ++it) {
200 DexCache* dex_cache = *it;
201 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
202 Class* klass = dex_cache->GetResolvedType(i);
203 if (klass != NULL && !IsImageClass(klass)) {
204 dex_cache->SetResolvedType(i, NULL);
205 dex_cache->GetInitializedStaticStorage()->Set(i, NULL);
206 }
207 }
208 for (size_t i = 0; i < dex_cache->NumResolvedMethods(); i++) {
209 Method* method = dex_cache->GetResolvedMethod(i);
210 if (method != NULL && !IsImageClass(method->GetDeclaringClass())) {
Ian Rogers19846512012-02-24 11:42:47 -0800211 dex_cache->SetResolvedMethod(i, resolution_method);
Brian Carlstromae826982011-11-09 01:33:42 -0800212 }
213 }
214 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
215 Field* field = dex_cache->GetResolvedField(i);
216 if (field != NULL && !IsImageClass(field->GetDeclaringClass())) {
217 dex_cache->SetResolvedField(i, NULL);
218 }
219 }
220 }
221}
222
223bool ImageWriter::NonImageClassesVisitor(Class* klass, void* arg) {
224 NonImageClasses* context = reinterpret_cast<NonImageClasses*>(arg);
225 if (!context->image_writer->IsImageClass(klass)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800226 context->non_image_classes->insert(ClassHelper(klass).GetDescriptor());
Brian Carlstromae826982011-11-09 01:33:42 -0800227 }
228 return true;
229}
230
231void ImageWriter::CheckNonImageClassesRemoved() {
232 if (image_classes_ == NULL) {
233 return;
234 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800235 Runtime::Current()->GetHeap()->GetLiveBits()->Walk(CheckNonImageClassesRemovedCallback, this);
Brian Carlstromae826982011-11-09 01:33:42 -0800236}
237
238void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
239 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
240 if (!obj->IsClass()) {
241 return;
242 }
243 Class* klass = obj->AsClass();
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800244 if (!image_writer->IsImageClass(klass)) {
245 image_writer->DumpImageClasses();
246 CHECK(image_writer->IsImageClass(klass)) << ClassHelper(klass).GetDescriptor()
247 << " " << PrettyDescriptor(klass);
248 }
249}
250
251void ImageWriter::DumpImageClasses() {
252 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
253 for (It it = image_classes_->begin(), end = image_classes_->end(); it != end; ++it) {
254 LOG(INFO) << " " << *it;
255 }
Brian Carlstromae826982011-11-09 01:33:42 -0800256}
257
Brian Carlstrom78128a62011-09-15 17:21:19 -0700258void ImageWriter::CalculateNewObjectOffsetsCallback(Object* obj, void* arg) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700259 DCHECK(obj != NULL);
260 DCHECK(arg != NULL);
261 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700262 if (!image_writer->InSourceSpace(obj)) {
263 return;
264 }
Brian Carlstromc74255f2011-09-11 22:47:39 -0700265
266 // if it is a string, we want to intern it if its not interned.
Elliott Hughesdbb40792011-11-18 17:05:22 -0800267 if (obj->GetClass()->IsStringClass()) {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700268 // we must be an interned string that was forward referenced and already assigned
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800269 if (image_writer->IsImageOffsetAssigned(obj)) {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700270 DCHECK_EQ(obj, obj->AsString()->Intern());
271 return;
272 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700273 SirtRef<String> interned(obj->AsString()->Intern());
274 if (obj != interned.get()) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800275 if (!image_writer->IsImageOffsetAssigned(interned.get())) {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700276 // interned obj is after us, allocate its location early
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700277 image_writer->AssignImageOffset(interned.get());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700278 }
279 // point those looking for this object to the interned version.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800280 image_writer->SetImageOffset(obj, image_writer->GetImageOffset(interned.get()));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700281 return;
282 }
283 // else (obj == interned), nothing to do but fall through to the normal case
284 }
285
286 image_writer->AssignImageOffset(obj);
Brian Carlstrom4e777d42011-08-15 13:53:52 -0700287}
288
Brian Carlstrome24fa612011-09-29 00:53:55 -0700289ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
Brian Carlstrom16192862011-09-12 17:50:06 -0700290 Runtime* runtime = Runtime::Current();
291 ClassLinker* class_linker = runtime->GetClassLinker();
292 Class* object_array_class = class_linker->FindSystemClass("[Ljava/lang/Object;");
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700293
294 // build an Object[] of all the DexCaches used in the source_space_
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700295 ObjectArray<Object>* dex_caches = ObjectArray<Object>::Alloc(object_array_class,
Brian Carlstromae826982011-11-09 01:33:42 -0800296 dex_caches_.size());
297 int i = 0;
298 typedef Set::const_iterator It; // TODO: C++0x auto
299 for (It it = dex_caches_.begin(), end = dex_caches_.end(); it != end; ++it, ++i) {
300 dex_caches->Set(i, *it);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700301 }
302
303 // build an Object[] of the roots needed to restore the runtime
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700304 SirtRef<ObjectArray<Object> > image_roots(
305 ObjectArray<Object>::Alloc(object_array_class, ImageHeader::kImageRootsMax));
Ian Rogers169c9a72011-11-13 20:13:17 -0800306 image_roots->Set(ImageHeader::kJniStubArray, runtime->GetJniDlsymLookupStub());
Brian Carlstrome24fa612011-09-29 00:53:55 -0700307 image_roots->Set(ImageHeader::kAbstractMethodErrorStubArray,
308 runtime->GetAbstractMethodErrorStubArray());
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700309 image_roots->Set(ImageHeader::kStaticResolutionStubArray,
310 runtime->GetResolutionStubArray(Runtime::kStaticMethod));
311 image_roots->Set(ImageHeader::kUnknownMethodResolutionStubArray,
312 runtime->GetResolutionStubArray(Runtime::kUnknownMethod));
Ian Rogers19846512012-02-24 11:42:47 -0800313 image_roots->Set(ImageHeader::kResolutionMethod, runtime->GetResolutionMethod());
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700314 image_roots->Set(ImageHeader::kCalleeSaveMethod,
315 runtime->GetCalleeSaveMethod(Runtime::kSaveAll));
316 image_roots->Set(ImageHeader::kRefsOnlySaveMethod,
317 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly));
318 image_roots->Set(ImageHeader::kRefsAndArgsSaveMethod,
319 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs));
Brian Carlstrome24fa612011-09-29 00:53:55 -0700320 image_roots->Set(ImageHeader::kOatLocation,
321 String::AllocFromModifiedUtf8(oat_file_->GetLocation().c_str()));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700322 image_roots->Set(ImageHeader::kDexCaches,
323 dex_caches);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700324 image_roots->Set(ImageHeader::kClassRoots,
325 class_linker->GetClassRoots());
Brian Carlstrome24fa612011-09-29 00:53:55 -0700326 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
327 CHECK(image_roots->Get(i) != NULL);
328 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700329 return image_roots.get();
Brian Carlstrom16192862011-09-12 17:50:06 -0700330}
331
Brian Carlstrom4e777d42011-08-15 13:53:52 -0700332void ImageWriter::CalculateNewObjectOffsets() {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700333 SirtRef<ObjectArray<Object> > image_roots(CreateImageRoots());
Brian Carlstrom16192862011-09-12 17:50:06 -0700334
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800335 HeapBitmap* heap_bitmap = Runtime::Current()->GetHeap()->GetLiveBits();
Brian Carlstrom4e777d42011-08-15 13:53:52 -0700336 DCHECK(heap_bitmap != NULL);
Ian Rogers30fab402012-01-23 15:43:46 -0800337 DCHECK_EQ(0U, image_end_);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700338
Brian Carlstrom16192862011-09-12 17:50:06 -0700339 // leave space for the header, but do not write it yet, we need to
340 // know where image_roots is going to end up
Ian Rogers30fab402012-01-23 15:43:46 -0800341 image_end_ += RoundUp(sizeof(ImageHeader), 8); // 64-bit-alignment
Brian Carlstroma663ea52011-08-19 23:33:41 -0700342
Ian Rogers1351b672012-02-24 12:22:57 -0800343 heap_bitmap->InOrderWalk(CalculateNewObjectOffsetsCallback, this); // TODO: add Space-limited Walk
Ian Rogers30fab402012-01-23 15:43:46 -0800344 DCHECK_LT(image_end_, image_->Size());
Brian Carlstroma663ea52011-08-19 23:33:41 -0700345
Brian Carlstrome24fa612011-09-29 00:53:55 -0700346 // Note that image_top_ is left at end of used space
Ian Rogers30fab402012-01-23 15:43:46 -0800347 oat_begin_ = image_begin_ + RoundUp(image_end_, kPageSize);
348 const byte* oat_limit = oat_begin_ + oat_file_->Size();
Brian Carlstrome24fa612011-09-29 00:53:55 -0700349
Brian Carlstrom16192862011-09-12 17:50:06 -0700350 // return to write header at start of image with future location of image_roots
Ian Rogers30fab402012-01-23 15:43:46 -0800351 ImageHeader image_header(reinterpret_cast<uint32_t>(image_begin_),
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700352 reinterpret_cast<uint32_t>(GetImageAddress(image_roots.get())),
Brian Carlstrome24fa612011-09-29 00:53:55 -0700353 oat_file_->GetOatHeader().GetChecksum(),
Ian Rogers30fab402012-01-23 15:43:46 -0800354 reinterpret_cast<uint32_t>(oat_begin_),
Brian Carlstrome24fa612011-09-29 00:53:55 -0700355 reinterpret_cast<uint32_t>(oat_limit));
Ian Rogers30fab402012-01-23 15:43:46 -0800356 memcpy(image_->Begin(), &image_header, sizeof(image_header));
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700357}
358
359void ImageWriter::CopyAndFixupObjects() {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800360 Heap* heap = Runtime::Current()->GetHeap();
361 HeapBitmap* heap_bitmap = heap->GetLiveBits();
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700362 DCHECK(heap_bitmap != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700363 // TODO: heap validation can't handle this fix up pass
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800364 heap->DisableObjectValidation();
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700365 heap_bitmap->Walk(CopyAndFixupObjectsCallback, this); // TODO: add Space-limited Walk
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700366}
367
Brian Carlstrom78128a62011-09-15 17:21:19 -0700368void ImageWriter::CopyAndFixupObjectsCallback(Object* object, void* arg) {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700369 DCHECK(object != NULL);
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700370 DCHECK(arg != NULL);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700371 const Object* obj = object;
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700372 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700373 if (!image_writer->InSourceSpace(object)) {
374 return;
375 }
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700376
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700377 // see GetLocalAddress for similar computation
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700378 size_t offset = image_writer->GetImageOffset(obj);
Ian Rogers30fab402012-01-23 15:43:46 -0800379 byte* dst = image_writer->image_->Begin() + offset;
Brian Carlstrom4873d462011-08-21 15:23:39 -0700380 const byte* src = reinterpret_cast<const byte*>(obj);
Elliott Hughes04b63fd2011-08-16 09:40:10 -0700381 size_t n = obj->SizeOf();
Ian Rogers30fab402012-01-23 15:43:46 -0800382 DCHECK_LT(offset + n, image_writer->image_->Size());
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700383 memcpy(dst, src, n);
384 Object* copy = reinterpret_cast<Object*>(dst);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800385 copy->monitor_ = 0; // We may have inflated the lock during compilation.
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700386 image_writer->FixupObject(obj, copy);
387}
388
Brian Carlstrom4873d462011-08-21 15:23:39 -0700389void ImageWriter::FixupObject(const Object* orig, Object* copy) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700390 DCHECK(orig != NULL);
391 DCHECK(copy != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700392 copy->SetClass(down_cast<Class*>(GetImageAddress(orig->GetClass())));
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700393 // TODO: special case init of pointers to malloc data (or removal of these pointers)
394 if (orig->IsClass()) {
395 FixupClass(orig->AsClass(), down_cast<Class*>(copy));
396 } else if (orig->IsObjectArray()) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700397 FixupObjectArray(orig->AsObjectArray<Object>(), down_cast<ObjectArray<Object>*>(copy));
Brian Carlstrom16192862011-09-12 17:50:06 -0700398 } else if (orig->IsMethod()) {
399 FixupMethod(orig->AsMethod(), down_cast<Method*>(copy));
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700400 } else {
401 FixupInstanceFields(orig, copy);
402 }
403}
404
Brian Carlstrom4873d462011-08-21 15:23:39 -0700405void ImageWriter::FixupClass(const Class* orig, Class* copy) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700406 FixupInstanceFields(orig, copy);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700407 FixupStaticFields(orig, copy);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700408}
409
Brian Carlstrom4873d462011-08-21 15:23:39 -0700410void ImageWriter::FixupMethod(const Method* orig, Method* copy) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700411 FixupInstanceFields(orig, copy);
Brian Carlstrome24fa612011-09-29 00:53:55 -0700412
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700413 // OatWriter replaces the code_ and invoke_stub_ with offset values.
Ian Rogers30fab402012-01-23 15:43:46 -0800414 // Here we readjust to a pointer relative to oat_begin_
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700415
416 // Every type of method can have an invoke stub
417 uint32_t invoke_stub_offset = orig->GetOatInvokeStubOffset();
Brian Carlstromae826982011-11-09 01:33:42 -0800418 const byte* invoke_stub = GetOatAddress(invoke_stub_offset);
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700419 copy->invoke_stub_ = reinterpret_cast<const Method::InvokeStub*>(invoke_stub);
420
421 if (orig->IsAbstract()) {
422 // Abstract methods are pointed to a stub that will throw AbstractMethodError if they are called
423 ByteArray* orig_ame_stub_array_ = Runtime::Current()->GetAbstractMethodErrorStubArray();
424 ByteArray* copy_ame_stub_array_ = down_cast<ByteArray*>(GetImageAddress(orig_ame_stub_array_));
425 copy->code_ = copy_ame_stub_array_->GetData();
426 return;
427 }
428
Ian Rogers19846512012-02-24 11:42:47 -0800429 if (orig == Runtime::Current()->GetResolutionMethod()) {
430 // The resolution stub's code points at the unknown resolution trampoline
431 ByteArray* orig_res_stub_array_ =
432 Runtime::Current()->GetResolutionStubArray(Runtime::kUnknownMethod);
433 CHECK(orig->GetCode() == orig_res_stub_array_->GetData());
434 ByteArray* copy_res_stub_array_ = down_cast<ByteArray*>(GetImageAddress(orig_res_stub_array_));
435 copy->code_ = copy_res_stub_array_->GetData();
436 return;
437 }
438
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700439 // Non-abstract methods typically have code
440 uint32_t code_offset = orig->GetOatCodeOffset();
Ian Rogers19846512012-02-24 11:42:47 -0800441 const byte* code = NULL;
442 if (orig->IsStatic()) {
443 // Static methods may point at the resolution trampoline stub
444 ByteArray* orig_res_stub_array_ =
445 Runtime::Current()->GetResolutionStubArray(Runtime::kStaticMethod);
446 if (reinterpret_cast<int8_t*>(code_offset) == orig_res_stub_array_->GetData()) {
447 ByteArray* copy_res_stub_array_ = down_cast<ByteArray*>(GetImageAddress(orig_res_stub_array_));
448 code = reinterpret_cast<const byte*>(copy_res_stub_array_->GetData());
449 }
450 }
451 if (code == NULL) {
452 code = GetOatAddress(code_offset);
453 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700454 copy->code_ = code;
455
Brian Carlstrom16192862011-09-12 17:50:06 -0700456 if (orig->IsNative()) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700457 // The native method's pointer is directed to a stub to lookup via dlsym.
458 // Note this is not the code_ pointer, that is handled above.
Ian Rogers169c9a72011-11-13 20:13:17 -0800459 ByteArray* orig_jni_stub_array_ = Runtime::Current()->GetJniDlsymLookupStub();
Brian Carlstrom16192862011-09-12 17:50:06 -0700460 ByteArray* copy_jni_stub_array_ = down_cast<ByteArray*>(GetImageAddress(orig_jni_stub_array_));
461 copy->native_method_ = copy_jni_stub_array_->GetData();
462 } else {
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700463 // normal (non-abstract non-native) methods have mapping tables to relocate
464 uint32_t mapping_table_off = orig->GetOatMappingTableOffset();
Brian Carlstromae826982011-11-09 01:33:42 -0800465 const byte* mapping_table = GetOatAddress(mapping_table_off);
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700466 copy->mapping_table_ = reinterpret_cast<const uint32_t*>(mapping_table);
467
468 uint32_t vmap_table_offset = orig->GetOatVmapTableOffset();
Brian Carlstromae826982011-11-09 01:33:42 -0800469 const byte* vmap_table = GetOatAddress(vmap_table_offset);
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700470 copy->vmap_table_ = reinterpret_cast<const uint16_t*>(vmap_table);
Brian Carlstrome7d856b2012-01-11 18:10:55 -0800471
472 uint32_t gc_map_offset = orig->GetOatGcMapOffset();
473 const byte* gc_map = GetOatAddress(gc_map_offset);
474 copy->gc_map_ = reinterpret_cast<const uint8_t*>(gc_map);
Brian Carlstrom16192862011-09-12 17:50:06 -0700475 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700476}
477
Brian Carlstrom4873d462011-08-21 15:23:39 -0700478void ImageWriter::FixupObjectArray(const ObjectArray<Object>* orig, ObjectArray<Object>* copy) {
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700479 for (int32_t i = 0; i < orig->GetLength(); ++i) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700480 const Object* element = orig->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700481 copy->SetWithoutChecks(i, GetImageAddress(element));
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700482 }
483}
484
Brian Carlstrom4873d462011-08-21 15:23:39 -0700485void ImageWriter::FixupInstanceFields(const Object* orig, Object* copy) {
486 DCHECK(orig != NULL);
487 DCHECK(copy != NULL);
488 Class* klass = orig->GetClass();
489 DCHECK(klass != NULL);
490 FixupFields(orig,
491 copy,
492 klass->GetReferenceInstanceOffsets(),
493 false);
494}
495
496void ImageWriter::FixupStaticFields(const Class* orig, Class* copy) {
497 DCHECK(orig != NULL);
498 DCHECK(copy != NULL);
499 FixupFields(orig,
500 copy,
501 orig->GetReferenceStaticOffsets(),
502 true);
503}
504
505void ImageWriter::FixupFields(const Object* orig,
506 Object* copy,
507 uint32_t ref_offsets,
508 bool is_static) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700509 if (ref_offsets != CLASS_WALK_SUPER) {
510 // Found a reference offset bitmap. Fixup the specified offsets.
511 while (ref_offsets != 0) {
512 size_t right_shift = CLZ(ref_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700513 MemberOffset byte_offset = CLASS_OFFSET_FROM_CLZ(right_shift);
514 const Object* ref = orig->GetFieldObject<const Object*>(byte_offset, false);
515 copy->SetFieldObject(byte_offset, GetImageAddress(ref), false);
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700516 ref_offsets &= ~(CLASS_HIGH_BIT >> right_shift);
517 }
518 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700519 // There is no reference offset bitmap. In the non-static case,
520 // walk up the class inheritance hierarchy and find reference
521 // offsets the hard way. In the static case, just consider this
522 // class.
523 for (const Class *klass = is_static ? orig->AsClass() : orig->GetClass();
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700524 klass != NULL;
Brian Carlstrom4873d462011-08-21 15:23:39 -0700525 klass = is_static ? NULL : klass->GetSuperClass()) {
526 size_t num_reference_fields = (is_static
527 ? klass->NumReferenceStaticFields()
528 : klass->NumReferenceInstanceFields());
529 for (size_t i = 0; i < num_reference_fields; ++i) {
530 Field* field = (is_static
531 ? klass->GetStaticField(i)
532 : klass->GetInstanceField(i));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700533 MemberOffset field_offset = field->GetOffset();
534 const Object* ref = orig->GetFieldObject<const Object*>(field_offset, false);
535 copy->SetFieldObject(field_offset, GetImageAddress(ref), false);
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700536 }
537 }
538 }
539}
540
Brian Carlstromf5822582012-03-19 22:34:31 -0700541static Method* GetReferrerMethod(const Compiler::PatchInformation* patch) {
542 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
543 Method* method = class_linker->ResolveMethod(patch->GetDexFile(),
544 patch->GetReferrerMethodIdx(),
545 patch->GetDexCache(),
546 NULL,
547 patch->GetReferrerIsDirect());
548 CHECK(method != NULL)
549 << patch->GetDexFile().GetLocation() << " " << patch->GetReferrerMethodIdx();
Brian Carlstrom0637e272012-03-20 01:07:52 -0700550 CHECK(!method->IsRuntimeMethod())
551 << patch->GetDexFile().GetLocation() << " " << patch->GetReferrerMethodIdx();
552 CHECK(patch->GetDexCache()->GetResolvedMethods()->Get(patch->GetReferrerMethodIdx()) == method)
553 << patch->GetDexFile().GetLocation() << " " << patch->GetReferrerMethodIdx() << " "
554 << PrettyMethod(patch->GetDexCache()->GetResolvedMethods()->Get(patch->GetReferrerMethodIdx())) << " "
555 << PrettyMethod(method);
Brian Carlstromf5822582012-03-19 22:34:31 -0700556 return method;
557}
558
559static Method* GetTargetMethod(const Compiler::PatchInformation* patch) {
560 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
561 Method* method = class_linker->ResolveMethod(patch->GetDexFile(),
562 patch->GetTargetMethodIdx(),
563 patch->GetDexCache(),
564 NULL,
565 patch->GetTargetIsDirect());
566 CHECK(method != NULL)
567 << patch->GetDexFile().GetLocation() << " " << patch->GetTargetMethodIdx();
Brian Carlstrom0637e272012-03-20 01:07:52 -0700568 CHECK(!method->IsRuntimeMethod())
569 << patch->GetDexFile().GetLocation() << " " << patch->GetTargetMethodIdx();
570 CHECK(patch->GetDexCache()->GetResolvedMethods()->Get(patch->GetTargetMethodIdx()) == method)
571 << patch->GetDexFile().GetLocation() << " " << patch->GetReferrerMethodIdx() << " "
572 << PrettyMethod(patch->GetDexCache()->GetResolvedMethods()->Get(patch->GetTargetMethodIdx())) << " "
573 << PrettyMethod(method);
Brian Carlstromf5822582012-03-19 22:34:31 -0700574 return method;
575}
576
577void ImageWriter::PatchOatCodeAndMethods(const Compiler& compiler) {
578 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
579
580 const std::vector<const Compiler::PatchInformation*>& code_to_patch = compiler.GetCodeToPatch();
581 for (size_t i = 0; i < code_to_patch.size(); i++) {
582 const Compiler::PatchInformation* patch = code_to_patch[i];
583 Method* target = GetTargetMethod(patch);
584 uint32_t code = reinterpret_cast<uint32_t>(class_linker->GetOatCodeFor(target));
585 uint32_t code_base = reinterpret_cast<uint32_t>(&oat_file_->GetOatHeader());
586 uint32_t code_offset = code - code_base;
587 SetPatchLocation(patch, reinterpret_cast<uint32_t>(GetOatAddress(code_offset)));
588 }
589
590 const std::vector<const Compiler::PatchInformation*>& methods_to_patch
591 = compiler.GetMethodsToPatch();
592 for (size_t i = 0; i < methods_to_patch.size(); i++) {
593 const Compiler::PatchInformation* patch = methods_to_patch[i];
594 Method* target = GetTargetMethod(patch);
595 SetPatchLocation(patch, reinterpret_cast<uint32_t>(GetImageAddress(target)));
596 }
597}
598
599void ImageWriter::SetPatchLocation(const Compiler::PatchInformation* patch, uint32_t value) {
600 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
601 Method* method = GetReferrerMethod(patch);
602 // Goodbye const, we are about to modify some code.
603 void* code = const_cast<void*>(class_linker->GetOatCodeFor(method));
604 // TODO: make this Thumb2 specific
605 uint8_t* base = reinterpret_cast<uint8_t*>(reinterpret_cast<uint32_t>(code) & ~0x1);
606 uint32_t* patch_location = reinterpret_cast<uint32_t*>(base + patch->GetLiteralOffset());
607#ifndef NDEBUG
608 const DexFile::MethodId& id = patch->GetDexFile().GetMethodId(patch->GetTargetMethodIdx());
609 uint32_t expected = reinterpret_cast<uint32_t>(&id);
610 uint32_t actual = *patch_location;
611 CHECK(actual == expected || actual == value) << std::hex
612 << "actual=" << actual
613 << "expected=" << expected
614 << "value=" << value;
615#endif
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700616 *patch_location = value;
Brian Carlstromf5822582012-03-19 22:34:31 -0700617}
618
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700619} // namespace art