blob: 7c88c955f1a5f8f5dbb27193ed46e995b7485eab [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"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070038#include "scoped_thread_state_change.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070039#include "space.h"
Elliott Hughesa168c832012-06-12 15:34:20 -070040#include "UniquePtr.h"
Brian Carlstromdb4d5402011-08-09 12:18:28 -070041#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();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070056 const Spaces& spaces = heap->GetSpaces();
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 Rogers00f7d0e2012-07-19 15:28:27 -070075 {
76 Thread::Current()->TransitionFromSuspendedToRunnable();
77 PruneNonImageClasses(); // Remove junk
78 ComputeLazyFieldsForImageClasses(); // Add useful information
79 ComputeEagerResolvedStrings();
80 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
81 }
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080082 heap->CollectGarbage(false); // Remove garbage
Mathieu Chartierb062fdd2012-07-03 09:51:48 -070083 // Trim size of alloc spaces
84 // TODO: C++0x auto
85 for (Spaces::const_iterator cur = spaces.begin(); cur != spaces.end(); ++cur) {
86 if ((*cur)->IsAllocSpace()) {
87 (*cur)->AsAllocSpace()->Trim();
88 }
89 }
90
Brian Carlstromae826982011-11-09 01:33:42 -080091 if (!AllocMemory()) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -070092 return false;
93 }
Brian Carlstromae826982011-11-09 01:33:42 -080094#ifndef NDEBUG
95 CheckNonImageClassesRemoved();
96#endif
Elliott Hughesb3bd5f02012-03-08 21:05:27 -080097 heap->DisableCardMarking();
Ian Rogers00f7d0e2012-07-19 15:28:27 -070098 {
99 Thread::Current()->TransitionFromSuspendedToRunnable();
100 CalculateNewObjectOffsets();
101 CopyAndFixupObjects();
102 PatchOatCodeAndMethods(compiler);
103 Thread::Current()->TransitionFromRunnableToSuspended(kNative);
104 }
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700105
Brian Carlstroma004aa92012-02-08 18:05:09 -0800106 UniquePtr<File> file(OS::OpenFile(image_filename.c_str(), true));
Elliott Hughes90a33692011-08-30 13:27:07 -0700107 if (file.get() == NULL) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700108 LOG(ERROR) << "Failed to open image file " << image_filename;
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700109 return false;
110 }
Brian Carlstrom6cd40e52012-05-03 14:15:11 -0700111 if (fchmod(file->Fd(), 0644) != 0) {
112 PLOG(ERROR) << "Failed to make image file world readable: " << image_filename;
113 return EXIT_FAILURE;
114 }
Ian Rogers30fab402012-01-23 15:43:46 -0800115 bool success = file->WriteFully(image_->Begin(), image_end_);
Brian Carlstrome24fa612011-09-29 00:53:55 -0700116 if (!success) {
117 PLOG(ERROR) << "Failed to write image file " << image_filename;
118 return false;
119 }
120 return true;
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700121}
122
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700123bool ImageWriter::InSourceSpace(const Object* object) const {
124 const Spaces& spaces = Runtime::Current()->GetHeap()->GetSpaces();
125 // TODO: C++0x auto
126 for (Spaces::const_iterator cur = spaces.begin(); cur != spaces.end(); ++cur) {
127 if ((*cur)->IsAllocSpace() && (*cur)->Contains(object)) {
128 return true;
129 }
130 }
131 return false;
132}
133
Brian Carlstromae826982011-11-09 01:33:42 -0800134bool ImageWriter::AllocMemory() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700135 typedef std::vector<Space*> SpaceVec;
136 const SpaceVec& spaces = Runtime::Current()->GetHeap()->GetSpaces();
137 size_t size = 0;
138 for (SpaceVec::const_iterator cur = spaces.begin(); cur != spaces.end(); ++cur) {
139 if ((*cur)->IsAllocSpace()) {
140 size += (*cur)->Size();
141 }
142 }
143
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700144 int prot = PROT_READ | PROT_WRITE;
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700145 size_t length = RoundUp(size, kPageSize);
Brian Carlstrom89521892011-12-07 22:05:07 -0800146 image_.reset(MemMap::MapAnonymous("image-writer-image", NULL, length, prot));
Elliott Hughes90a33692011-08-30 13:27:07 -0700147 if (image_.get() == NULL) {
Brian Carlstrome24fa612011-09-29 00:53:55 -0700148 LOG(ERROR) << "Failed to allocate memory for image file generation";
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700149 return false;
150 }
151 return true;
152}
153
Ian Rogersd418eda2012-01-30 12:14:28 -0800154void ImageWriter::ComputeLazyFieldsForImageClasses() {
155 Runtime* runtime = Runtime::Current();
156 ClassLinker* class_linker = runtime->GetClassLinker();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700157 class_linker->VisitClassesWithoutClassesLock(ComputeLazyFieldsForClassesVisitor, NULL);
Ian Rogersd418eda2012-01-30 12:14:28 -0800158}
159
Elliott Hughes1bac54f2012-03-16 12:48:31 -0700160bool ImageWriter::ComputeLazyFieldsForClassesVisitor(Class* c, void* /*arg*/) {
161 c->ComputeName();
Ian Rogersd418eda2012-01-30 12:14:28 -0800162 return true;
163}
164
Ian Rogersd1f1bf02012-02-26 16:59:20 -0800165void ImageWriter::ComputeEagerResolvedStringsCallback(Object* obj, void* arg) {
166 if (!obj->GetClass()->IsStringClass()) {
167 return;
168 }
169 String* string = obj->AsString();
170 std::string utf8_string(string->ToModifiedUtf8());
171 ImageWriter* writer = reinterpret_cast<ImageWriter*>(arg);
172 ClassLinker* linker = Runtime::Current()->GetClassLinker();
173 typedef Set::const_iterator CacheIt; // TODO: C++0x auto
174 for (CacheIt it = writer->dex_caches_.begin(), end = writer->dex_caches_.end(); it != end; ++it) {
175 DexCache* dex_cache = *it;
176 const DexFile& dex_file = linker->FindDexFile(dex_cache);
177 const DexFile::StringId* string_id = dex_file.FindStringId(utf8_string);
178 if (string_id != NULL) {
179 // This string occurs in this dex file, assign the dex cache entry.
180 uint32_t string_idx = dex_file.GetIndexForStringId(*string_id);
181 if (dex_cache->GetResolvedString(string_idx) == NULL) {
182 dex_cache->SetResolvedString(string_idx, string);
183 }
184 }
185 }
186}
187
188void ImageWriter::ComputeEagerResolvedStrings() {
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700189 // TODO: Check image spaces only?
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700190 ReaderMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700191 Runtime::Current()->GetHeap()->GetLiveBitmap()->Walk(ComputeEagerResolvedStringsCallback, this);
Ian Rogersd1f1bf02012-02-26 16:59:20 -0800192}
193
Brian Carlstromae826982011-11-09 01:33:42 -0800194bool ImageWriter::IsImageClass(const Class* klass) {
195 if (image_classes_ == NULL) {
196 return true;
197 }
198 while (klass->IsArrayClass()) {
199 klass = klass->GetComponentType();
200 }
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800201 if (klass->IsPrimitive()) {
Brian Carlstromae826982011-11-09 01:33:42 -0800202 return true;
203 }
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800204 const std::string descriptor(ClassHelper(klass).GetDescriptor());
Brian Carlstromae826982011-11-09 01:33:42 -0800205 return image_classes_->find(descriptor) != image_classes_->end();
206}
207
208
209struct NonImageClasses {
210 ImageWriter* image_writer;
211 std::set<std::string>* non_image_classes;
212};
213
214void ImageWriter::PruneNonImageClasses() {
215 if (image_classes_ == NULL) {
216 return;
217 }
218 Runtime* runtime = Runtime::Current();
219 ClassLinker* class_linker = runtime->GetClassLinker();
220
221 std::set<std::string> non_image_classes;
222 NonImageClasses context;
223 context.image_writer = this;
224 context.non_image_classes = &non_image_classes;
225 class_linker->VisitClasses(NonImageClassesVisitor, &context);
226
227 typedef std::set<std::string>::const_iterator ClassIt; // TODO: C++0x auto
228 for (ClassIt it = non_image_classes.begin(), end = non_image_classes.end(); it != end; ++it) {
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800229 class_linker->RemoveClass((*it).c_str(), NULL);
Brian Carlstromae826982011-11-09 01:33:42 -0800230 }
231
Ian Rogers19846512012-02-24 11:42:47 -0800232 Method* resolution_method = runtime->GetResolutionMethod();
Brian Carlstromae826982011-11-09 01:33:42 -0800233 typedef Set::const_iterator CacheIt; // TODO: C++0x auto
234 for (CacheIt it = dex_caches_.begin(), end = dex_caches_.end(); it != end; ++it) {
235 DexCache* dex_cache = *it;
236 for (size_t i = 0; i < dex_cache->NumResolvedTypes(); i++) {
237 Class* klass = dex_cache->GetResolvedType(i);
238 if (klass != NULL && !IsImageClass(klass)) {
239 dex_cache->SetResolvedType(i, NULL);
240 dex_cache->GetInitializedStaticStorage()->Set(i, NULL);
241 }
242 }
243 for (size_t i = 0; i < dex_cache->NumResolvedMethods(); i++) {
244 Method* method = dex_cache->GetResolvedMethod(i);
245 if (method != NULL && !IsImageClass(method->GetDeclaringClass())) {
Ian Rogers19846512012-02-24 11:42:47 -0800246 dex_cache->SetResolvedMethod(i, resolution_method);
Brian Carlstromae826982011-11-09 01:33:42 -0800247 }
248 }
249 for (size_t i = 0; i < dex_cache->NumResolvedFields(); i++) {
250 Field* field = dex_cache->GetResolvedField(i);
251 if (field != NULL && !IsImageClass(field->GetDeclaringClass())) {
252 dex_cache->SetResolvedField(i, NULL);
253 }
254 }
255 }
256}
257
258bool ImageWriter::NonImageClassesVisitor(Class* klass, void* arg) {
259 NonImageClasses* context = reinterpret_cast<NonImageClasses*>(arg);
260 if (!context->image_writer->IsImageClass(klass)) {
Ian Rogers6d4d9fc2011-11-30 16:24:48 -0800261 context->non_image_classes->insert(ClassHelper(klass).GetDescriptor());
Brian Carlstromae826982011-11-09 01:33:42 -0800262 }
263 return true;
264}
265
266void ImageWriter::CheckNonImageClassesRemoved() {
267 if (image_classes_ == NULL) {
268 return;
269 }
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700270
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700271 ReaderMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700272 Runtime::Current()->GetHeap()->GetLiveBitmap()->Walk(CheckNonImageClassesRemovedCallback, this);
Brian Carlstromae826982011-11-09 01:33:42 -0800273}
274
275void ImageWriter::CheckNonImageClassesRemovedCallback(Object* obj, void* arg) {
276 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
277 if (!obj->IsClass()) {
278 return;
279 }
280 Class* klass = obj->AsClass();
Elliott Hughesc3b77c72011-12-15 20:56:48 -0800281 if (!image_writer->IsImageClass(klass)) {
282 image_writer->DumpImageClasses();
283 CHECK(image_writer->IsImageClass(klass)) << ClassHelper(klass).GetDescriptor()
284 << " " << PrettyDescriptor(klass);
285 }
286}
287
288void ImageWriter::DumpImageClasses() {
289 typedef std::set<std::string>::const_iterator It; // TODO: C++0x auto
290 for (It it = image_classes_->begin(), end = image_classes_->end(); it != end; ++it) {
291 LOG(INFO) << " " << *it;
292 }
Brian Carlstromae826982011-11-09 01:33:42 -0800293}
294
Brian Carlstrom78128a62011-09-15 17:21:19 -0700295void ImageWriter::CalculateNewObjectOffsetsCallback(Object* obj, void* arg) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700296 DCHECK(obj != NULL);
297 DCHECK(arg != NULL);
298 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700299 if (!image_writer->InSourceSpace(obj)) {
300 return;
301 }
Brian Carlstromc74255f2011-09-11 22:47:39 -0700302
303 // if it is a string, we want to intern it if its not interned.
Elliott Hughesdbb40792011-11-18 17:05:22 -0800304 if (obj->GetClass()->IsStringClass()) {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700305 // we must be an interned string that was forward referenced and already assigned
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800306 if (image_writer->IsImageOffsetAssigned(obj)) {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700307 DCHECK_EQ(obj, obj->AsString()->Intern());
308 return;
309 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700310 SirtRef<String> interned(obj->AsString()->Intern());
311 if (obj != interned.get()) {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800312 if (!image_writer->IsImageOffsetAssigned(interned.get())) {
Brian Carlstromc74255f2011-09-11 22:47:39 -0700313 // interned obj is after us, allocate its location early
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700314 image_writer->AssignImageOffset(interned.get());
Brian Carlstromc74255f2011-09-11 22:47:39 -0700315 }
316 // point those looking for this object to the interned version.
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800317 image_writer->SetImageOffset(obj, image_writer->GetImageOffset(interned.get()));
Brian Carlstromc74255f2011-09-11 22:47:39 -0700318 return;
319 }
320 // else (obj == interned), nothing to do but fall through to the normal case
321 }
322
323 image_writer->AssignImageOffset(obj);
Brian Carlstrom4e777d42011-08-15 13:53:52 -0700324}
325
Brian Carlstrome24fa612011-09-29 00:53:55 -0700326ObjectArray<Object>* ImageWriter::CreateImageRoots() const {
Brian Carlstrom16192862011-09-12 17:50:06 -0700327 Runtime* runtime = Runtime::Current();
328 ClassLinker* class_linker = runtime->GetClassLinker();
329 Class* object_array_class = class_linker->FindSystemClass("[Ljava/lang/Object;");
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700330
331 // build an Object[] of all the DexCaches used in the source_space_
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700332 ObjectArray<Object>* dex_caches = ObjectArray<Object>::Alloc(object_array_class,
Brian Carlstromae826982011-11-09 01:33:42 -0800333 dex_caches_.size());
334 int i = 0;
335 typedef Set::const_iterator It; // TODO: C++0x auto
336 for (It it = dex_caches_.begin(), end = dex_caches_.end(); it != end; ++it, ++i) {
337 dex_caches->Set(i, *it);
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700338 }
339
340 // build an Object[] of the roots needed to restore the runtime
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700341 SirtRef<ObjectArray<Object> > image_roots(
342 ObjectArray<Object>::Alloc(object_array_class, ImageHeader::kImageRootsMax));
Ian Rogers169c9a72011-11-13 20:13:17 -0800343 image_roots->Set(ImageHeader::kJniStubArray, runtime->GetJniDlsymLookupStub());
Brian Carlstrome24fa612011-09-29 00:53:55 -0700344 image_roots->Set(ImageHeader::kAbstractMethodErrorStubArray,
345 runtime->GetAbstractMethodErrorStubArray());
Ian Rogers1cb0a1d2011-10-06 15:24:35 -0700346 image_roots->Set(ImageHeader::kStaticResolutionStubArray,
347 runtime->GetResolutionStubArray(Runtime::kStaticMethod));
348 image_roots->Set(ImageHeader::kUnknownMethodResolutionStubArray,
349 runtime->GetResolutionStubArray(Runtime::kUnknownMethod));
Ian Rogers19846512012-02-24 11:42:47 -0800350 image_roots->Set(ImageHeader::kResolutionMethod, runtime->GetResolutionMethod());
Ian Rogers4f0d07c2011-10-06 23:38:47 -0700351 image_roots->Set(ImageHeader::kCalleeSaveMethod,
352 runtime->GetCalleeSaveMethod(Runtime::kSaveAll));
353 image_roots->Set(ImageHeader::kRefsOnlySaveMethod,
354 runtime->GetCalleeSaveMethod(Runtime::kRefsOnly));
355 image_roots->Set(ImageHeader::kRefsAndArgsSaveMethod,
356 runtime->GetCalleeSaveMethod(Runtime::kRefsAndArgs));
Brian Carlstrome24fa612011-09-29 00:53:55 -0700357 image_roots->Set(ImageHeader::kOatLocation,
358 String::AllocFromModifiedUtf8(oat_file_->GetLocation().c_str()));
Brian Carlstrom58ae9412011-10-04 00:56:06 -0700359 image_roots->Set(ImageHeader::kDexCaches,
360 dex_caches);
Brian Carlstrom34f426c2011-10-04 12:58:02 -0700361 image_roots->Set(ImageHeader::kClassRoots,
362 class_linker->GetClassRoots());
Brian Carlstrome24fa612011-09-29 00:53:55 -0700363 for (int i = 0; i < ImageHeader::kImageRootsMax; i++) {
364 CHECK(image_roots->Get(i) != NULL);
365 }
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700366 return image_roots.get();
Brian Carlstrom16192862011-09-12 17:50:06 -0700367}
368
Brian Carlstrom4e777d42011-08-15 13:53:52 -0700369void ImageWriter::CalculateNewObjectOffsets() {
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700370 SirtRef<ObjectArray<Object> > image_roots(CreateImageRoots());
Brian Carlstrom16192862011-09-12 17:50:06 -0700371
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700372 Heap* heap = Runtime::Current()->GetHeap();
373 typedef std::vector<Space*> SpaceVec;
374 const SpaceVec& spaces = heap->GetSpaces();
375 DCHECK(!spaces.empty());
Ian Rogers30fab402012-01-23 15:43:46 -0800376 DCHECK_EQ(0U, image_end_);
Brian Carlstroma663ea52011-08-19 23:33:41 -0700377
Brian Carlstrom16192862011-09-12 17:50:06 -0700378 // leave space for the header, but do not write it yet, we need to
379 // know where image_roots is going to end up
Ian Rogers30fab402012-01-23 15:43:46 -0800380 image_end_ += RoundUp(sizeof(ImageHeader), 8); // 64-bit-alignment
Brian Carlstroma663ea52011-08-19 23:33:41 -0700381
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700382 // TODO: Image spaces only?
383 for (SpaceVec::const_iterator cur = spaces.begin(); cur != spaces.end(); ++cur) {
384 (*cur)->GetLiveBitmap()->InOrderWalk(CalculateNewObjectOffsetsCallback, this);
385 DCHECK_LT(image_end_, image_->Size());
386 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700387
Brian Carlstrome24fa612011-09-29 00:53:55 -0700388 // Note that image_top_ is left at end of used space
Ian Rogers30fab402012-01-23 15:43:46 -0800389 oat_begin_ = image_begin_ + RoundUp(image_end_, kPageSize);
390 const byte* oat_limit = oat_begin_ + oat_file_->Size();
Brian Carlstrome24fa612011-09-29 00:53:55 -0700391
Brian Carlstrom16192862011-09-12 17:50:06 -0700392 // return to write header at start of image with future location of image_roots
Ian Rogers30fab402012-01-23 15:43:46 -0800393 ImageHeader image_header(reinterpret_cast<uint32_t>(image_begin_),
Brian Carlstrom40381fb2011-10-19 14:13:40 -0700394 reinterpret_cast<uint32_t>(GetImageAddress(image_roots.get())),
Brian Carlstrome24fa612011-09-29 00:53:55 -0700395 oat_file_->GetOatHeader().GetChecksum(),
Ian Rogers30fab402012-01-23 15:43:46 -0800396 reinterpret_cast<uint32_t>(oat_begin_),
Brian Carlstrome24fa612011-09-29 00:53:55 -0700397 reinterpret_cast<uint32_t>(oat_limit));
Ian Rogers30fab402012-01-23 15:43:46 -0800398 memcpy(image_->Begin(), &image_header, sizeof(image_header));
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700399}
400
401void ImageWriter::CopyAndFixupObjects() {
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800402 Heap* heap = Runtime::Current()->GetHeap();
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700403 // TODO: heap validation can't handle this fix up pass
Elliott Hughesb3bd5f02012-03-08 21:05:27 -0800404 heap->DisableObjectValidation();
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700405 // TODO: Image spaces only?
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700406 ReaderMutexLock mu(*GlobalSynchronization::heap_bitmap_lock_);
Mathieu Chartierb062fdd2012-07-03 09:51:48 -0700407 heap->GetLiveBitmap()->Walk(CopyAndFixupObjectsCallback, this);
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700408}
409
Brian Carlstrom78128a62011-09-15 17:21:19 -0700410void ImageWriter::CopyAndFixupObjectsCallback(Object* object, void* arg) {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700411 DCHECK(object != NULL);
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700412 DCHECK(arg != NULL);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700413 const Object* obj = object;
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700414 ImageWriter* image_writer = reinterpret_cast<ImageWriter*>(arg);
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700415 if (!image_writer->InSourceSpace(object)) {
416 return;
417 }
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700418
Brian Carlstrom69b15fb2011-09-03 12:25:21 -0700419 // see GetLocalAddress for similar computation
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700420 size_t offset = image_writer->GetImageOffset(obj);
Ian Rogers30fab402012-01-23 15:43:46 -0800421 byte* dst = image_writer->image_->Begin() + offset;
Brian Carlstrom4873d462011-08-21 15:23:39 -0700422 const byte* src = reinterpret_cast<const byte*>(obj);
Elliott Hughes04b63fd2011-08-16 09:40:10 -0700423 size_t n = obj->SizeOf();
Ian Rogers30fab402012-01-23 15:43:46 -0800424 DCHECK_LT(offset + n, image_writer->image_->Size());
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700425 memcpy(dst, src, n);
426 Object* copy = reinterpret_cast<Object*>(dst);
Elliott Hughesd9c67be2012-02-02 19:54:06 -0800427 copy->monitor_ = 0; // We may have inflated the lock during compilation.
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700428 image_writer->FixupObject(obj, copy);
429}
430
Brian Carlstrom4873d462011-08-21 15:23:39 -0700431void ImageWriter::FixupObject(const Object* orig, Object* copy) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700432 DCHECK(orig != NULL);
433 DCHECK(copy != NULL);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700434 copy->SetClass(down_cast<Class*>(GetImageAddress(orig->GetClass())));
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700435 // TODO: special case init of pointers to malloc data (or removal of these pointers)
436 if (orig->IsClass()) {
437 FixupClass(orig->AsClass(), down_cast<Class*>(copy));
438 } else if (orig->IsObjectArray()) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700439 FixupObjectArray(orig->AsObjectArray<Object>(), down_cast<ObjectArray<Object>*>(copy));
Brian Carlstrom16192862011-09-12 17:50:06 -0700440 } else if (orig->IsMethod()) {
441 FixupMethod(orig->AsMethod(), down_cast<Method*>(copy));
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700442 } else {
443 FixupInstanceFields(orig, copy);
444 }
445}
446
Brian Carlstrom4873d462011-08-21 15:23:39 -0700447void ImageWriter::FixupClass(const Class* orig, Class* copy) {
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700448 FixupInstanceFields(orig, copy);
Brian Carlstrom4873d462011-08-21 15:23:39 -0700449 FixupStaticFields(orig, copy);
Brian Carlstrom9cff8e12011-08-18 16:47:29 -0700450}
451
Brian Carlstrom4873d462011-08-21 15:23:39 -0700452void ImageWriter::FixupMethod(const Method* orig, Method* copy) {
Brian Carlstroma663ea52011-08-19 23:33:41 -0700453 FixupInstanceFields(orig, copy);
Brian Carlstrome24fa612011-09-29 00:53:55 -0700454
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700455 // OatWriter replaces the code_ and invoke_stub_ with offset values.
Ian Rogers30fab402012-01-23 15:43:46 -0800456 // Here we readjust to a pointer relative to oat_begin_
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700457
458 // Every type of method can have an invoke stub
459 uint32_t invoke_stub_offset = orig->GetOatInvokeStubOffset();
Brian Carlstromae826982011-11-09 01:33:42 -0800460 const byte* invoke_stub = GetOatAddress(invoke_stub_offset);
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700461 copy->invoke_stub_ = reinterpret_cast<const Method::InvokeStub*>(invoke_stub);
462
463 if (orig->IsAbstract()) {
464 // Abstract methods are pointed to a stub that will throw AbstractMethodError if they are called
465 ByteArray* orig_ame_stub_array_ = Runtime::Current()->GetAbstractMethodErrorStubArray();
466 ByteArray* copy_ame_stub_array_ = down_cast<ByteArray*>(GetImageAddress(orig_ame_stub_array_));
467 copy->code_ = copy_ame_stub_array_->GetData();
468 return;
469 }
470
Ian Rogers19846512012-02-24 11:42:47 -0800471 if (orig == Runtime::Current()->GetResolutionMethod()) {
472 // The resolution stub's code points at the unknown resolution trampoline
473 ByteArray* orig_res_stub_array_ =
474 Runtime::Current()->GetResolutionStubArray(Runtime::kUnknownMethod);
475 CHECK(orig->GetCode() == orig_res_stub_array_->GetData());
476 ByteArray* copy_res_stub_array_ = down_cast<ByteArray*>(GetImageAddress(orig_res_stub_array_));
477 copy->code_ = copy_res_stub_array_->GetData();
478 return;
479 }
480
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700481 // Non-abstract methods typically have code
482 uint32_t code_offset = orig->GetOatCodeOffset();
Ian Rogers19846512012-02-24 11:42:47 -0800483 const byte* code = NULL;
484 if (orig->IsStatic()) {
485 // Static methods may point at the resolution trampoline stub
486 ByteArray* orig_res_stub_array_ =
487 Runtime::Current()->GetResolutionStubArray(Runtime::kStaticMethod);
488 if (reinterpret_cast<int8_t*>(code_offset) == orig_res_stub_array_->GetData()) {
489 ByteArray* copy_res_stub_array_ = down_cast<ByteArray*>(GetImageAddress(orig_res_stub_array_));
490 code = reinterpret_cast<const byte*>(copy_res_stub_array_->GetData());
491 }
492 }
493 if (code == NULL) {
494 code = GetOatAddress(code_offset);
495 }
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700496 copy->code_ = code;
497
Brian Carlstrom16192862011-09-12 17:50:06 -0700498 if (orig->IsNative()) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700499 // The native method's pointer is directed to a stub to lookup via dlsym.
500 // Note this is not the code_ pointer, that is handled above.
Ian Rogers169c9a72011-11-13 20:13:17 -0800501 ByteArray* orig_jni_stub_array_ = Runtime::Current()->GetJniDlsymLookupStub();
Brian Carlstrom16192862011-09-12 17:50:06 -0700502 ByteArray* copy_jni_stub_array_ = down_cast<ByteArray*>(GetImageAddress(orig_jni_stub_array_));
503 copy->native_method_ = copy_jni_stub_array_->GetData();
504 } else {
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700505 // normal (non-abstract non-native) methods have mapping tables to relocate
506 uint32_t mapping_table_off = orig->GetOatMappingTableOffset();
Brian Carlstromae826982011-11-09 01:33:42 -0800507 const byte* mapping_table = GetOatAddress(mapping_table_off);
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700508 copy->mapping_table_ = reinterpret_cast<const uint32_t*>(mapping_table);
509
510 uint32_t vmap_table_offset = orig->GetOatVmapTableOffset();
Brian Carlstromae826982011-11-09 01:33:42 -0800511 const byte* vmap_table = GetOatAddress(vmap_table_offset);
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700512 copy->vmap_table_ = reinterpret_cast<const uint16_t*>(vmap_table);
Brian Carlstrome7d856b2012-01-11 18:10:55 -0800513
514 uint32_t gc_map_offset = orig->GetOatGcMapOffset();
515 const byte* gc_map = GetOatAddress(gc_map_offset);
516 copy->gc_map_ = reinterpret_cast<const uint8_t*>(gc_map);
Brian Carlstrom16192862011-09-12 17:50:06 -0700517 }
Brian Carlstroma663ea52011-08-19 23:33:41 -0700518}
519
Brian Carlstrom4873d462011-08-21 15:23:39 -0700520void ImageWriter::FixupObjectArray(const ObjectArray<Object>* orig, ObjectArray<Object>* copy) {
Elliott Hughesd8ddfd52011-08-15 14:32:53 -0700521 for (int32_t i = 0; i < orig->GetLength(); ++i) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700522 const Object* element = orig->Get(i);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700523 copy->SetWithoutChecks(i, GetImageAddress(element));
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700524 }
525}
526
Brian Carlstrom4873d462011-08-21 15:23:39 -0700527void ImageWriter::FixupInstanceFields(const Object* orig, Object* copy) {
528 DCHECK(orig != NULL);
529 DCHECK(copy != NULL);
530 Class* klass = orig->GetClass();
531 DCHECK(klass != NULL);
532 FixupFields(orig,
533 copy,
534 klass->GetReferenceInstanceOffsets(),
535 false);
536}
537
538void ImageWriter::FixupStaticFields(const Class* orig, Class* copy) {
539 DCHECK(orig != NULL);
540 DCHECK(copy != NULL);
541 FixupFields(orig,
542 copy,
543 orig->GetReferenceStaticOffsets(),
544 true);
545}
546
547void ImageWriter::FixupFields(const Object* orig,
548 Object* copy,
549 uint32_t ref_offsets,
550 bool is_static) {
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700551 if (ref_offsets != CLASS_WALK_SUPER) {
552 // Found a reference offset bitmap. Fixup the specified offsets.
553 while (ref_offsets != 0) {
554 size_t right_shift = CLZ(ref_offsets);
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700555 MemberOffset byte_offset = CLASS_OFFSET_FROM_CLZ(right_shift);
556 const Object* ref = orig->GetFieldObject<const Object*>(byte_offset, false);
557 copy->SetFieldObject(byte_offset, GetImageAddress(ref), false);
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700558 ref_offsets &= ~(CLASS_HIGH_BIT >> right_shift);
559 }
560 } else {
Brian Carlstrom4873d462011-08-21 15:23:39 -0700561 // There is no reference offset bitmap. In the non-static case,
562 // walk up the class inheritance hierarchy and find reference
563 // offsets the hard way. In the static case, just consider this
564 // class.
565 for (const Class *klass = is_static ? orig->AsClass() : orig->GetClass();
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700566 klass != NULL;
Brian Carlstrom4873d462011-08-21 15:23:39 -0700567 klass = is_static ? NULL : klass->GetSuperClass()) {
568 size_t num_reference_fields = (is_static
569 ? klass->NumReferenceStaticFields()
570 : klass->NumReferenceInstanceFields());
571 for (size_t i = 0; i < num_reference_fields; ++i) {
572 Field* field = (is_static
573 ? klass->GetStaticField(i)
574 : klass->GetInstanceField(i));
Ian Rogers0cfe1fb2011-08-26 03:29:44 -0700575 MemberOffset field_offset = field->GetOffset();
576 const Object* ref = orig->GetFieldObject<const Object*>(field_offset, false);
577 copy->SetFieldObject(field_offset, GetImageAddress(ref), false);
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700578 }
579 }
580 }
581}
582
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700583static Method* GetReferrerMethod(const Compiler::PatchInformation* patch)
584 SHARED_LOCKS_REQUIRED(GlobalSynchronization::mutator_lock_) {
585 ScopedObjectAccessUnchecked soa(Thread::Current());
Brian Carlstromf5822582012-03-19 22:34:31 -0700586 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700587 DexCache* dex_cache = class_linker->FindDexCache(patch->GetDexFile());
Brian Carlstromf5822582012-03-19 22:34:31 -0700588 Method* method = class_linker->ResolveMethod(patch->GetDexFile(),
589 patch->GetReferrerMethodIdx(),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700590 dex_cache,
Brian Carlstromf5822582012-03-19 22:34:31 -0700591 NULL,
592 patch->GetReferrerIsDirect());
593 CHECK(method != NULL)
594 << patch->GetDexFile().GetLocation() << " " << patch->GetReferrerMethodIdx();
Brian Carlstrom0637e272012-03-20 01:07:52 -0700595 CHECK(!method->IsRuntimeMethod())
596 << patch->GetDexFile().GetLocation() << " " << patch->GetReferrerMethodIdx();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700597 CHECK(dex_cache->GetResolvedMethods()->Get(patch->GetReferrerMethodIdx()) == method)
Brian Carlstrom0637e272012-03-20 01:07:52 -0700598 << patch->GetDexFile().GetLocation() << " " << patch->GetReferrerMethodIdx() << " "
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700599 << PrettyMethod(dex_cache->GetResolvedMethods()->Get(patch->GetReferrerMethodIdx())) << " "
Brian Carlstrom0637e272012-03-20 01:07:52 -0700600 << PrettyMethod(method);
Brian Carlstromf5822582012-03-19 22:34:31 -0700601 return method;
602}
603
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700604static Method* GetTargetMethod(const Compiler::PatchInformation* patch)
605 SHARED_LOCKS_REQUIRED(GlobalSynchronization::mutator_lock_) {
Brian Carlstromf5822582012-03-19 22:34:31 -0700606 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700607 DexCache* dex_cache = class_linker->FindDexCache(patch->GetDexFile());
Brian Carlstromf5822582012-03-19 22:34:31 -0700608 Method* method = class_linker->ResolveMethod(patch->GetDexFile(),
609 patch->GetTargetMethodIdx(),
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700610 dex_cache,
Brian Carlstromf5822582012-03-19 22:34:31 -0700611 NULL,
612 patch->GetTargetIsDirect());
613 CHECK(method != NULL)
614 << patch->GetDexFile().GetLocation() << " " << patch->GetTargetMethodIdx();
Brian Carlstrom0637e272012-03-20 01:07:52 -0700615 CHECK(!method->IsRuntimeMethod())
616 << patch->GetDexFile().GetLocation() << " " << patch->GetTargetMethodIdx();
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700617 CHECK(dex_cache->GetResolvedMethods()->Get(patch->GetTargetMethodIdx()) == method)
Brian Carlstrom0637e272012-03-20 01:07:52 -0700618 << patch->GetDexFile().GetLocation() << " " << patch->GetReferrerMethodIdx() << " "
Ian Rogers00f7d0e2012-07-19 15:28:27 -0700619 << PrettyMethod(dex_cache->GetResolvedMethods()->Get(patch->GetTargetMethodIdx())) << " "
Brian Carlstrom0637e272012-03-20 01:07:52 -0700620 << PrettyMethod(method);
Brian Carlstromf5822582012-03-19 22:34:31 -0700621 return method;
622}
623
624void ImageWriter::PatchOatCodeAndMethods(const Compiler& compiler) {
625 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
626
627 const std::vector<const Compiler::PatchInformation*>& code_to_patch = compiler.GetCodeToPatch();
628 for (size_t i = 0; i < code_to_patch.size(); i++) {
629 const Compiler::PatchInformation* patch = code_to_patch[i];
630 Method* target = GetTargetMethod(patch);
631 uint32_t code = reinterpret_cast<uint32_t>(class_linker->GetOatCodeFor(target));
632 uint32_t code_base = reinterpret_cast<uint32_t>(&oat_file_->GetOatHeader());
633 uint32_t code_offset = code - code_base;
634 SetPatchLocation(patch, reinterpret_cast<uint32_t>(GetOatAddress(code_offset)));
635 }
636
637 const std::vector<const Compiler::PatchInformation*>& methods_to_patch
638 = compiler.GetMethodsToPatch();
639 for (size_t i = 0; i < methods_to_patch.size(); i++) {
640 const Compiler::PatchInformation* patch = methods_to_patch[i];
641 Method* target = GetTargetMethod(patch);
642 SetPatchLocation(patch, reinterpret_cast<uint32_t>(GetImageAddress(target)));
643 }
644}
645
646void ImageWriter::SetPatchLocation(const Compiler::PatchInformation* patch, uint32_t value) {
647 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
648 Method* method = GetReferrerMethod(patch);
649 // Goodbye const, we are about to modify some code.
650 void* code = const_cast<void*>(class_linker->GetOatCodeFor(method));
651 // TODO: make this Thumb2 specific
652 uint8_t* base = reinterpret_cast<uint8_t*>(reinterpret_cast<uint32_t>(code) & ~0x1);
653 uint32_t* patch_location = reinterpret_cast<uint32_t*>(base + patch->GetLiteralOffset());
654#ifndef NDEBUG
655 const DexFile::MethodId& id = patch->GetDexFile().GetMethodId(patch->GetTargetMethodIdx());
656 uint32_t expected = reinterpret_cast<uint32_t>(&id);
657 uint32_t actual = *patch_location;
658 CHECK(actual == expected || actual == value) << std::hex
659 << "actual=" << actual
660 << "expected=" << expected
661 << "value=" << value;
662#endif
Elliott Hughesb25c3f62012-03-26 16:35:06 -0700663 *patch_location = value;
Brian Carlstromf5822582012-03-19 22:34:31 -0700664}
665
Brian Carlstromdb4d5402011-08-09 12:18:28 -0700666} // namespace art