blob: c6beb3617839a6916700742460b438214f23df7a [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 Carlstrome24fa612011-09-29 00:53:55 -070016
17#include "oat_writer.h"
18
Elliott Hughesa0e18062012-04-13 15:59:59 -070019#include <zlib.h>
20
Ian Rogerse77493c2014-08-20 15:08:45 -070021#include "base/allocator.h"
Brian Carlstromba150c32013-08-27 17:31:03 -070022#include "base/bit_vector.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080023#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080024#include "base/unix_file/fd_file.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070025#include "class_linker.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070026#include "compiled_class.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070027#include "dex_file-inl.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000028#include "dex/verification_results.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070029#include "gc/space/space.h"
Vladimir Markof4da6752014-08-01 19:04:18 +010030#include "image_writer.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070031#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080032#include "mirror/array.h"
33#include "mirror/class_loader.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070034#include "mirror/object-inl.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070035#include "os.h"
Brian Carlstromcd60ac72013-01-20 17:09:51 -080036#include "output_stream.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070037#include "safe_map.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070038#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070039#include "handle_scope-inl.h"
Vladimir Markof4da6752014-08-01 19:04:18 +010040#include "utils/arm/assembler_thumb2.h"
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +010041#include "utils/arm64/assembler_arm64.h"
jeffhaoec014232012-09-05 10:42:25 -070042#include "verifier/method_verifier.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070043
44namespace art {
45
Vladimir Markof4da6752014-08-01 19:04:18 +010046class OatWriter::RelativeCallPatcher {
47 public:
48 virtual ~RelativeCallPatcher() { }
49
50 // Reserve space for relative call thunks if needed, return adjusted offset.
51 // After all methods have been processed it's call one last time with compiled_method == nullptr.
52 virtual uint32_t ReserveSpace(uint32_t offset, const CompiledMethod* compiled_method) = 0;
53
54 // Write relative call thunks if needed, return adjusted offset.
55 virtual uint32_t WriteThunks(OutputStream* out, uint32_t offset) = 0;
56
57 // Patch method code. The input displacement is relative to the patched location,
58 // the patcher may need to adjust it if the correct base is different.
59 virtual void Patch(std::vector<uint8_t>* code, uint32_t literal_offset, uint32_t patch_offset,
60 uint32_t target_offset) = 0;
61
62 protected:
63 RelativeCallPatcher() { }
64
65 private:
66 DISALLOW_COPY_AND_ASSIGN(RelativeCallPatcher);
67};
68
69class OatWriter::NoRelativeCallPatcher FINAL : public RelativeCallPatcher {
70 public:
71 NoRelativeCallPatcher() { }
72
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070073 uint32_t ReserveSpace(uint32_t offset,
74 const CompiledMethod* compiled_method ATTRIBUTE_UNUSED) OVERRIDE {
Vladimir Markof4da6752014-08-01 19:04:18 +010075 return offset; // No space reserved; no patches expected.
76 }
77
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070078 uint32_t WriteThunks(OutputStream* out ATTRIBUTE_UNUSED, uint32_t offset) OVERRIDE {
Vladimir Markof4da6752014-08-01 19:04:18 +010079 return offset; // No thunks added; no patches expected.
80 }
81
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070082 void Patch(std::vector<uint8_t>* code ATTRIBUTE_UNUSED, uint32_t literal_offset ATTRIBUTE_UNUSED,
83 uint32_t patch_offset ATTRIBUTE_UNUSED,
84 uint32_t target_offset ATTRIBUTE_UNUSED) OVERRIDE {
Vladimir Markof4da6752014-08-01 19:04:18 +010085 LOG(FATAL) << "Unexpected relative patch.";
86 }
87
88 private:
89 DISALLOW_COPY_AND_ASSIGN(NoRelativeCallPatcher);
90};
91
92class OatWriter::X86RelativeCallPatcher FINAL : public RelativeCallPatcher {
93 public:
94 X86RelativeCallPatcher() { }
95
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070096 uint32_t ReserveSpace(uint32_t offset,
97 const CompiledMethod* compiled_method ATTRIBUTE_UNUSED) OVERRIDE {
Vladimir Markof4da6752014-08-01 19:04:18 +010098 return offset; // No space reserved; no limit on relative call distance.
99 }
100
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700101 uint32_t WriteThunks(OutputStream* out ATTRIBUTE_UNUSED, uint32_t offset) OVERRIDE {
Vladimir Markof4da6752014-08-01 19:04:18 +0100102 return offset; // No thunks added; no limit on relative call distance.
103 }
104
105 void Patch(std::vector<uint8_t>* code, uint32_t literal_offset, uint32_t patch_offset,
106 uint32_t target_offset) OVERRIDE {
107 DCHECK_LE(literal_offset + 4u, code->size());
108 // Unsigned arithmetic with its well-defined overflow behavior is just fine here.
109 uint32_t displacement = target_offset - patch_offset;
110 displacement -= kPcDisplacement; // The base PC is at the end of the 4-byte patch.
111
112 typedef __attribute__((__aligned__(1))) int32_t unaligned_int32_t;
113 reinterpret_cast<unaligned_int32_t*>(&(*code)[literal_offset])[0] = displacement;
114 }
115
116 private:
117 // PC displacement from patch location; x86 PC for relative calls points to the next
118 // instruction and the patch location is 4 bytes earlier.
119 static constexpr int32_t kPcDisplacement = 4;
120
121 DISALLOW_COPY_AND_ASSIGN(X86RelativeCallPatcher);
122};
123
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100124class OatWriter::ArmBaseRelativeCallPatcher : public RelativeCallPatcher {
Vladimir Markof4da6752014-08-01 19:04:18 +0100125 public:
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100126 ArmBaseRelativeCallPatcher(OatWriter* writer,
127 InstructionSet instruction_set, std::vector<uint8_t> thunk_code,
128 uint32_t max_positive_displacement, uint32_t max_negative_displacement)
129 : writer_(writer), instruction_set_(instruction_set), thunk_code_(thunk_code),
130 max_positive_displacement_(max_positive_displacement),
131 max_negative_displacement_(max_negative_displacement),
Vladimir Markof4da6752014-08-01 19:04:18 +0100132 thunk_locations_(), current_thunk_to_write_(0u), unprocessed_patches_() {
133 }
134
135 uint32_t ReserveSpace(uint32_t offset, const CompiledMethod* compiled_method) OVERRIDE {
136 // NOTE: The final thunk can be reserved from InitCodeMethodVisitor::EndClass() while it
137 // may be written early by WriteCodeMethodVisitor::VisitMethod() for a deduplicated chunk
138 // of code. To avoid any alignment discrepancies for the final chunk, we always align the
139 // offset after reserving of writing any chunk.
140 if (UNLIKELY(compiled_method == nullptr)) {
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100141 uint32_t aligned_offset = CompiledMethod::AlignCode(offset, instruction_set_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100142 bool needs_thunk = ReserveSpaceProcessPatches(aligned_offset);
143 if (needs_thunk) {
144 thunk_locations_.push_back(aligned_offset);
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100145 offset = CompiledMethod::AlignCode(aligned_offset + thunk_code_.size(), instruction_set_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100146 }
147 return offset;
148 }
149 DCHECK(compiled_method->GetQuickCode() != nullptr);
150 uint32_t quick_code_size = compiled_method->GetQuickCode()->size();
151 uint32_t quick_code_offset = compiled_method->AlignCode(offset) + sizeof(OatQuickMethodHeader);
152 uint32_t next_aligned_offset = compiled_method->AlignCode(quick_code_offset + quick_code_size);
153 if (!unprocessed_patches_.empty() &&
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100154 next_aligned_offset - unprocessed_patches_.front().second > max_positive_displacement_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100155 bool needs_thunk = ReserveSpaceProcessPatches(next_aligned_offset);
156 if (needs_thunk) {
157 // A single thunk will cover all pending patches.
158 unprocessed_patches_.clear();
159 uint32_t thunk_location = compiled_method->AlignCode(offset);
160 thunk_locations_.push_back(thunk_location);
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100161 offset = CompiledMethod::AlignCode(thunk_location + thunk_code_.size(), instruction_set_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100162 }
163 }
164 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
165 if (patch.Type() == kLinkerPatchCallRelative) {
166 unprocessed_patches_.emplace_back(patch.TargetMethod(),
167 quick_code_offset + patch.LiteralOffset());
168 }
169 }
170 return offset;
171 }
172
173 uint32_t WriteThunks(OutputStream* out, uint32_t offset) OVERRIDE {
174 if (current_thunk_to_write_ == thunk_locations_.size()) {
175 return offset;
176 }
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100177 uint32_t aligned_offset = CompiledMethod::AlignCode(offset, instruction_set_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100178 if (UNLIKELY(aligned_offset == thunk_locations_[current_thunk_to_write_])) {
179 ++current_thunk_to_write_;
180 uint32_t aligned_code_delta = aligned_offset - offset;
181 if (aligned_code_delta != 0u && !writer_->WriteCodeAlignment(out, aligned_code_delta)) {
182 return 0u;
183 }
184 if (!out->WriteFully(thunk_code_.data(), thunk_code_.size())) {
185 return 0u;
186 }
187 writer_->size_relative_call_thunks_ += thunk_code_.size();
188 uint32_t thunk_end_offset = aligned_offset + thunk_code_.size();
189 // Align after writing chunk, see the ReserveSpace() above.
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100190 offset = CompiledMethod::AlignCode(thunk_end_offset, instruction_set_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100191 aligned_code_delta = offset - thunk_end_offset;
192 if (aligned_code_delta != 0u && !writer_->WriteCodeAlignment(out, aligned_code_delta)) {
193 return 0u;
194 }
195 }
196 return offset;
197 }
198
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100199 protected:
200 uint32_t CalculateDisplacement(uint32_t patch_offset, uint32_t target_offset) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100201 // Unsigned arithmetic with its well-defined overflow behavior is just fine here.
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100202 uint32_t displacement = target_offset - patch_offset;
Vladimir Markof4da6752014-08-01 19:04:18 +0100203 // NOTE: With unsigned arithmetic we do mean to use && rather than || below.
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100204 if (displacement > max_positive_displacement_ && displacement < -max_negative_displacement_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100205 // Unwritten thunks have higher offsets, check if it's within range.
206 DCHECK(current_thunk_to_write_ == thunk_locations_.size() ||
207 thunk_locations_[current_thunk_to_write_] > patch_offset);
208 if (current_thunk_to_write_ != thunk_locations_.size() &&
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100209 thunk_locations_[current_thunk_to_write_] - patch_offset < max_positive_displacement_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100210 displacement = thunk_locations_[current_thunk_to_write_] - patch_offset;
211 } else {
212 // We must have a previous thunk then.
213 DCHECK_NE(current_thunk_to_write_, 0u);
214 DCHECK_LT(thunk_locations_[current_thunk_to_write_ - 1], patch_offset);
215 displacement = thunk_locations_[current_thunk_to_write_ - 1] - patch_offset;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100216 DCHECK(displacement >= -max_negative_displacement_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100217 }
218 }
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100219 return displacement;
220 }
221
222 private:
223 bool ReserveSpaceProcessPatches(uint32_t next_aligned_offset) {
224 // Process as many patches as possible, stop only on unresolved targets or calls too far back.
225 while (!unprocessed_patches_.empty()) {
226 uint32_t patch_offset = unprocessed_patches_.front().second;
227 auto it = writer_->method_offset_map_.find(unprocessed_patches_.front().first);
228 if (it == writer_->method_offset_map_.end()) {
229 // If still unresolved, check if we have a thunk within range.
230 DCHECK(thunk_locations_.empty() || thunk_locations_.back() <= patch_offset);
231 if (thunk_locations_.empty() ||
232 patch_offset - thunk_locations_.back() > max_negative_displacement_) {
233 return next_aligned_offset - patch_offset > max_positive_displacement_;
234 }
235 } else if (it->second >= patch_offset) {
236 DCHECK_LE(it->second - patch_offset, max_positive_displacement_);
237 } else {
238 // When calling back, check if we have a thunk that's closer than the actual target.
239 uint32_t target_offset = (thunk_locations_.empty() || it->second > thunk_locations_.back())
240 ? it->second
241 : thunk_locations_.back();
242 DCHECK_GT(patch_offset, target_offset);
243 if (patch_offset - target_offset > max_negative_displacement_) {
244 return true;
245 }
246 }
247 unprocessed_patches_.pop_front();
248 }
249 return false;
250 }
251
252 OatWriter* const writer_;
253 const InstructionSet instruction_set_;
254 const std::vector<uint8_t> thunk_code_;
255 const uint32_t max_positive_displacement_;
256 const uint32_t max_negative_displacement_;
257 std::vector<uint32_t> thunk_locations_;
258 size_t current_thunk_to_write_;
259
260 // ReserveSpace() tracks unprocessed patches.
261 typedef std::pair<MethodReference, uint32_t> UnprocessedPatch;
262 std::deque<UnprocessedPatch> unprocessed_patches_;
263
264 DISALLOW_COPY_AND_ASSIGN(ArmBaseRelativeCallPatcher);
265};
266
267class OatWriter::Thumb2RelativeCallPatcher FINAL : public ArmBaseRelativeCallPatcher {
268 public:
269 explicit Thumb2RelativeCallPatcher(OatWriter* writer)
270 : ArmBaseRelativeCallPatcher(writer, kThumb2, CompileThunkCode(),
271 kMaxPositiveDisplacement, kMaxNegativeDisplacement) {
272 }
273
274 void Patch(std::vector<uint8_t>* code, uint32_t literal_offset, uint32_t patch_offset,
275 uint32_t target_offset) OVERRIDE {
276 DCHECK_LE(literal_offset + 4u, code->size());
277 DCHECK_EQ(literal_offset & 1u, 0u);
278 DCHECK_EQ(patch_offset & 1u, 0u);
279 DCHECK_EQ(target_offset & 1u, 1u); // Thumb2 mode bit.
280 uint32_t displacement = CalculateDisplacement(patch_offset, target_offset & ~1u);
Vladimir Markof4da6752014-08-01 19:04:18 +0100281 displacement -= kPcDisplacement; // The base PC is at the end of the 4-byte patch.
282 DCHECK_EQ(displacement & 1u, 0u);
283 DCHECK((displacement >> 24) == 0u || (displacement >> 24) == 255u); // 25-bit signed.
284 uint32_t signbit = (displacement >> 31) & 0x1;
285 uint32_t i1 = (displacement >> 23) & 0x1;
286 uint32_t i2 = (displacement >> 22) & 0x1;
287 uint32_t imm10 = (displacement >> 12) & 0x03ff;
288 uint32_t imm11 = (displacement >> 1) & 0x07ff;
289 uint32_t j1 = i1 ^ (signbit ^ 1);
290 uint32_t j2 = i2 ^ (signbit ^ 1);
291 uint32_t value = (signbit << 26) | (j1 << 13) | (j2 << 11) | (imm10 << 16) | imm11;
292 value |= 0xf000d000; // BL
293
294 uint8_t* addr = &(*code)[literal_offset];
295 // Check that we're just overwriting an existing BL.
296 DCHECK_EQ(addr[1] & 0xf8, 0xf0);
297 DCHECK_EQ(addr[3] & 0xd0, 0xd0);
298 // Write the new BL.
299 addr[0] = (value >> 16) & 0xff;
300 addr[1] = (value >> 24) & 0xff;
301 addr[2] = (value >> 0) & 0xff;
302 addr[3] = (value >> 8) & 0xff;
303 }
304
305 private:
Vladimir Markof4da6752014-08-01 19:04:18 +0100306 static std::vector<uint8_t> CompileThunkCode() {
307 // The thunk just uses the entry point in the ArtMethod. This works even for calls
308 // to the generic JNI and interpreter trampolines.
309 arm::Thumb2Assembler assembler;
310 assembler.LoadFromOffset(
311 arm::kLoadWord, arm::PC, arm::R0,
Mathieu Chartier2d721012014-11-10 11:08:06 -0800312 mirror::ArtMethod::EntryPointFromQuickCompiledCodeOffset(kArmPointerSize).Int32Value());
Vladimir Markof4da6752014-08-01 19:04:18 +0100313 assembler.bkpt(0);
314 std::vector<uint8_t> thunk_code(assembler.CodeSize());
315 MemoryRegion code(thunk_code.data(), thunk_code.size());
316 assembler.FinalizeInstructions(code);
317 return thunk_code;
318 }
319
320 // PC displacement from patch location; Thumb2 PC is always at instruction address + 4.
321 static constexpr int32_t kPcDisplacement = 4;
322
323 // Maximum positive and negative displacement measured from the patch location.
324 // (Signed 25 bit displacement with the last bit 0 has range [-2^24, 2^24-2] measured from
325 // the Thumb2 PC pointing right after the BL, i.e. 4 bytes later than the patch location.)
326 static constexpr uint32_t kMaxPositiveDisplacement = (1u << 24) - 2 + kPcDisplacement;
327 static constexpr uint32_t kMaxNegativeDisplacement = (1u << 24) - kPcDisplacement;
328
Vladimir Markof4da6752014-08-01 19:04:18 +0100329 DISALLOW_COPY_AND_ASSIGN(Thumb2RelativeCallPatcher);
330};
331
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100332class OatWriter::Arm64RelativeCallPatcher FINAL : public ArmBaseRelativeCallPatcher {
333 public:
334 explicit Arm64RelativeCallPatcher(OatWriter* writer)
335 : ArmBaseRelativeCallPatcher(writer, kArm64, CompileThunkCode(),
336 kMaxPositiveDisplacement, kMaxNegativeDisplacement) {
337 }
338
339 void Patch(std::vector<uint8_t>* code, uint32_t literal_offset, uint32_t patch_offset,
340 uint32_t target_offset) OVERRIDE {
341 DCHECK_LE(literal_offset + 4u, code->size());
342 DCHECK_EQ(literal_offset & 3u, 0u);
343 DCHECK_EQ(patch_offset & 3u, 0u);
344 DCHECK_EQ(target_offset & 3u, 0u);
345 uint32_t displacement = CalculateDisplacement(patch_offset, target_offset & ~1u);
346 DCHECK_EQ(displacement & 3u, 0u);
347 DCHECK((displacement >> 27) == 0u || (displacement >> 27) == 31u); // 28-bit signed.
348 uint32_t value = (displacement & 0x0fffffffu) >> 2;
349 value |= 0x94000000; // BL
350
351 uint8_t* addr = &(*code)[literal_offset];
352 // Check that we're just overwriting an existing BL.
353 DCHECK_EQ(addr[3] & 0xfc, 0x94);
354 // Write the new BL.
355 addr[0] = (value >> 0) & 0xff;
356 addr[1] = (value >> 8) & 0xff;
357 addr[2] = (value >> 16) & 0xff;
358 addr[3] = (value >> 24) & 0xff;
359 }
360
361 private:
362 static std::vector<uint8_t> CompileThunkCode() {
363 // The thunk just uses the entry point in the ArtMethod. This works even for calls
364 // to the generic JNI and interpreter trampolines.
365 arm64::Arm64Assembler assembler;
Mathieu Chartier2d721012014-11-10 11:08:06 -0800366 Offset offset(mirror::ArtMethod::EntryPointFromQuickCompiledCodeOffset(
367 kArm64PointerSize).Int32Value());
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100368 assembler.JumpTo(ManagedRegister(arm64::X0), offset, ManagedRegister(arm64::IP0));
369 std::vector<uint8_t> thunk_code(assembler.CodeSize());
370 MemoryRegion code(thunk_code.data(), thunk_code.size());
371 assembler.FinalizeInstructions(code);
372 return thunk_code;
373 }
374
375 // Maximum positive and negative displacement measured from the patch location.
376 // (Signed 28 bit displacement with the last bit 0 has range [-2^27, 2^27-4] measured from
377 // the ARM64 PC pointing to the BL.)
378 static constexpr uint32_t kMaxPositiveDisplacement = (1u << 27) - 4u;
379 static constexpr uint32_t kMaxNegativeDisplacement = (1u << 27);
380
381 DISALLOW_COPY_AND_ASSIGN(Arm64RelativeCallPatcher);
382};
383
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100384#define DCHECK_OFFSET() \
385 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
386 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
387
388#define DCHECK_OFFSET_() \
389 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
390 << "file_offset=" << file_offset << " offset_=" << offset_
391
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700392OatWriter::OatWriter(const std::vector<const DexFile*>& dex_files,
Brian Carlstrom28db0122012-10-18 16:20:41 -0700393 uint32_t image_file_location_oat_checksum,
Ian Rogersef7d42f2014-01-06 12:55:46 -0800394 uintptr_t image_file_location_oat_begin,
Alex Lighta59dd802014-07-02 16:28:08 -0700395 int32_t image_patch_delta,
Ian Rogersca368cb2013-11-15 15:52:08 -0800396 const CompilerDriver* compiler,
Vladimir Markof4da6752014-08-01 19:04:18 +0100397 ImageWriter* image_writer,
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700398 TimingLogger* timings,
399 SafeMap<std::string, std::string>* key_value_store)
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700400 : compiler_driver_(compiler),
Vladimir Markof4da6752014-08-01 19:04:18 +0100401 image_writer_(image_writer),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700402 dex_files_(&dex_files),
Vladimir Markof4da6752014-08-01 19:04:18 +0100403 size_(0u),
404 oat_data_offset_(0u),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700405 image_file_location_oat_checksum_(image_file_location_oat_checksum),
406 image_file_location_oat_begin_(image_file_location_oat_begin),
Alex Lighta59dd802014-07-02 16:28:08 -0700407 image_patch_delta_(image_patch_delta),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700408 key_value_store_(key_value_store),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700409 oat_header_(NULL),
410 size_dex_file_alignment_(0),
411 size_executable_offset_alignment_(0),
412 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700413 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700414 size_dex_file_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700415 size_interpreter_to_interpreter_bridge_(0),
416 size_interpreter_to_compiled_code_bridge_(0),
417 size_jni_dlsym_lookup_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700418 size_portable_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700419 size_portable_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700420 size_portable_to_interpreter_bridge_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800421 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700422 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700423 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700424 size_quick_to_interpreter_bridge_(0),
425 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100426 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700427 size_code_(0),
428 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100429 size_relative_call_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700430 size_mapping_table_(0),
431 size_vmap_table_(0),
432 size_gc_map_(0),
433 size_oat_dex_file_location_size_(0),
434 size_oat_dex_file_location_data_(0),
435 size_oat_dex_file_location_checksum_(0),
436 size_oat_dex_file_offset_(0),
437 size_oat_dex_file_methods_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700438 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700439 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700440 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100441 size_oat_class_method_offsets_(0),
442 method_offset_map_() {
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700443 CHECK(key_value_store != nullptr);
444
Vladimir Markof4da6752014-08-01 19:04:18 +0100445 switch (compiler_driver_->GetInstructionSet()) {
446 case kX86:
447 case kX86_64:
448 relative_call_patcher_.reset(new X86RelativeCallPatcher);
449 break;
450 case kArm:
451 // Fall through: we generate Thumb2 code for "arm".
452 case kThumb2:
453 relative_call_patcher_.reset(new Thumb2RelativeCallPatcher(this));
454 break;
455 case kArm64:
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100456 relative_call_patcher_.reset(new Arm64RelativeCallPatcher(this));
457 break;
Vladimir Markof4da6752014-08-01 19:04:18 +0100458 default:
459 relative_call_patcher_.reset(new NoRelativeCallPatcher);
460 break;
461 }
462
Ian Rogersca368cb2013-11-15 15:52:08 -0800463 size_t offset;
464 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700465 TimingLogger::ScopedTiming split("InitOatHeader", timings);
Ian Rogersca368cb2013-11-15 15:52:08 -0800466 offset = InitOatHeader();
467 }
468 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700469 TimingLogger::ScopedTiming split("InitOatDexFiles", timings);
Ian Rogersca368cb2013-11-15 15:52:08 -0800470 offset = InitOatDexFiles(offset);
471 }
472 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700473 TimingLogger::ScopedTiming split("InitDexFiles", timings);
Ian Rogersca368cb2013-11-15 15:52:08 -0800474 offset = InitDexFiles(offset);
475 }
476 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700477 TimingLogger::ScopedTiming split("InitOatClasses", timings);
Ian Rogersca368cb2013-11-15 15:52:08 -0800478 offset = InitOatClasses(offset);
479 }
480 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700481 TimingLogger::ScopedTiming split("InitOatMaps", timings);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100482 offset = InitOatMaps(offset);
483 }
484 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700485 TimingLogger::ScopedTiming split("InitOatCode", timings);
Ian Rogersca368cb2013-11-15 15:52:08 -0800486 offset = InitOatCode(offset);
487 }
488 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700489 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings);
Ian Rogersca368cb2013-11-15 15:52:08 -0800490 offset = InitOatCodeDexFiles(offset);
491 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700492 size_ = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700493
494 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Vladimir Markof4da6752014-08-01 19:04:18 +0100495 CHECK_EQ(compiler->IsImage(), image_writer_ != nullptr);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700496 CHECK_EQ(compiler->IsImage(),
497 key_value_store_->find(OatHeader::kImageLocationKey) == key_value_store_->end());
Alex Lighta59dd802014-07-02 16:28:08 -0700498 CHECK_ALIGNED(image_patch_delta_, kPageSize);
Brian Carlstrome24fa612011-09-29 00:53:55 -0700499}
500
Ian Rogers0571d352011-11-03 19:51:38 -0700501OatWriter::~OatWriter() {
502 delete oat_header_;
503 STLDeleteElements(&oat_dex_files_);
Brian Carlstrom389efb02012-01-11 12:06:26 -0800504 STLDeleteElements(&oat_classes_);
Ian Rogers0571d352011-11-03 19:51:38 -0700505}
506
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100507struct OatWriter::GcMapDataAccess {
508 static const std::vector<uint8_t>* GetData(const CompiledMethod* compiled_method) ALWAYS_INLINE {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100509 return compiled_method->GetGcMap();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100510 }
511
512 static uint32_t GetOffset(OatClass* oat_class, size_t method_offsets_index) ALWAYS_INLINE {
513 return oat_class->method_offsets_[method_offsets_index].gc_map_offset_;
514 }
515
516 static void SetOffset(OatClass* oat_class, size_t method_offsets_index, uint32_t offset)
517 ALWAYS_INLINE {
518 oat_class->method_offsets_[method_offsets_index].gc_map_offset_ = offset;
519 }
520
521 static const char* Name() ALWAYS_INLINE {
522 return "GC map";
523 }
524};
525
526struct OatWriter::MappingTableDataAccess {
527 static const std::vector<uint8_t>* GetData(const CompiledMethod* compiled_method) ALWAYS_INLINE {
528 return &compiled_method->GetMappingTable();
529 }
530
531 static uint32_t GetOffset(OatClass* oat_class, size_t method_offsets_index) ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100532 uint32_t offset = oat_class->method_headers_[method_offsets_index].mapping_table_offset_;
533 return offset == 0u ? 0u :
534 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100535 }
536
537 static void SetOffset(OatClass* oat_class, size_t method_offsets_index, uint32_t offset)
538 ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100539 oat_class->method_headers_[method_offsets_index].mapping_table_offset_ =
540 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100541 }
542
543 static const char* Name() ALWAYS_INLINE {
544 return "mapping table";
545 }
546};
547
548struct OatWriter::VmapTableDataAccess {
549 static const std::vector<uint8_t>* GetData(const CompiledMethod* compiled_method) ALWAYS_INLINE {
550 return &compiled_method->GetVmapTable();
551 }
552
553 static uint32_t GetOffset(OatClass* oat_class, size_t method_offsets_index) ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100554 uint32_t offset = oat_class->method_headers_[method_offsets_index].vmap_table_offset_;
555 return offset == 0u ? 0u :
556 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100557 }
558
559 static void SetOffset(OatClass* oat_class, size_t method_offsets_index, uint32_t offset)
560 ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100561 oat_class->method_headers_[method_offsets_index].vmap_table_offset_ =
562 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100563 }
564
565 static const char* Name() ALWAYS_INLINE {
566 return "vmap table";
567 }
568};
569
570class OatWriter::DexMethodVisitor {
571 public:
572 DexMethodVisitor(OatWriter* writer, size_t offset)
573 : writer_(writer),
574 offset_(offset),
575 dex_file_(nullptr),
576 class_def_index_(DexFile::kDexNoIndex) {
577 }
578
579 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
580 DCHECK(dex_file_ == nullptr);
581 DCHECK_EQ(class_def_index_, DexFile::kDexNoIndex);
582 dex_file_ = dex_file;
583 class_def_index_ = class_def_index;
584 return true;
585 }
586
587 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
588
589 virtual bool EndClass() {
590 if (kIsDebugBuild) {
591 dex_file_ = nullptr;
592 class_def_index_ = DexFile::kDexNoIndex;
593 }
594 return true;
595 }
596
597 size_t GetOffset() const {
598 return offset_;
599 }
600
601 protected:
602 virtual ~DexMethodVisitor() { }
603
604 OatWriter* const writer_;
605
606 // The offset is usually advanced for each visited method by the derived class.
607 size_t offset_;
608
609 // The dex file and class def index are set in StartClass().
610 const DexFile* dex_file_;
611 size_t class_def_index_;
612};
613
614class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
615 public:
616 OatDexMethodVisitor(OatWriter* writer, size_t offset)
617 : DexMethodVisitor(writer, offset),
618 oat_class_index_(0u),
619 method_offsets_index_(0u) {
620 }
621
622 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
623 DexMethodVisitor::StartClass(dex_file, class_def_index);
624 DCHECK_LT(oat_class_index_, writer_->oat_classes_.size());
625 method_offsets_index_ = 0u;
626 return true;
627 }
628
629 bool EndClass() {
630 ++oat_class_index_;
631 return DexMethodVisitor::EndClass();
632 }
633
634 protected:
635 size_t oat_class_index_;
636 size_t method_offsets_index_;
637};
638
639class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
640 public:
641 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
642 : DexMethodVisitor(writer, offset),
643 compiled_methods_(),
644 num_non_null_compiled_methods_(0u) {
645 compiled_methods_.reserve(256u);
646 }
647
648 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
649 DexMethodVisitor::StartClass(dex_file, class_def_index);
650 compiled_methods_.clear();
651 num_non_null_compiled_methods_ = 0u;
652 return true;
653 }
654
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700655 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED, const ClassDataItemIterator& it) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100656 // Fill in the compiled_methods_ array for methods that have a
657 // CompiledMethod. We track the number of non-null entries in
658 // num_non_null_compiled_methods_ since we only want to allocate
659 // OatMethodOffsets for the compiled methods.
660 uint32_t method_idx = it.GetMemberIndex();
661 CompiledMethod* compiled_method =
662 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
663 compiled_methods_.push_back(compiled_method);
664 if (compiled_method != nullptr) {
665 ++num_non_null_compiled_methods_;
666 }
667 return true;
668 }
669
670 bool EndClass() {
671 ClassReference class_ref(dex_file_, class_def_index_);
672 CompiledClass* compiled_class = writer_->compiler_driver_->GetCompiledClass(class_ref);
673 mirror::Class::Status status;
674 if (compiled_class != NULL) {
675 status = compiled_class->GetStatus();
676 } else if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
677 status = mirror::Class::kStatusError;
678 } else {
679 status = mirror::Class::kStatusNotReady;
680 }
681
682 OatClass* oat_class = new OatClass(offset_, compiled_methods_,
683 num_non_null_compiled_methods_, status);
684 writer_->oat_classes_.push_back(oat_class);
Vladimir Markof4da6752014-08-01 19:04:18 +0100685 oat_class->UpdateChecksum(writer_->oat_header_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100686 offset_ += oat_class->SizeOf();
687 return DexMethodVisitor::EndClass();
688 }
689
690 private:
691 std::vector<CompiledMethod*> compiled_methods_;
692 size_t num_non_null_compiled_methods_;
693};
694
695class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
696 public:
697 InitCodeMethodVisitor(OatWriter* writer, size_t offset)
698 : OatDexMethodVisitor(writer, offset) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100699 writer_->absolute_patch_locations_.reserve(
700 writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
701 }
702
703 bool EndClass() {
704 OatDexMethodVisitor::EndClass();
705 if (oat_class_index_ == writer_->oat_classes_.size()) {
706 offset_ = writer_->relative_call_patcher_->ReserveSpace(offset_, nullptr);
707 }
708 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100709 }
710
711 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
712 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
713 OatClass* oat_class = writer_->oat_classes_[oat_class_index_];
714 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
715
716 if (compiled_method != nullptr) {
717 // Derived from CompiledMethod.
718 uint32_t quick_code_offset = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100719
720 const std::vector<uint8_t>* portable_code = compiled_method->GetPortableCode();
721 const std::vector<uint8_t>* quick_code = compiled_method->GetQuickCode();
722 if (portable_code != nullptr) {
723 CHECK(quick_code == nullptr);
724 size_t oat_method_offsets_offset =
725 oat_class->GetOatMethodOffsetsOffsetFromOatHeader(class_def_method_index);
726 compiled_method->AddOatdataOffsetToCompliledCodeOffset(
727 oat_method_offsets_offset + OFFSETOF_MEMBER(OatMethodOffsets, code_offset_));
728 } else {
729 CHECK(quick_code != nullptr);
Vladimir Markof4da6752014-08-01 19:04:18 +0100730 offset_ = writer_->relative_call_patcher_->ReserveSpace(offset_, compiled_method);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100731 offset_ = compiled_method->AlignCode(offset_);
732 DCHECK_ALIGNED_PARAM(offset_,
733 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
734 uint32_t code_size = quick_code->size() * sizeof(uint8_t);
735 CHECK_NE(code_size, 0U);
736 uint32_t thumb_offset = compiled_method->CodeDelta();
Vladimir Marko7624d252014-05-02 14:40:15 +0100737 quick_code_offset = offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100738
Alex Light78382fa2014-06-06 15:45:32 -0700739 bool deduped = false;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100740
741 // Deduplicate code arrays.
Vladimir Markobd72fc12014-07-09 16:06:40 +0100742 auto lb = dedupe_map_.lower_bound(compiled_method);
743 if (lb != dedupe_map_.end() && !dedupe_map_.key_comp()(compiled_method, lb->first)) {
744 quick_code_offset = lb->second;
Alex Light78382fa2014-06-06 15:45:32 -0700745 deduped = true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100746 } else {
Vladimir Markobd72fc12014-07-09 16:06:40 +0100747 dedupe_map_.PutBefore(lb, compiled_method, quick_code_offset);
Vladimir Marko7624d252014-05-02 14:40:15 +0100748 }
749
Vladimir Markof4da6752014-08-01 19:04:18 +0100750 MethodReference method_ref(dex_file_, it.GetMemberIndex());
751 auto method_lb = writer_->method_offset_map_.lower_bound(method_ref);
752 if (method_lb != writer_->method_offset_map_.end() &&
753 !writer_->method_offset_map_.key_comp()(method_ref, method_lb->first)) {
754 // TODO: Should this be a hard failure?
755 LOG(WARNING) << "Multiple definitions of "
756 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file)
757 << ((method_lb->second != quick_code_offset) ? "; OFFSET MISMATCH" : "");
758 } else {
759 writer_->method_offset_map_.PutBefore(method_lb, method_ref, quick_code_offset);
760 }
761
Vladimir Marko7624d252014-05-02 14:40:15 +0100762 // Update quick method header.
763 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
764 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
765 uint32_t mapping_table_offset = method_header->mapping_table_offset_;
766 uint32_t vmap_table_offset = method_header->vmap_table_offset_;
767 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
768 // to 0-offset and we need to adjust it by code_offset.
769 uint32_t code_offset = quick_code_offset - thumb_offset;
770 if (mapping_table_offset != 0u) {
771 mapping_table_offset += code_offset;
772 DCHECK_LT(mapping_table_offset, code_offset);
773 }
774 if (vmap_table_offset != 0u) {
775 vmap_table_offset += code_offset;
776 DCHECK_LT(vmap_table_offset, code_offset);
777 }
778 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
779 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
780 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
781 *method_header = OatQuickMethodHeader(mapping_table_offset, vmap_table_offset,
782 frame_size_in_bytes, core_spill_mask, fp_spill_mask,
783 code_size);
784
Vladimir Markobd72fc12014-07-09 16:06:40 +0100785 if (!deduped) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100786 // Update offsets. (Checksum is updated when writing.)
Vladimir Marko8a630572014-04-09 18:45:35 +0100787 offset_ += sizeof(*method_header); // Method header is prepended before code.
Vladimir Marko8a630572014-04-09 18:45:35 +0100788 offset_ += code_size;
Vladimir Markof4da6752014-08-01 19:04:18 +0100789 // Record absolute patch locations.
790 if (!compiled_method->GetPatches().empty()) {
791 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
792 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
793 if (patch.Type() != kLinkerPatchCallRelative) {
794 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
795 }
796 }
797 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100798 }
Alex Light78382fa2014-06-06 15:45:32 -0700799
Andreas Gampe79273802014-08-05 20:21:05 -0700800 if (writer_->compiler_driver_->GetCompilerOptions().GetIncludeDebugSymbols()) {
801 // Record debug information for this function if we are doing that.
Alex Light78382fa2014-06-06 15:45:32 -0700802
Alex Light78382fa2014-06-06 15:45:32 -0700803 std::string name = PrettyMethod(it.GetMemberIndex(), *dex_file_, true);
804 if (deduped) {
Andreas Gampe79273802014-08-05 20:21:05 -0700805 // TODO We should place the DEDUPED tag on the first instance of a deduplicated symbol
806 // so that it will show up in a debuggerd crash report.
Alex Light78382fa2014-06-06 15:45:32 -0700807 name += " [ DEDUPED ]";
808 }
Andreas Gampe79273802014-08-05 20:21:05 -0700809
810 const uint32_t quick_code_start = quick_code_offset -
811 writer_->oat_header_->GetExecutableOffset();
Yevgeny Roubane3ea8382014-08-08 16:29:38 +0700812 const DexFile::CodeItem *code_item = it.GetMethodCodeItem();
Andreas Gampe79273802014-08-05 20:21:05 -0700813 writer_->method_info_.push_back(DebugInfo(name,
Yevgeny Roubane3ea8382014-08-08 16:29:38 +0700814 dex_file_->GetSourceFile(dex_file_->GetClassDef(class_def_index_)),
815 quick_code_start, quick_code_start + code_size,
816 code_item == nullptr ? nullptr : dex_file_->GetDebugInfoStream(code_item),
817 compiled_method));
Alex Light78382fa2014-06-06 15:45:32 -0700818 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100819 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100820
821 if (kIsDebugBuild) {
822 // We expect GC maps except when the class hasn't been verified or the method is native.
823 const CompilerDriver* compiler_driver = writer_->compiler_driver_;
824 ClassReference class_ref(dex_file_, class_def_index_);
825 CompiledClass* compiled_class = compiler_driver->GetCompiledClass(class_ref);
826 mirror::Class::Status status;
827 if (compiled_class != NULL) {
828 status = compiled_class->GetStatus();
829 } else if (compiler_driver->GetVerificationResults()->IsClassRejected(class_ref)) {
830 status = mirror::Class::kStatusError;
831 } else {
832 status = mirror::Class::kStatusNotReady;
833 }
Nicolas Geoffray39468442014-09-02 15:17:15 +0100834 std::vector<uint8_t> const * gc_map = compiled_method->GetGcMap();
835 if (gc_map != nullptr) {
836 size_t gc_map_size = gc_map->size() * sizeof(gc_map[0]);
Andreas Gampe51829322014-08-25 15:05:04 -0700837 bool is_native = it.MemberIsNative();
Nicolas Geoffray39468442014-09-02 15:17:15 +0100838 CHECK(gc_map_size != 0 || is_native || status < mirror::Class::kStatusVerified)
839 << gc_map << " " << gc_map_size << " " << (is_native ? "true" : "false") << " "
840 << (status < mirror::Class::kStatusVerified) << " " << status << " "
841 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
842 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100843 }
844
845 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
846 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
847 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100848 ++method_offsets_index_;
849 }
850
851 return true;
852 }
853
854 private:
855 // Deduplication is already done on a pointer basis by the compiler driver,
856 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +0100857 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100858};
859
860template <typename DataAccess>
861class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
862 public:
863 InitMapMethodVisitor(OatWriter* writer, size_t offset)
864 : OatDexMethodVisitor(writer, offset) {
865 }
866
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700867 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100868 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
869 OatClass* oat_class = writer_->oat_classes_[oat_class_index_];
870 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
871
872 if (compiled_method != nullptr) {
873 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
874 DCHECK_EQ(DataAccess::GetOffset(oat_class, method_offsets_index_), 0u);
875
876 const std::vector<uint8_t>* map = DataAccess::GetData(compiled_method);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100877 uint32_t map_size = map == nullptr ? 0 : map->size() * sizeof((*map)[0]);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100878 if (map_size != 0u) {
Vladimir Markobd72fc12014-07-09 16:06:40 +0100879 auto lb = dedupe_map_.lower_bound(map);
880 if (lb != dedupe_map_.end() && !dedupe_map_.key_comp()(map, lb->first)) {
881 DataAccess::SetOffset(oat_class, method_offsets_index_, lb->second);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100882 } else {
883 DataAccess::SetOffset(oat_class, method_offsets_index_, offset_);
Vladimir Markobd72fc12014-07-09 16:06:40 +0100884 dedupe_map_.PutBefore(lb, map, offset_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100885 offset_ += map_size;
886 writer_->oat_header_->UpdateChecksum(&(*map)[0], map_size);
887 }
888 }
889 ++method_offsets_index_;
890 }
891
892 return true;
893 }
894
895 private:
896 // Deduplication is already done on a pointer basis by the compiler driver,
897 // so we can simply compare the pointers to find out if things are duplicated.
898 SafeMap<const std::vector<uint8_t>*, uint32_t> dedupe_map_;
899};
900
901class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
902 public:
903 InitImageMethodVisitor(OatWriter* writer, size_t offset)
904 : OatDexMethodVisitor(writer, offset) {
905 }
906
907 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
908 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
909 OatClass* oat_class = writer_->oat_classes_[oat_class_index_];
910 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
911
Vladimir Marko7624d252014-05-02 14:40:15 +0100912 OatMethodOffsets offsets(0u, 0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100913 if (compiled_method != nullptr) {
914 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
915 offsets = oat_class->method_offsets_[method_offsets_index_];
916 ++method_offsets_index_;
917 }
918
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100919 ClassLinker* linker = Runtime::Current()->GetClassLinker();
920 InvokeType invoke_type = it.GetMethodInvokeType(dex_file_->GetClassDef(class_def_index_));
921 // Unchecked as we hold mutator_lock_ on entry.
922 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700923 StackHandleScope<2> hs(soa.Self());
924 Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(*dex_file_)));
Vladimir Marko7624d252014-05-02 14:40:15 +0100925 mirror::ArtMethod* method = linker->ResolveMethod(*dex_file_, it.GetMemberIndex(), dex_cache,
Mathieu Chartier0cd81352014-05-22 16:48:55 -0700926 NullHandle<mirror::ClassLoader>(),
927 NullHandle<mirror::ArtMethod>(),
928 invoke_type);
Andreas Gamped9efea62014-07-21 22:56:08 -0700929 if (method == nullptr) {
930 LOG(ERROR) << "Unexpected failure to resolve a method: "
931 << PrettyMethod(it.GetMemberIndex(), *dex_file_, true);
932 soa.Self()->AssertPendingException();
933 mirror::Throwable* exc = soa.Self()->GetException(nullptr);
934 std::string dump = exc->Dump();
935 LOG(FATAL) << dump;
936 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100937 // Portable code offsets are set by ElfWriterMclinker::FixupCompiledCodeOffset after linking.
938 method->SetQuickOatCodeOffset(offsets.code_offset_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100939 method->SetOatNativeGcMapOffset(offsets.gc_map_offset_);
940
941 return true;
942 }
943};
944
945class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
946 public:
947 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +0100948 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100949 : OatDexMethodVisitor(writer, relative_offset),
950 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +0100951 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100952 soa_(Thread::Current()),
953 no_thread_suspension_(soa_.Self(), "OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +0100954 class_linker_(Runtime::Current()->GetClassLinker()),
955 dex_cache_(nullptr) {
956 if (writer_->image_writer_ != nullptr) {
957 // If we're creating the image, the address space must be ready so that we can apply patches.
958 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
959 patched_code_.reserve(16 * KB);
960 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100961 }
962
Vladimir Markof4da6752014-08-01 19:04:18 +0100963 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100964 }
965
966 bool StartClass(const DexFile* dex_file, size_t class_def_index)
967 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
968 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
969 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
970 dex_cache_ = class_linker_->FindDexCache(*dex_file);
971 }
972 return true;
973 }
974
975 bool EndClass() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
976 bool result = OatDexMethodVisitor::EndClass();
977 if (oat_class_index_ == writer_->oat_classes_.size()) {
978 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
979 offset_ = writer_->relative_call_patcher_->WriteThunks(out_, offset_);
980 if (UNLIKELY(offset_ == 0u)) {
981 PLOG(ERROR) << "Failed to write final relative call thunks";
982 result = false;
983 }
984 }
985 return result;
986 }
987
988 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
989 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100990 OatClass* oat_class = writer_->oat_classes_[oat_class_index_];
991 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
992
993 if (compiled_method != NULL) { // ie. not an abstract method
994 size_t file_offset = file_offset_;
995 OutputStream* out = out_;
996
997 const std::vector<uint8_t>* quick_code = compiled_method->GetQuickCode();
998 if (quick_code != nullptr) {
999 CHECK(compiled_method->GetPortableCode() == nullptr);
Vladimir Markof4da6752014-08-01 19:04:18 +01001000 offset_ = writer_->relative_call_patcher_->WriteThunks(out, offset_);
1001 if (offset_ == 0u) {
1002 ReportWriteFailure("relative call thunk", it);
1003 return false;
1004 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001005 uint32_t aligned_offset = compiled_method->AlignCode(offset_);
1006 uint32_t aligned_code_delta = aligned_offset - offset_;
1007 if (aligned_code_delta != 0) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001008 if (!writer_->WriteCodeAlignment(out, aligned_code_delta)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001009 ReportWriteFailure("code alignment padding", it);
1010 return false;
1011 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001012 offset_ += aligned_code_delta;
1013 DCHECK_OFFSET_();
1014 }
1015 DCHECK_ALIGNED_PARAM(offset_,
1016 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1017 uint32_t code_size = quick_code->size() * sizeof(uint8_t);
1018 CHECK_NE(code_size, 0U);
1019
1020 // Deduplicate code arrays.
1021 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
1022 DCHECK(method_offsets.code_offset_ < offset_ || method_offsets.code_offset_ ==
Vladimir Marko7624d252014-05-02 14:40:15 +01001023 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001024 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1025 if (method_offsets.code_offset_ >= offset_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001026 const OatQuickMethodHeader& method_header =
1027 oat_class->method_headers_[method_offsets_index_];
1028 writer_->oat_header_->UpdateChecksum(&method_header, sizeof(method_header));
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001029 if (!out->WriteFully(&method_header, sizeof(method_header))) {
1030 ReportWriteFailure("method header", it);
1031 return false;
1032 }
1033 writer_->size_method_header_ += sizeof(method_header);
1034 offset_ += sizeof(method_header);
1035 DCHECK_OFFSET_();
Vladimir Markof4da6752014-08-01 19:04:18 +01001036
1037 if (!compiled_method->GetPatches().empty()) {
1038 patched_code_ = *quick_code;
1039 quick_code = &patched_code_;
1040 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
1041 if (patch.Type() == kLinkerPatchCallRelative) {
1042 // NOTE: Relative calls across oat files are not supported.
1043 uint32_t target_offset = GetTargetOffset(patch);
1044 uint32_t literal_offset = patch.LiteralOffset();
1045 writer_->relative_call_patcher_->Patch(&patched_code_, literal_offset,
1046 offset_ + literal_offset, target_offset);
1047 } else if (patch.Type() == kLinkerPatchCall) {
1048 uint32_t target_offset = GetTargetOffset(patch);
1049 PatchCodeAddress(&patched_code_, patch.LiteralOffset(), target_offset);
1050 } else if (patch.Type() == kLinkerPatchMethod) {
1051 mirror::ArtMethod* method = GetTargetMethod(patch);
1052 PatchObjectAddress(&patched_code_, patch.LiteralOffset(), method);
1053 } else if (patch.Type() == kLinkerPatchType) {
1054 mirror::Class* type = GetTargetType(patch);
1055 PatchObjectAddress(&patched_code_, patch.LiteralOffset(), type);
1056 }
1057 }
1058 }
1059
1060 writer_->oat_header_->UpdateChecksum(&(*quick_code)[0], code_size);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001061 if (!out->WriteFully(&(*quick_code)[0], code_size)) {
1062 ReportWriteFailure("method code", it);
1063 return false;
1064 }
1065 writer_->size_code_ += code_size;
1066 offset_ += code_size;
1067 }
1068 DCHECK_OFFSET_();
1069 }
1070 ++method_offsets_index_;
1071 }
1072
1073 return true;
1074 }
1075
1076 private:
1077 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001078 const size_t file_offset_;
1079 const ScopedObjectAccess soa_;
1080 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001081 ClassLinker* const class_linker_;
1082 mirror::DexCache* dex_cache_;
1083 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001084
1085 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1086 PLOG(ERROR) << "Failed to write " << what << " for "
1087 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1088 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001089
1090 mirror::ArtMethod* GetTargetMethod(const LinkerPatch& patch)
1091 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1092 MethodReference ref = patch.TargetMethod();
1093 mirror::DexCache* dex_cache =
1094 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(*ref.dex_file);
1095 mirror::ArtMethod* method = dex_cache->GetResolvedMethod(ref.dex_method_index);
1096 CHECK(method != nullptr);
1097 return method;
1098 }
1099
1100 uint32_t GetTargetOffset(const LinkerPatch& patch) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1101 auto target_it = writer_->method_offset_map_.find(patch.TargetMethod());
1102 uint32_t target_offset =
1103 (target_it != writer_->method_offset_map_.end()) ? target_it->second : 0u;
1104 // If there's no compiled code, point to the correct trampoline.
1105 if (UNLIKELY(target_offset == 0)) {
1106 mirror::ArtMethod* target = GetTargetMethod(patch);
1107 DCHECK(target != nullptr);
1108 DCHECK_EQ(target->GetQuickOatCodeOffset(), 0u);
1109 target_offset = target->IsNative()
1110 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1111 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1112 }
1113 return target_offset;
1114 }
1115
1116 mirror::Class* GetTargetType(const LinkerPatch& patch)
1117 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1118 mirror::DexCache* dex_cache = (dex_file_ == patch.TargetTypeDexFile())
1119 ? dex_cache_ : class_linker_->FindDexCache(*patch.TargetTypeDexFile());
1120 mirror::Class* type = dex_cache->GetResolvedType(patch.TargetTypeIndex());
1121 CHECK(type != nullptr);
1122 return type;
1123 }
1124
1125 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
1126 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1127 // NOTE: Direct method pointers across oat files don't use linker patches. However, direct
1128 // type pointers across oat files do. (TODO: Investigate why.)
1129 if (writer_->image_writer_ != nullptr) {
1130 object = writer_->image_writer_->GetImageAddress(object);
1131 }
1132 uint32_t address = PointerToLowMemUInt32(object);
1133 DCHECK_LE(offset + 4, code->size());
1134 uint8_t* data = &(*code)[offset];
1135 data[0] = address & 0xffu;
1136 data[1] = (address >> 8) & 0xffu;
1137 data[2] = (address >> 16) & 0xffu;
1138 data[3] = (address >> 24) & 0xffu;
1139 }
1140
1141 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
1142 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1143 // NOTE: Direct calls across oat files don't use linker patches.
1144 DCHECK(writer_->image_writer_ != nullptr);
1145 uint32_t address = PointerToLowMemUInt32(writer_->image_writer_->GetOatFileBegin() +
1146 writer_->oat_data_offset_ + target_offset);
1147 DCHECK_LE(offset + 4, code->size());
1148 uint8_t* data = &(*code)[offset];
1149 data[0] = address & 0xffu;
1150 data[1] = (address >> 8) & 0xffu;
1151 data[2] = (address >> 16) & 0xffu;
1152 data[3] = (address >> 24) & 0xffu;
1153 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001154};
1155
1156template <typename DataAccess>
1157class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1158 public:
1159 WriteMapMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
1160 size_t relative_offset)
1161 : OatDexMethodVisitor(writer, relative_offset),
1162 out_(out),
1163 file_offset_(file_offset) {
1164 }
1165
1166 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
1167 OatClass* oat_class = writer_->oat_classes_[oat_class_index_];
1168 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1169
1170 if (compiled_method != NULL) { // ie. not an abstract method
1171 size_t file_offset = file_offset_;
1172 OutputStream* out = out_;
1173
1174 uint32_t map_offset = DataAccess::GetOffset(oat_class, method_offsets_index_);
1175 ++method_offsets_index_;
1176
1177 // Write deduplicated map.
1178 const std::vector<uint8_t>* map = DataAccess::GetData(compiled_method);
Nicolas Geoffray39468442014-09-02 15:17:15 +01001179 size_t map_size = map == nullptr ? 0 : map->size() * sizeof((*map)[0]);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001180 DCHECK((map_size == 0u && map_offset == 0u) ||
1181 (map_size != 0u && map_offset != 0u && map_offset <= offset_))
1182 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1183 if (map_size != 0u && map_offset == offset_) {
1184 if (UNLIKELY(!out->WriteFully(&(*map)[0], map_size))) {
1185 ReportWriteFailure(it);
1186 return false;
1187 }
1188 offset_ += map_size;
1189 }
1190 DCHECK_OFFSET_();
1191 }
1192
1193 return true;
1194 }
1195
1196 private:
1197 OutputStream* const out_;
1198 size_t const file_offset_;
1199
1200 void ReportWriteFailure(const ClassDataItemIterator& it) {
1201 PLOG(ERROR) << "Failed to write " << DataAccess::Name() << " for "
1202 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1203 }
1204};
1205
1206// Visit all methods from all classes in all dex files with the specified visitor.
1207bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1208 for (const DexFile* dex_file : *dex_files_) {
1209 const size_t class_def_count = dex_file->NumClassDefs();
1210 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1211 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1212 return false;
1213 }
1214 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -07001215 const uint8_t* class_data = dex_file->GetClassData(class_def);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001216 if (class_data != NULL) { // ie not an empty class, such as a marker interface
1217 ClassDataItemIterator it(*dex_file, class_data);
1218 while (it.HasNextStaticField()) {
1219 it.Next();
1220 }
1221 while (it.HasNextInstanceField()) {
1222 it.Next();
1223 }
1224 size_t class_def_method_index = 0u;
1225 while (it.HasNextDirectMethod()) {
1226 if (!visitor->VisitMethod(class_def_method_index, it)) {
1227 return false;
1228 }
1229 ++class_def_method_index;
1230 it.Next();
1231 }
1232 while (it.HasNextVirtualMethod()) {
1233 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1234 return false;
1235 }
1236 ++class_def_method_index;
1237 it.Next();
1238 }
1239 }
1240 if (UNLIKELY(!visitor->EndClass())) {
1241 return false;
1242 }
1243 }
1244 }
1245 return true;
1246}
1247
Brian Carlstrom81f3ca12012-03-17 00:27:35 -07001248size_t OatWriter::InitOatHeader() {
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001249 oat_header_ = OatHeader::Create(compiler_driver_->GetInstructionSet(),
1250 compiler_driver_->GetInstructionSetFeatures(),
1251 dex_files_,
1252 image_file_location_oat_checksum_,
1253 image_file_location_oat_begin_,
1254 key_value_store_);
1255
1256 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001257}
1258
1259size_t OatWriter::InitOatDexFiles(size_t offset) {
1260 // create the OatDexFiles
1261 for (size_t i = 0; i != dex_files_->size(); ++i) {
1262 const DexFile* dex_file = (*dex_files_)[i];
1263 CHECK(dex_file != NULL);
Brian Carlstrom265091e2013-01-30 14:08:26 -08001264 OatDexFile* oat_dex_file = new OatDexFile(offset, *dex_file);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001265 oat_dex_files_.push_back(oat_dex_file);
1266 offset += oat_dex_file->SizeOf();
1267 }
1268 return offset;
1269}
1270
Brian Carlstrom89521892011-12-07 22:05:07 -08001271size_t OatWriter::InitDexFiles(size_t offset) {
1272 // calculate the offsets within OatDexFiles to the DexFiles
1273 for (size_t i = 0; i != dex_files_->size(); ++i) {
1274 // dex files are required to be 4 byte aligned
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001275 size_t original_offset = offset;
Brian Carlstrom89521892011-12-07 22:05:07 -08001276 offset = RoundUp(offset, 4);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001277 size_dex_file_alignment_ += offset - original_offset;
Brian Carlstrom89521892011-12-07 22:05:07 -08001278
1279 // set offset in OatDexFile to DexFile
1280 oat_dex_files_[i]->dex_file_offset_ = offset;
1281
1282 const DexFile* dex_file = (*dex_files_)[i];
1283 offset += dex_file->GetHeader().file_size_;
1284 }
1285 return offset;
1286}
1287
Brian Carlstrom389efb02012-01-11 12:06:26 -08001288size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001289 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001290 InitOatClassesMethodVisitor visitor(this, offset);
1291 bool success = VisitDexMethods(&visitor);
1292 CHECK(success);
1293 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001294
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001295 // Update oat_dex_files_.
1296 auto oat_class_it = oat_classes_.begin();
1297 for (OatDexFile* oat_dex_file : oat_dex_files_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001298 for (uint32_t& method_offset : oat_dex_file->methods_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001299 DCHECK(oat_class_it != oat_classes_.end());
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001300 method_offset = (*oat_class_it)->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001301 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001302 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001303 oat_dex_file->UpdateChecksum(oat_header_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001304 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001305 CHECK(oat_class_it == oat_classes_.end());
1306
1307 return offset;
1308}
1309
1310size_t OatWriter::InitOatMaps(size_t offset) {
1311 #define VISIT(VisitorType) \
1312 do { \
1313 VisitorType visitor(this, offset); \
1314 bool success = VisitDexMethods(&visitor); \
1315 DCHECK(success); \
1316 offset = visitor.GetOffset(); \
1317 } while (false)
1318
1319 VISIT(InitMapMethodVisitor<GcMapDataAccess>);
1320 VISIT(InitMapMethodVisitor<MappingTableDataAccess>);
1321 VISIT(InitMapMethodVisitor<VmapTableDataAccess>);
1322
1323 #undef VISIT
1324
Brian Carlstrome24fa612011-09-29 00:53:55 -07001325 return offset;
1326}
1327
1328size_t OatWriter::InitOatCode(size_t offset) {
1329 // calculate the offsets within OatHeader to executable code
1330 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001331 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001332 // required to be on a new page boundary
1333 offset = RoundUp(offset, kPageSize);
1334 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001335 size_executable_offset_alignment_ = offset - old_offset;
1336 if (compiler_driver_->IsImage()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001337 CHECK_EQ(image_patch_delta_, 0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001338 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001339
Ian Rogers848871b2013-08-05 10:56:33 -07001340 #define DO_TRAMPOLINE(field, fn_name) \
1341 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001342 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1343 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Ian Rogers848871b2013-08-05 10:56:33 -07001344 field.reset(compiler_driver_->Create ## fn_name()); \
1345 offset += field->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001346
Ian Rogers848871b2013-08-05 10:56:33 -07001347 DO_TRAMPOLINE(interpreter_to_interpreter_bridge_, InterpreterToInterpreterBridge);
1348 DO_TRAMPOLINE(interpreter_to_compiled_code_bridge_, InterpreterToCompiledCodeBridge);
1349 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Jeff Hao88474b42013-10-23 16:24:40 -07001350 DO_TRAMPOLINE(portable_imt_conflict_trampoline_, PortableImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001351 DO_TRAMPOLINE(portable_resolution_trampoline_, PortableResolutionTrampoline);
1352 DO_TRAMPOLINE(portable_to_interpreter_bridge_, PortableToInterpreterBridge);
Andreas Gampe2da88232014-02-27 12:26:20 -08001353 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001354 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001355 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1356 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001357
Ian Rogers848871b2013-08-05 10:56:33 -07001358 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001359 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001360 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1361 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1362 oat_header_->SetJniDlsymLookupOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001363 oat_header_->SetPortableImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001364 oat_header_->SetPortableResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001365 oat_header_->SetPortableToInterpreterBridgeOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001366 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001367 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001368 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001369 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Alex Lighta59dd802014-07-02 16:28:08 -07001370 oat_header_->SetImagePatchDelta(image_patch_delta_);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001371 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001372 return offset;
1373}
1374
1375size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001376 #define VISIT(VisitorType) \
1377 do { \
1378 VisitorType visitor(this, offset); \
1379 bool success = VisitDexMethods(&visitor); \
1380 DCHECK(success); \
1381 offset = visitor.GetOffset(); \
1382 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001383
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001384 VISIT(InitCodeMethodVisitor);
Ian Rogers1212a022013-03-04 10:48:41 -08001385 if (compiler_driver_->IsImage()) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001386 VISIT(InitImageMethodVisitor);
Ian Rogers0571d352011-11-03 19:51:38 -07001387 }
Logan Chien8b977d32012-02-21 19:14:55 +08001388
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001389 #undef VISIT
1390
Brian Carlstrome24fa612011-09-29 00:53:55 -07001391 return offset;
1392}
1393
Ian Rogers3d504072014-03-01 09:16:49 -08001394bool OatWriter::Write(OutputStream* out) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001395 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
1396 if (raw_file_offset == (off_t) -1) {
1397 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
1398 return false;
1399 }
1400 const size_t file_offset = static_cast<size_t>(raw_file_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001401
Vladimir Markof4da6752014-08-01 19:04:18 +01001402 // Reserve space for header. It will be written last - after updating the checksum.
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001403 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Markof4da6752014-08-01 19:04:18 +01001404 if (out->Seek(header_size, kSeekCurrent) == (off_t) -1) {
1405 PLOG(ERROR) << "Failed to reserve space for oat header in " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001406 return false;
1407 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001408 size_oat_header_ += sizeof(OatHeader);
1409 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Brian Carlstrom81f3ca12012-03-17 00:27:35 -07001410
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001411 if (!WriteTables(out, file_offset)) {
Ian Rogers3d504072014-03-01 09:16:49 -08001412 LOG(ERROR) << "Failed to write oat tables to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001413 return false;
1414 }
1415
Vladimir Markof4da6752014-08-01 19:04:18 +01001416 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
1417 if (tables_end_offset == (off_t) -1) {
1418 LOG(ERROR) << "Failed to seek to oat code position in " << out->GetLocation();
1419 return false;
1420 }
1421 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001422 relative_offset = WriteMaps(out, file_offset, relative_offset);
1423 if (relative_offset == 0) {
1424 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1425 return false;
1426 }
1427
1428 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001429 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001430 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001431 return false;
1432 }
1433
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001434 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1435 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001436 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001437 return false;
1438 }
1439
Vladimir Markof4da6752014-08-01 19:04:18 +01001440 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
1441 if (oat_end_file_offset == (off_t) -1) {
1442 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1443 return false;
1444 }
1445
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001446 if (kIsDebugBuild) {
1447 uint32_t size_total = 0;
1448 #define DO_STAT(x) \
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001449 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << x << "B)"; \
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001450 size_total += x;
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001451
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001452 DO_STAT(size_dex_file_alignment_);
1453 DO_STAT(size_executable_offset_alignment_);
1454 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001455 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001456 DO_STAT(size_dex_file_);
Ian Rogers848871b2013-08-05 10:56:33 -07001457 DO_STAT(size_interpreter_to_interpreter_bridge_);
1458 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1459 DO_STAT(size_jni_dlsym_lookup_);
Jeff Hao88474b42013-10-23 16:24:40 -07001460 DO_STAT(size_portable_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001461 DO_STAT(size_portable_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001462 DO_STAT(size_portable_to_interpreter_bridge_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001463 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001464 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001465 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001466 DO_STAT(size_quick_to_interpreter_bridge_);
1467 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001468 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001469 DO_STAT(size_code_);
1470 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001471 DO_STAT(size_relative_call_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001472 DO_STAT(size_mapping_table_);
1473 DO_STAT(size_vmap_table_);
1474 DO_STAT(size_gc_map_);
1475 DO_STAT(size_oat_dex_file_location_size_);
1476 DO_STAT(size_oat_dex_file_location_data_);
1477 DO_STAT(size_oat_dex_file_location_checksum_);
1478 DO_STAT(size_oat_dex_file_offset_);
1479 DO_STAT(size_oat_dex_file_methods_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001480 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001481 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001482 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001483 DO_STAT(size_oat_class_method_offsets_);
1484 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001485
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001486 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)"; \
Vladimir Markof4da6752014-08-01 19:04:18 +01001487 CHECK_EQ(file_offset + size_total, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001488 CHECK_EQ(size_, size_total);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001489 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001490
Vladimir Markof4da6752014-08-01 19:04:18 +01001491 CHECK_EQ(file_offset + size_, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001492 CHECK_EQ(size_, relative_offset);
1493
Vladimir Markof4da6752014-08-01 19:04:18 +01001494 // Write the header now that the checksum is final.
1495 if (out->Seek(file_offset, kSeekSet) == (off_t) -1) {
1496 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1497 return false;
1498 }
1499 DCHECK_EQ(raw_file_offset, out->Seek(0, kSeekCurrent));
1500 if (!out->WriteFully(oat_header_, header_size)) {
1501 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1502 return false;
1503 }
1504 if (out->Seek(oat_end_file_offset, kSeekSet) == (off_t) -1) {
1505 PLOG(ERROR) << "Failed to seek to end after writing oat header to " << out->GetLocation();
1506 return false;
1507 }
1508 DCHECK_EQ(oat_end_file_offset, out->Seek(0, kSeekCurrent));
1509
Brian Carlstrome24fa612011-09-29 00:53:55 -07001510 return true;
1511}
1512
Ian Rogers3d504072014-03-01 09:16:49 -08001513bool OatWriter::WriteTables(OutputStream* out, const size_t file_offset) {
Brian Carlstrome24fa612011-09-29 00:53:55 -07001514 for (size_t i = 0; i != oat_dex_files_.size(); ++i) {
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001515 if (!oat_dex_files_[i]->Write(this, out, file_offset)) {
Ian Rogers3d504072014-03-01 09:16:49 -08001516 PLOG(ERROR) << "Failed to write oat dex information to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001517 return false;
1518 }
1519 }
Brian Carlstrom89521892011-12-07 22:05:07 -08001520 for (size_t i = 0; i != oat_dex_files_.size(); ++i) {
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001521 uint32_t expected_offset = file_offset + oat_dex_files_[i]->dex_file_offset_;
Ian Rogers3d504072014-03-01 09:16:49 -08001522 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
Brian Carlstrom89521892011-12-07 22:05:07 -08001523 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
1524 const DexFile* dex_file = (*dex_files_)[i];
1525 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
1526 << " Expected: " << expected_offset << " File: " << dex_file->GetLocation();
1527 return false;
1528 }
1529 const DexFile* dex_file = (*dex_files_)[i];
Ian Rogers3d504072014-03-01 09:16:49 -08001530 if (!out->WriteFully(&dex_file->GetHeader(), dex_file->GetHeader().file_size_)) {
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001531 PLOG(ERROR) << "Failed to write dex file " << dex_file->GetLocation()
Ian Rogers3d504072014-03-01 09:16:49 -08001532 << " to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08001533 return false;
1534 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001535 size_dex_file_ += dex_file->GetHeader().file_size_;
Brian Carlstrom89521892011-12-07 22:05:07 -08001536 }
Brian Carlstrom389efb02012-01-11 12:06:26 -08001537 for (size_t i = 0; i != oat_classes_.size(); ++i) {
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001538 if (!oat_classes_[i]->Write(this, out, file_offset)) {
Ian Rogers3d504072014-03-01 09:16:49 -08001539 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001540 return false;
1541 }
1542 }
1543 return true;
1544}
1545
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001546size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
1547 #define VISIT(VisitorType) \
1548 do { \
1549 VisitorType visitor(this, out, file_offset, relative_offset); \
1550 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1551 return 0; \
1552 } \
1553 relative_offset = visitor.GetOffset(); \
1554 } while (false)
1555
1556 size_t gc_maps_offset = relative_offset;
1557 VISIT(WriteMapMethodVisitor<GcMapDataAccess>);
1558 size_gc_map_ = relative_offset - gc_maps_offset;
1559
1560 size_t mapping_tables_offset = relative_offset;
1561 VISIT(WriteMapMethodVisitor<MappingTableDataAccess>);
1562 size_mapping_table_ = relative_offset - mapping_tables_offset;
1563
1564 size_t vmap_tables_offset = relative_offset;
1565 VISIT(WriteMapMethodVisitor<VmapTableDataAccess>);
1566 size_vmap_table_ = relative_offset - vmap_tables_offset;
1567
1568 #undef VISIT
1569
1570 return relative_offset;
1571}
1572
1573size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Ian Rogers3d504072014-03-01 09:16:49 -08001574 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001575 relative_offset += size_executable_offset_alignment_;
1576 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001577 size_t expected_file_offset = file_offset + relative_offset;
1578 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001579 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
Ian Rogers3d504072014-03-01 09:16:49 -08001580 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001581 return 0;
1582 }
Brian Carlstrom265091e2013-01-30 14:08:26 -08001583 DCHECK_OFFSET();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001584 if (compiler_driver_->IsImage()) {
1585 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001586
Ian Rogers848871b2013-08-05 10:56:33 -07001587 #define DO_TRAMPOLINE(field) \
1588 do { \
1589 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
1590 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08001591 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07001592 size_trampoline_alignment_ += alignment_padding; \
Ian Rogers3d504072014-03-01 09:16:49 -08001593 if (!out->WriteFully(&(*field)[0], field->size())) { \
1594 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001595 return false; \
1596 } \
1597 size_ ## field += field->size(); \
1598 relative_offset += alignment_padding + field->size(); \
1599 DCHECK_OFFSET(); \
1600 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001601
Ian Rogers848871b2013-08-05 10:56:33 -07001602 DO_TRAMPOLINE(interpreter_to_interpreter_bridge_);
1603 DO_TRAMPOLINE(interpreter_to_compiled_code_bridge_);
1604 DO_TRAMPOLINE(jni_dlsym_lookup_);
Jeff Hao88474b42013-10-23 16:24:40 -07001605 DO_TRAMPOLINE(portable_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001606 DO_TRAMPOLINE(portable_resolution_trampoline_);
1607 DO_TRAMPOLINE(portable_to_interpreter_bridge_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001608 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001609 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001610 DO_TRAMPOLINE(quick_resolution_trampoline_);
1611 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
1612 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001613 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001614 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001615}
1616
Ian Rogers3d504072014-03-01 09:16:49 -08001617size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001618 const size_t file_offset,
1619 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001620 #define VISIT(VisitorType) \
1621 do { \
1622 VisitorType visitor(this, out, file_offset, relative_offset); \
1623 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1624 return 0; \
1625 } \
1626 relative_offset = visitor.GetOffset(); \
1627 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001628
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001629 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001630
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001631 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08001632
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001633 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001634}
1635
Vladimir Markof4da6752014-08-01 19:04:18 +01001636bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
1637 static const uint8_t kPadding[] = {
1638 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
1639 };
1640 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
1641 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
1642 return false;
1643 }
1644 size_code_alignment_ += aligned_code_delta;
1645 return true;
1646}
1647
Brian Carlstrom265091e2013-01-30 14:08:26 -08001648OatWriter::OatDexFile::OatDexFile(size_t offset, const DexFile& dex_file) {
1649 offset_ = offset;
Elliott Hughes95572412011-12-13 18:14:20 -08001650 const std::string& location(dex_file.GetLocation());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001651 dex_file_location_size_ = location.size();
1652 dex_file_location_data_ = reinterpret_cast<const uint8_t*>(location.data());
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001653 dex_file_location_checksum_ = dex_file.GetLocationChecksum();
Brian Carlstrom89521892011-12-07 22:05:07 -08001654 dex_file_offset_ = 0;
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -08001655 methods_offsets_.resize(dex_file.NumClassDefs());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001656}
1657
1658size_t OatWriter::OatDexFile::SizeOf() const {
1659 return sizeof(dex_file_location_size_)
1660 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001661 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08001662 + sizeof(dex_file_offset_)
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -08001663 + (sizeof(methods_offsets_[0]) * methods_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001664}
1665
Ian Rogers3d504072014-03-01 09:16:49 -08001666void OatWriter::OatDexFile::UpdateChecksum(OatHeader* oat_header) const {
1667 oat_header->UpdateChecksum(&dex_file_location_size_, sizeof(dex_file_location_size_));
1668 oat_header->UpdateChecksum(dex_file_location_data_, dex_file_location_size_);
1669 oat_header->UpdateChecksum(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_));
1670 oat_header->UpdateChecksum(&dex_file_offset_, sizeof(dex_file_offset_));
1671 oat_header->UpdateChecksum(&methods_offsets_[0],
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -08001672 sizeof(methods_offsets_[0]) * methods_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001673}
1674
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001675bool OatWriter::OatDexFile::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08001676 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001677 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08001678 DCHECK_OFFSET_();
Ian Rogers3d504072014-03-01 09:16:49 -08001679 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
1680 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001681 return false;
1682 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001683 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Ian Rogers3d504072014-03-01 09:16:49 -08001684 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
1685 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001686 return false;
1687 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001688 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Ian Rogers3d504072014-03-01 09:16:49 -08001689 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
1690 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001691 return false;
1692 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001693 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Ian Rogers3d504072014-03-01 09:16:49 -08001694 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
1695 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08001696 return false;
1697 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001698 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Ian Rogers3d504072014-03-01 09:16:49 -08001699 if (!out->WriteFully(&methods_offsets_[0],
Brian Carlstromcd60ac72013-01-20 17:09:51 -08001700 sizeof(methods_offsets_[0]) * methods_offsets_.size())) {
Ian Rogers3d504072014-03-01 09:16:49 -08001701 PLOG(ERROR) << "Failed to write methods offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001702 return false;
1703 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001704 oat_writer->size_oat_dex_file_methods_offsets_ +=
1705 sizeof(methods_offsets_[0]) * methods_offsets_.size();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001706 return true;
1707}
1708
Brian Carlstromba150c32013-08-27 17:31:03 -07001709OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001710 const std::vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07001711 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001712 mirror::Class::Status status)
1713 : compiled_methods_(compiled_methods) {
1714 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07001715 CHECK_LE(num_non_null_compiled_methods, num_methods);
1716
Brian Carlstrom265091e2013-01-30 14:08:26 -08001717 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07001718 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
1719
1720 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
1721 // apply when there are 0 methods, we just arbitrarily say that 0
1722 // methods means kOatClassNoneCompiled and that we won't use
1723 // kOatClassAllCompiled unless there is at least one compiled
1724 // method. This means in an interpretter only system, we can assert
1725 // that all classes are kOatClassNoneCompiled.
1726 if (num_non_null_compiled_methods == 0) {
1727 type_ = kOatClassNoneCompiled;
1728 } else if (num_non_null_compiled_methods == num_methods) {
1729 type_ = kOatClassAllCompiled;
1730 } else {
1731 type_ = kOatClassSomeCompiled;
1732 }
1733
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001734 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07001735 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01001736 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07001737
1738 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
1739 if (type_ == kOatClassSomeCompiled) {
1740 method_bitmap_ = new BitVector(num_methods, false, Allocator::GetMallocAllocator());
1741 method_bitmap_size_ = method_bitmap_->GetSizeOf();
1742 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
1743 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
1744 } else {
1745 method_bitmap_ = NULL;
1746 method_bitmap_size_ = 0;
1747 }
1748
1749 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001750 CompiledMethod* compiled_method = compiled_methods_[i];
Brian Carlstromba150c32013-08-27 17:31:03 -07001751 if (compiled_method == NULL) {
1752 oat_method_offsets_offsets_from_oat_class_[i] = 0;
1753 } else {
1754 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
1755 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
1756 if (type_ == kOatClassSomeCompiled) {
1757 method_bitmap_->SetBit(i);
1758 }
1759 }
1760 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001761}
1762
Brian Carlstromba150c32013-08-27 17:31:03 -07001763OatWriter::OatClass::~OatClass() {
Mathieu Chartier661974a2014-01-09 11:23:53 -08001764 delete method_bitmap_;
Brian Carlstromba150c32013-08-27 17:31:03 -07001765}
1766
Brian Carlstrom265091e2013-01-30 14:08:26 -08001767size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
1768 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07001769 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
1770 if (method_offset == 0) {
1771 return 0;
1772 }
1773 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08001774}
1775
1776size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
1777 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07001778 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08001779}
1780
1781size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07001782 return sizeof(status_)
1783 + sizeof(type_)
1784 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
1785 + method_bitmap_size_
1786 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001787}
1788
Ian Rogers3d504072014-03-01 09:16:49 -08001789void OatWriter::OatClass::UpdateChecksum(OatHeader* oat_header) const {
1790 oat_header->UpdateChecksum(&status_, sizeof(status_));
1791 oat_header->UpdateChecksum(&type_, sizeof(type_));
Brian Carlstromba150c32013-08-27 17:31:03 -07001792 if (method_bitmap_size_ != 0) {
1793 CHECK_EQ(kOatClassSomeCompiled, type_);
Ian Rogers3d504072014-03-01 09:16:49 -08001794 oat_header->UpdateChecksum(&method_bitmap_size_, sizeof(method_bitmap_size_));
1795 oat_header->UpdateChecksum(method_bitmap_->GetRawStorage(), method_bitmap_size_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001796 }
Ian Rogers3d504072014-03-01 09:16:49 -08001797 oat_header->UpdateChecksum(&method_offsets_[0],
1798 sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001799}
1800
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001801bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08001802 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001803 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08001804 DCHECK_OFFSET_();
Ian Rogers3d504072014-03-01 09:16:49 -08001805 if (!out->WriteFully(&status_, sizeof(status_))) {
1806 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001807 return false;
1808 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001809 oat_writer->size_oat_class_status_ += sizeof(status_);
Ian Rogers3d504072014-03-01 09:16:49 -08001810 if (!out->WriteFully(&type_, sizeof(type_))) {
1811 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07001812 return false;
1813 }
1814 oat_writer->size_oat_class_type_ += sizeof(type_);
1815 if (method_bitmap_size_ != 0) {
1816 CHECK_EQ(kOatClassSomeCompiled, type_);
Ian Rogers3d504072014-03-01 09:16:49 -08001817 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
1818 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07001819 return false;
1820 }
1821 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Ian Rogers3d504072014-03-01 09:16:49 -08001822 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
1823 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07001824 return false;
1825 }
1826 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
1827 }
Ian Rogers3d504072014-03-01 09:16:49 -08001828 if (!out->WriteFully(&method_offsets_[0],
Brian Carlstromcd60ac72013-01-20 17:09:51 -08001829 sizeof(method_offsets_[0]) * method_offsets_.size())) {
Ian Rogers3d504072014-03-01 09:16:49 -08001830 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001831 return false;
1832 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001833 oat_writer->size_oat_class_method_offsets_ += sizeof(method_offsets_[0]) * method_offsets_.size();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001834 return true;
1835}
1836
Brian Carlstrome24fa612011-09-29 00:53:55 -07001837} // namespace art