blob: 59b7e80417a855a40eec6cf379a51024bca7e6c3 [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();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070055 const Spaces& spaces = heap->GetSpaces();
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
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070078 // Trim size of alloc spaces
79 // TODO: C++0x auto
80 for (Spaces::const_iterator cur = spaces.begin(); cur != spaces.end(); ++cur) {
81 if ((*cur)->IsAllocSpace()) {
82 (*cur)->AsAllocSpace()->Trim();
83 }
84 }
85
Brian Carlstromae826982011-11-09 01:33:42 -080086 if (!AllocMemory()) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -070087 return false;
88 }
Brian Carlstromae826982011-11-09 01:33:42 -080089#ifndef NDEBUG
90 CheckNonImageClassesRemoved();
91#endif
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080092 heap->DisableCardMarking();
Brian Carlstromdb4d5402011-08-09 12:18:28 -070093 CalculateNewObjectOffsets();
94 CopyAndFixupObjects();
Brian Carlstromf5822582012-03-19 22:34:31 -070095 PatchOatCodeAndMethods(compiler);
Elliott Hughesd8ddfd52011-08-15 14:32:53 -070096
Brian Carlstroma004aa92012-02-08 18:05:09 -080097 UniquePtr<File> file(OS::OpenFile(image_filename.c_str(), true));
Elliott Hughes90a33692011-08-30 13:27:07 -070098 if (file.get() == NULL) {
Brian Carlstrome24fa612011-09-29 00:53:55 -070099 LOG(ERROR) << "Failed to open image file " << image_filename;
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700100 return false;
101 }
Brian Carlstrom6cd40e52012-05-03 14:15:11 -0700102 if (fchmod(file->Fd(), 0644) != 0) {
103 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
104 return EXIT_FAILURE;
105 }
Ian Rogers30fab402012-01-23 15:43:46 -0800106 bool success = file->WriteFully(image_->Begin(), image_end_);
Brian Carlstrome24fa612011-09-29 00:53:55 -0700107 if (!success) {
108 PLOG(ERROR) << "Failed to write image file " << image_filename;
109 return false;
110 }
111 return true;
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700112}
113
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700114bool ImageWriter::InSourceSpace(const Object* object) const {
115 const Spaces& spaces = Runtime::Current()->GetHeap()->GetSpaces();
116 // TODO: C++0x auto
117 for (Spaces::const_iterator cur = spaces.begin(); cur != spaces.end(); ++cur) {
118 if ((*cur)->IsAllocSpace() && (*cur)->Contains(object)) {
119 return true;
120 }
121 }
122 return false;
123}
124
Brian Carlstromae826982011-11-09 01:33:42 -0800125bool ImageWriter::AllocMemory() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700126 typedef std::vector<Space*> SpaceVec;
127 const SpaceVec& spaces = Runtime::Current()->GetHeap()->GetSpaces();
128 size_t size = 0;
129 for (SpaceVec::const_iterator cur = spaces.begin(); cur != spaces.end(); ++cur) {
130 if ((*cur)->IsAllocSpace()) {
131 size += (*cur)->Size();
132 }
133 }
134
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700135 int prot = PROT_READ | PROT_WRITE;
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700136 size_t length = RoundUp(size, kPageSize);
Brian Carlstrom89521892011-12-07 22:05:07 -0800137 image_.reset(MemMap::MapAnonymous("image-writer-image", NULL, length, prot));
Elliott Hughes90a33692011-08-30 13:27:07 -0700138 if (image_.get() == NULL) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700139 LOG(ERROR) << "Failed to allocate memory for image file generation";
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700140 return false;
141 }
142 return true;
143}
144
Ian Rogersd418eda2012-01-30 12:14:28 -0800145void ImageWriter::ComputeLazyFieldsForImageClasses() {
146 Runtime* runtime = Runtime::Current();
147 ClassLinker* class_linker = runtime->GetClassLinker();
148 class_linker->VisitClasses(ComputeLazyFieldsForClassesVisitor, NULL);
149}
150
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700151bool ImageWriter::ComputeLazyFieldsForClassesVisitor(Class* c, void* /*arg*/) {
152 c->ComputeName();
Ian Rogersd418eda2012-01-30 12:14:28 -0800153 return true;
154}
155
Ian Rogersd1f1bf02012-02-26 16:59:20 -0800156void ImageWriter::ComputeEagerResolvedStringsCallback(Object* obj, void* arg) {
157 if (!obj->GetClass()->IsStringClass()) {
158 return;
159 }
160 String* string = obj->AsString();
161 std::string utf8_string(string->ToModifiedUtf8());
162 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
163 ClassLinker* linker = Runtime::Current()->GetClassLinker();
164 typedef Set::const_iterator CacheIt; // TODO: C++0x auto
165 for (CacheIt it = writer->dex_caches_.begin(), end = writer->dex_caches_.end(); it != end; ++it) {
166 DexCache* dex_cache = *it;
167 const DexFile& dex_file = linker->FindDexFile(dex_cache);
168 const DexFile::StringId* string_id = dex_file.FindStringId(utf8_string);
169 if (string_id != NULL) {
170 // This string occurs in this dex file, assign the dex cache entry.
171 uint32_t string_idx = dex_file.GetIndexForStringId(*string_id);
172 if (dex_cache->GetResolvedString(string_idx) == NULL) {
173 dex_cache->SetResolvedString(string_idx, string);
174 }
175 }
176 }
177}
178
179void ImageWriter::ComputeEagerResolvedStrings() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700180 // TODO: Check image spaces only?
181 Runtime::Current()->GetHeap()->GetLiveBitmap()->Walk(ComputeEagerResolvedStringsCallback, this);
Ian Rogersd1f1bf02012-02-26 16:59:20 -0800182}
183
Brian Carlstromae826982011-11-09 01:33:42 -0800184bool ImageWriter::IsImageClass(const Class* klass) {
185 if (image_classes_ == NULL) {
186 return true;
187 }
188 while (klass->IsArrayClass()) {
189 klass = klass->GetComponentType();
190 }
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800191 if (klass->IsPrimitive()) {
Brian Carlstromae826982011-11-09 01:33:42 -0800192 return true;
193 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800194 const std::string descriptor(ClassHelper(klass).GetDescriptor());
Brian Carlstromae826982011-11-09 01:33:42 -0800195 return image_classes_->find(descriptor) != image_classes_->end();
196}
197
198
199struct NonImageClasses {
200 ImageWriter* image_writer;
201 std::set<std::string>* non_image_classes;
202};
203
204void ImageWriter::PruneNonImageClasses() {
205 if (image_classes_ == NULL) {
206 return;
207 }
208 Runtime* runtime = Runtime::Current();
209 ClassLinker* class_linker = runtime->GetClassLinker();
210
211 std::set<std::string> non_image_classes;
212 NonImageClasses context;
213 context.image_writer = this;
214 context.non_image_classes = &non_image_classes;
215 class_linker->VisitClasses(NonImageClassesVisitor, &context);
216
217 typedef std::set<std::string>::const_iterator ClassIt; // TODO: C++0x auto
218 for (ClassIt it = non_image_classes.begin(), end = non_image_classes.end(); it != end; ++it) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800219 class_linker->RemoveClass((*it).c_str(), NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800220 }
221
Ian Rogers19846512012-02-24 11:42:47 -0800222 Method* resolution_method = runtime->GetResolutionMethod();
Brian Carlstromae826982011-11-09 01:33:42 -0800223 typedef Set::const_iterator CacheIt; // TODO: C++0x auto
224 for (CacheIt it = dex_caches_.begin(), end = dex_caches_.end(); it != end; ++it) {
225 DexCache* dex_cache = *it;
226 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
227 Class* klass = dex_cache->GetResolvedType(i);
228 if (klass != NULL && !IsImageClass(klass)) {
229 dex_cache->SetResolvedType(i, NULL);
230 dex_cache->GetInitializedStaticStorage()->Set(i, NULL);
231 }
232 }
233 for (size_t i = 0; i < dex_cache->NumResolvedMethods(); i++) {
234 Method* method = dex_cache->GetResolvedMethod(i);
235 if (method != NULL && !IsImageClass(method->GetDeclaringClass())) {
Ian Rogers19846512012-02-24 11:42:47 -0800236 dex_cache->SetResolvedMethod(i, resolution_method);
Brian Carlstromae826982011-11-09 01:33:42 -0800237 }
238 }
239 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
240 Field* field = dex_cache->GetResolvedField(i);
241 if (field != NULL && !IsImageClass(field->GetDeclaringClass())) {
242 dex_cache->SetResolvedField(i, NULL);
243 }
244 }
245 }
246}
247
248bool ImageWriter::NonImageClassesVisitor(Class* klass, void* arg) {
249 NonImageClasses* context = reinterpret_cast<NonImageClasses*>(arg);
250 if (!context->image_writer->IsImageClass(klass)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800251 context->non_image_classes->insert(ClassHelper(klass).GetDescriptor());
Brian Carlstromae826982011-11-09 01:33:42 -0800252 }
253 return true;
254}
255
256void ImageWriter::CheckNonImageClassesRemoved() {
257 if (image_classes_ == NULL) {
258 return;
259 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700260
261 Runtime::Current()->GetHeap()->GetLiveBitmap()->Walk(CheckNonImageClassesRemovedCallback, this);
Brian Carlstromae826982011-11-09 01:33:42 -0800262}
263
264void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
265 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
266 if (!obj->IsClass()) {
267 return;
268 }
269 Class* klass = obj->AsClass();
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800270 if (!image_writer->IsImageClass(klass)) {
271 image_writer->DumpImageClasses();
272 CHECK(image_writer->IsImageClass(klass)) << ClassHelper(klass).GetDescriptor()
273 << " " << PrettyDescriptor(klass);
274 }
275}
276
277void ImageWriter::DumpImageClasses() {
278 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
279 for (It it = image_classes_->begin(), end = image_classes_->end(); it != end; ++it) {
280 LOG(INFO) << " " << *it;
281 }
Brian Carlstromae826982011-11-09 01:33:42 -0800282}
283
Brian Carlstrom78128a62011-09-15 17:21:19 -0700284void ImageWriter::CalculateNewObjectOffsetsCallback(Object* obj, void* arg) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700285 DCHECK(obj != NULL);
286 DCHECK(arg != NULL);
287 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700288 if (!image_writer->InSourceSpace(obj)) {
289 return;
290 }
Brian Carlstromc74255f2011-09-11 22:47:39 -0700291
292 // if it is a string, we want to intern it if its not interned.
Elliott Hughesdbb40792011-11-18 17:05:22 -0800293 if (obj->GetClass()->IsStringClass()) {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700294 // we must be an interned string that was forward referenced and already assigned
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800295 if (image_writer->IsImageOffsetAssigned(obj)) {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700296 DCHECK_EQ(obj, obj->AsString()->Intern());
297 return;
298 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700299 SirtRef<String> interned(obj->AsString()->Intern());
300 if (obj != interned.get()) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800301 if (!image_writer->IsImageOffsetAssigned(interned.get())) {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700302 // interned obj is after us, allocate its location early
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700303 image_writer->AssignImageOffset(interned.get());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700304 }
305 // point those looking for this object to the interned version.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800306 image_writer->SetImageOffset(obj, image_writer->GetImageOffset(interned.get()));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700307 return;
308 }
309 // else (obj == interned), nothing to do but fall through to the normal case
310 }
311
312 image_writer->AssignImageOffset(obj);
Brian Carlstrom4e777d42011-08-15 13:53:52 -0700313}
314
Brian Carlstrome24fa612011-09-29 00:53:55 -0700315ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
Brian Carlstrom16192862011-09-12 17:50:06 -0700316 Runtime* runtime = Runtime::Current();
317 ClassLinker* class_linker = runtime->GetClassLinker();
318 Class* object_array_class = class_linker->FindSystemClass("[Ljava/lang/Object;");
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700319
320 // build an Object[] of all the DexCaches used in the source_space_
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700321 ObjectArray<Object>* dex_caches = ObjectArray<Object>::Alloc(object_array_class,
Brian Carlstromae826982011-11-09 01:33:42 -0800322 dex_caches_.size());
323 int i = 0;
324 typedef Set::const_iterator It; // TODO: C++0x auto
325 for (It it = dex_caches_.begin(), end = dex_caches_.end(); it != end; ++it, ++i) {
326 dex_caches->Set(i, *it);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700327 }
328
329 // build an Object[] of the roots needed to restore the runtime
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700330 SirtRef<ObjectArray<Object> > image_roots(
331 ObjectArray<Object>::Alloc(object_array_class, ImageHeader::kImageRootsMax));
Ian Rogers169c9a72011-11-13 20:13:17 -0800332 image_roots->Set(ImageHeader::kJniStubArray, runtime->GetJniDlsymLookupStub());
Brian Carlstrome24fa612011-09-29 00:53:55 -0700333 image_roots->Set(ImageHeader::kAbstractMethodErrorStubArray,
334 runtime->GetAbstractMethodErrorStubArray());
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700335 image_roots->Set(ImageHeader::kStaticResolutionStubArray,
336 runtime->GetResolutionStubArray(Runtime::kStaticMethod));
337 image_roots->Set(ImageHeader::kUnknownMethodResolutionStubArray,
338 runtime->GetResolutionStubArray(Runtime::kUnknownMethod));
Ian Rogers19846512012-02-24 11:42:47 -0800339 image_roots->Set(ImageHeader::kResolutionMethod, runtime->GetResolutionMethod());
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700340 image_roots->Set(ImageHeader::kCalleeSaveMethod,
341 runtime->GetCalleeSaveMethod(Runtime::kSaveAll));
342 image_roots->Set(ImageHeader::kRefsOnlySaveMethod,
343 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly));
344 image_roots->Set(ImageHeader::kRefsAndArgsSaveMethod,
345 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs));
Brian Carlstrome24fa612011-09-29 00:53:55 -0700346 image_roots->Set(ImageHeader::kOatLocation,
347 String::AllocFromModifiedUtf8(oat_file_->GetLocation().c_str()));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700348 image_roots->Set(ImageHeader::kDexCaches,
349 dex_caches);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700350 image_roots->Set(ImageHeader::kClassRoots,
351 class_linker->GetClassRoots());
Brian Carlstrome24fa612011-09-29 00:53:55 -0700352 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
353 CHECK(image_roots->Get(i) != NULL);
354 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700355 return image_roots.get();
Brian Carlstrom16192862011-09-12 17:50:06 -0700356}
357
Brian Carlstrom4e777d42011-08-15 13:53:52 -0700358void ImageWriter::CalculateNewObjectOffsets() {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700359 SirtRef<ObjectArray<Object> > image_roots(CreateImageRoots());
Brian Carlstrom16192862011-09-12 17:50:06 -0700360
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700361 Heap* heap = Runtime::Current()->GetHeap();
362 typedef std::vector<Space*> SpaceVec;
363 const SpaceVec& spaces = heap->GetSpaces();
364 DCHECK(!spaces.empty());
Ian Rogers30fab402012-01-23 15:43:46 -0800365 DCHECK_EQ(0U, image_end_);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700366
Brian Carlstrom16192862011-09-12 17:50:06 -0700367 // leave space for the header, but do not write it yet, we need to
368 // know where image_roots is going to end up
Ian Rogers30fab402012-01-23 15:43:46 -0800369 image_end_ += RoundUp(sizeof(ImageHeader), 8); // 64-bit-alignment
Brian Carlstroma663ea52011-08-19 23:33:41 -0700370
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700371 // TODO: Image spaces only?
372 for (SpaceVec::const_iterator cur = spaces.begin(); cur != spaces.end(); ++cur) {
373 (*cur)->GetLiveBitmap()->InOrderWalk(CalculateNewObjectOffsetsCallback, this);
374 DCHECK_LT(image_end_, image_->Size());
375 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700376
Brian Carlstrome24fa612011-09-29 00:53:55 -0700377 // Note that image_top_ is left at end of used space
Ian Rogers30fab402012-01-23 15:43:46 -0800378 oat_begin_ = image_begin_ + RoundUp(image_end_, kPageSize);
379 const byte* oat_limit = oat_begin_ + oat_file_->Size();
Brian Carlstrome24fa612011-09-29 00:53:55 -0700380
Brian Carlstrom16192862011-09-12 17:50:06 -0700381 // return to write header at start of image with future location of image_roots
Ian Rogers30fab402012-01-23 15:43:46 -0800382 ImageHeader image_header(reinterpret_cast<uint32_t>(image_begin_),
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700383 reinterpret_cast<uint32_t>(GetImageAddress(image_roots.get())),
Brian Carlstrome24fa612011-09-29 00:53:55 -0700384 oat_file_->GetOatHeader().GetChecksum(),
Ian Rogers30fab402012-01-23 15:43:46 -0800385 reinterpret_cast<uint32_t>(oat_begin_),
Brian Carlstrome24fa612011-09-29 00:53:55 -0700386 reinterpret_cast<uint32_t>(oat_limit));
Ian Rogers30fab402012-01-23 15:43:46 -0800387 memcpy(image_->Begin(), &image_header, sizeof(image_header));
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700388}
389
390void ImageWriter::CopyAndFixupObjects() {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800391 Heap* heap = Runtime::Current()->GetHeap();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700392 // TODO: heap validation can't handle this fix up pass
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800393 heap->DisableObjectValidation();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700394 // TODO: Image spaces only?
395 heap->GetLiveBitmap()->Walk(CopyAndFixupObjectsCallback, this);
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700396}
397
Brian Carlstrom78128a62011-09-15 17:21:19 -0700398void ImageWriter::CopyAndFixupObjectsCallback(Object* object, void* arg) {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700399 DCHECK(object != NULL);
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700400 DCHECK(arg != NULL);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700401 const Object* obj = object;
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700402 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700403 if (!image_writer->InSourceSpace(object)) {
404 return;
405 }
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700406
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700407 // see GetLocalAddress for similar computation
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700408 size_t offset = image_writer->GetImageOffset(obj);
Ian Rogers30fab402012-01-23 15:43:46 -0800409 byte* dst = image_writer->image_->Begin() + offset;
Brian Carlstrom4873d462011-08-21 15:23:39 -0700410 const byte* src = reinterpret_cast<const byte*>(obj);
Elliott Hughes04b63fd2011-08-16 09:40:10 -0700411 size_t n = obj->SizeOf();
Ian Rogers30fab402012-01-23 15:43:46 -0800412 DCHECK_LT(offset + n, image_writer->image_->Size());
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700413 memcpy(dst, src, n);
414 Object* copy = reinterpret_cast<Object*>(dst);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800415 copy->monitor_ = 0; // We may have inflated the lock during compilation.
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700416 image_writer->FixupObject(obj, copy);
417}
418
Brian Carlstrom4873d462011-08-21 15:23:39 -0700419void ImageWriter::FixupObject(const Object* orig, Object* copy) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700420 DCHECK(orig != NULL);
421 DCHECK(copy != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700422 copy->SetClass(down_cast<Class*>(GetImageAddress(orig->GetClass())));
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700423 // TODO: special case init of pointers to malloc data (or removal of these pointers)
424 if (orig->IsClass()) {
425 FixupClass(orig->AsClass(), down_cast<Class*>(copy));
426 } else if (orig->IsObjectArray()) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700427 FixupObjectArray(orig->AsObjectArray<Object>(), down_cast<ObjectArray<Object>*>(copy));
Brian Carlstrom16192862011-09-12 17:50:06 -0700428 } else if (orig->IsMethod()) {
429 FixupMethod(orig->AsMethod(), down_cast<Method*>(copy));
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700430 } else {
431 FixupInstanceFields(orig, copy);
432 }
433}
434
Brian Carlstrom4873d462011-08-21 15:23:39 -0700435void ImageWriter::FixupClass(const Class* orig, Class* copy) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700436 FixupInstanceFields(orig, copy);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700437 FixupStaticFields(orig, copy);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700438}
439
Brian Carlstrom4873d462011-08-21 15:23:39 -0700440void ImageWriter::FixupMethod(const Method* orig, Method* copy) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700441 FixupInstanceFields(orig, copy);
Brian Carlstrome24fa612011-09-29 00:53:55 -0700442
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700443 // OatWriter replaces the code_ and invoke_stub_ with offset values.
Ian Rogers30fab402012-01-23 15:43:46 -0800444 // Here we readjust to a pointer relative to oat_begin_
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700445
446 // Every type of method can have an invoke stub
447 uint32_t invoke_stub_offset = orig->GetOatInvokeStubOffset();
Brian Carlstromae826982011-11-09 01:33:42 -0800448 const byte* invoke_stub = GetOatAddress(invoke_stub_offset);
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700449 copy->invoke_stub_ = reinterpret_cast<const Method::InvokeStub*>(invoke_stub);
450
451 if (orig->IsAbstract()) {
452 // Abstract methods are pointed to a stub that will throw AbstractMethodError if they are called
453 ByteArray* orig_ame_stub_array_ = Runtime::Current()->GetAbstractMethodErrorStubArray();
454 ByteArray* copy_ame_stub_array_ = down_cast<ByteArray*>(GetImageAddress(orig_ame_stub_array_));
455 copy->code_ = copy_ame_stub_array_->GetData();
456 return;
457 }
458
Ian Rogers19846512012-02-24 11:42:47 -0800459 if (orig == Runtime::Current()->GetResolutionMethod()) {
460 // The resolution stub's code points at the unknown resolution trampoline
461 ByteArray* orig_res_stub_array_ =
462 Runtime::Current()->GetResolutionStubArray(Runtime::kUnknownMethod);
463 CHECK(orig->GetCode() == orig_res_stub_array_->GetData());
464 ByteArray* copy_res_stub_array_ = down_cast<ByteArray*>(GetImageAddress(orig_res_stub_array_));
465 copy->code_ = copy_res_stub_array_->GetData();
466 return;
467 }
468
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700469 // Non-abstract methods typically have code
470 uint32_t code_offset = orig->GetOatCodeOffset();
Ian Rogers19846512012-02-24 11:42:47 -0800471 const byte* code = NULL;
472 if (orig->IsStatic()) {
473 // Static methods may point at the resolution trampoline stub
474 ByteArray* orig_res_stub_array_ =
475 Runtime::Current()->GetResolutionStubArray(Runtime::kStaticMethod);
476 if (reinterpret_cast<int8_t*>(code_offset) == orig_res_stub_array_->GetData()) {
477 ByteArray* copy_res_stub_array_ = down_cast<ByteArray*>(GetImageAddress(orig_res_stub_array_));
478 code = reinterpret_cast<const byte*>(copy_res_stub_array_->GetData());
479 }
480 }
481 if (code == NULL) {
482 code = GetOatAddress(code_offset);
483 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700484 copy->code_ = code;
485
Brian Carlstrom16192862011-09-12 17:50:06 -0700486 if (orig->IsNative()) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700487 // The native method's pointer is directed to a stub to lookup via dlsym.
488 // Note this is not the code_ pointer, that is handled above.
Ian Rogers169c9a72011-11-13 20:13:17 -0800489 ByteArray* orig_jni_stub_array_ = Runtime::Current()->GetJniDlsymLookupStub();
Brian Carlstrom16192862011-09-12 17:50:06 -0700490 ByteArray* copy_jni_stub_array_ = down_cast<ByteArray*>(GetImageAddress(orig_jni_stub_array_));
491 copy->native_method_ = copy_jni_stub_array_->GetData();
492 } else {
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700493 // normal (non-abstract non-native) methods have mapping tables to relocate
494 uint32_t mapping_table_off = orig->GetOatMappingTableOffset();
Brian Carlstromae826982011-11-09 01:33:42 -0800495 const byte* mapping_table = GetOatAddress(mapping_table_off);
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700496 copy->mapping_table_ = reinterpret_cast<const uint32_t*>(mapping_table);
497
498 uint32_t vmap_table_offset = orig->GetOatVmapTableOffset();
Brian Carlstromae826982011-11-09 01:33:42 -0800499 const byte* vmap_table = GetOatAddress(vmap_table_offset);
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700500 copy->vmap_table_ = reinterpret_cast<const uint16_t*>(vmap_table);
Brian Carlstrome7d856b2012-01-11 18:10:55 -0800501
502 uint32_t gc_map_offset = orig->GetOatGcMapOffset();
503 const byte* gc_map = GetOatAddress(gc_map_offset);
504 copy->gc_map_ = reinterpret_cast<const uint8_t*>(gc_map);
Brian Carlstrom16192862011-09-12 17:50:06 -0700505 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700506}
507
Brian Carlstrom4873d462011-08-21 15:23:39 -0700508void ImageWriter::FixupObjectArray(const ObjectArray<Object>* orig, ObjectArray<Object>* copy) {
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700509 for (int32_t i = 0; i < orig->GetLength(); ++i) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700510 const Object* element = orig->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700511 copy->SetWithoutChecks(i, GetImageAddress(element));
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700512 }
513}
514
Brian Carlstrom4873d462011-08-21 15:23:39 -0700515void ImageWriter::FixupInstanceFields(const Object* orig, Object* copy) {
516 DCHECK(orig != NULL);
517 DCHECK(copy != NULL);
518 Class* klass = orig->GetClass();
519 DCHECK(klass != NULL);
520 FixupFields(orig,
521 copy,
522 klass->GetReferenceInstanceOffsets(),
523 false);
524}
525
526void ImageWriter::FixupStaticFields(const Class* orig, Class* copy) {
527 DCHECK(orig != NULL);
528 DCHECK(copy != NULL);
529 FixupFields(orig,
530 copy,
531 orig->GetReferenceStaticOffsets(),
532 true);
533}
534
535void ImageWriter::FixupFields(const Object* orig,
536 Object* copy,
537 uint32_t ref_offsets,
538 bool is_static) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700539 if (ref_offsets != CLASS_WALK_SUPER) {
540 // Found a reference offset bitmap. Fixup the specified offsets.
541 while (ref_offsets != 0) {
542 size_t right_shift = CLZ(ref_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700543 MemberOffset byte_offset = CLASS_OFFSET_FROM_CLZ(right_shift);
544 const Object* ref = orig->GetFieldObject<const Object*>(byte_offset, false);
545 copy->SetFieldObject(byte_offset, GetImageAddress(ref), false);
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700546 ref_offsets &= ~(CLASS_HIGH_BIT >> right_shift);
547 }
548 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700549 // There is no reference offset bitmap. In the non-static case,
550 // walk up the class inheritance hierarchy and find reference
551 // offsets the hard way. In the static case, just consider this
552 // class.
553 for (const Class *klass = is_static ? orig->AsClass() : orig->GetClass();
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700554 klass != NULL;
Brian Carlstrom4873d462011-08-21 15:23:39 -0700555 klass = is_static ? NULL : klass->GetSuperClass()) {
556 size_t num_reference_fields = (is_static
557 ? klass->NumReferenceStaticFields()
558 : klass->NumReferenceInstanceFields());
559 for (size_t i = 0; i < num_reference_fields; ++i) {
560 Field* field = (is_static
561 ? klass->GetStaticField(i)
562 : klass->GetInstanceField(i));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700563 MemberOffset field_offset = field->GetOffset();
564 const Object* ref = orig->GetFieldObject<const Object*>(field_offset, false);
565 copy->SetFieldObject(field_offset, GetImageAddress(ref), false);
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700566 }
567 }
568 }
569}
570
Brian Carlstromf5822582012-03-19 22:34:31 -0700571static Method* GetReferrerMethod(const Compiler::PatchInformation* patch) {
572 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
573 Method* method = class_linker->ResolveMethod(patch->GetDexFile(),
574 patch->GetReferrerMethodIdx(),
575 patch->GetDexCache(),
576 NULL,
577 patch->GetReferrerIsDirect());
578 CHECK(method != NULL)
579 << patch->GetDexFile().GetLocation() << " " << patch->GetReferrerMethodIdx();
Brian Carlstrom0637e272012-03-20 01:07:52 -0700580 CHECK(!method->IsRuntimeMethod())
581 << patch->GetDexFile().GetLocation() << " " << patch->GetReferrerMethodIdx();
582 CHECK(patch->GetDexCache()->GetResolvedMethods()->Get(patch->GetReferrerMethodIdx()) == method)
583 << patch->GetDexFile().GetLocation() << " " << patch->GetReferrerMethodIdx() << " "
584 << PrettyMethod(patch->GetDexCache()->GetResolvedMethods()->Get(patch->GetReferrerMethodIdx())) << " "
585 << PrettyMethod(method);
Brian Carlstromf5822582012-03-19 22:34:31 -0700586 return method;
587}
588
589static Method* GetTargetMethod(const Compiler::PatchInformation* patch) {
590 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
591 Method* method = class_linker->ResolveMethod(patch->GetDexFile(),
592 patch->GetTargetMethodIdx(),
593 patch->GetDexCache(),
594 NULL,
595 patch->GetTargetIsDirect());
596 CHECK(method != NULL)
597 << patch->GetDexFile().GetLocation() << " " << patch->GetTargetMethodIdx();
Brian Carlstrom0637e272012-03-20 01:07:52 -0700598 CHECK(!method->IsRuntimeMethod())
599 << patch->GetDexFile().GetLocation() << " " << patch->GetTargetMethodIdx();
600 CHECK(patch->GetDexCache()->GetResolvedMethods()->Get(patch->GetTargetMethodIdx()) == method)
601 << patch->GetDexFile().GetLocation() << " " << patch->GetReferrerMethodIdx() << " "
602 << PrettyMethod(patch->GetDexCache()->GetResolvedMethods()->Get(patch->GetTargetMethodIdx())) << " "
603 << PrettyMethod(method);
Brian Carlstromf5822582012-03-19 22:34:31 -0700604 return method;
605}
606
607void ImageWriter::PatchOatCodeAndMethods(const Compiler& compiler) {
608 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
609
610 const std::vector<const Compiler::PatchInformation*>& code_to_patch = compiler.GetCodeToPatch();
611 for (size_t i = 0; i < code_to_patch.size(); i++) {
612 const Compiler::PatchInformation* patch = code_to_patch[i];
613 Method* target = GetTargetMethod(patch);
614 uint32_t code = reinterpret_cast<uint32_t>(class_linker->GetOatCodeFor(target));
615 uint32_t code_base = reinterpret_cast<uint32_t>(&oat_file_->GetOatHeader());
616 uint32_t code_offset = code - code_base;
617 SetPatchLocation(patch, reinterpret_cast<uint32_t>(GetOatAddress(code_offset)));
618 }
619
620 const std::vector<const Compiler::PatchInformation*>& methods_to_patch
621 = compiler.GetMethodsToPatch();
622 for (size_t i = 0; i < methods_to_patch.size(); i++) {
623 const Compiler::PatchInformation* patch = methods_to_patch[i];
624 Method* target = GetTargetMethod(patch);
625 SetPatchLocation(patch, reinterpret_cast<uint32_t>(GetImageAddress(target)));
626 }
627}
628
629void ImageWriter::SetPatchLocation(const Compiler::PatchInformation* patch, uint32_t value) {
630 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
631 Method* method = GetReferrerMethod(patch);
632 // Goodbye const, we are about to modify some code.
633 void* code = const_cast<void*>(class_linker->GetOatCodeFor(method));
634 // TODO: make this Thumb2 specific
635 uint8_t* base = reinterpret_cast<uint8_t*>(reinterpret_cast<uint32_t>(code) & ~0x1);
636 uint32_t* patch_location = reinterpret_cast<uint32_t*>(base + patch->GetLiteralOffset());
637#ifndef NDEBUG
638 const DexFile::MethodId& id = patch->GetDexFile().GetMethodId(patch->GetTargetMethodIdx());
639 uint32_t expected = reinterpret_cast<uint32_t>(&id);
640 uint32_t actual = *patch_location;
641 CHECK(actual == expected || actual == value) << std::hex
642 << "actual=" << actual
643 << "expected=" << expected
644 << "value=" << value;
645#endif
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700646 *patch_location = value;
Brian Carlstromf5822582012-03-19 22:34:31 -0700647}
648
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700649} // namespace art