blob: 04f0db657294fe9d26ccf3d4bdfe8559e9b6963a [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
Vladimir Markoc74658b2015-03-31 10:26:41 +010021#include "arch/arm64/instruction_set_features_arm64.h"
Ian Rogerse77493c2014-08-20 15:08:45 -070022#include "base/allocator.h"
Brian Carlstromba150c32013-08-27 17:31:03 -070023#include "base/bit_vector.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080024#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080025#include "base/unix_file/fd_file.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070026#include "class_linker.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070027#include "compiled_class.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000028#include "compiled_method.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070029#include "dex_file-inl.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000030#include "dex/verification_results.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000031#include "driver/compiler_driver.h"
32#include "driver/compiler_options.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070033#include "gc/space/space.h"
Vladimir Markof4da6752014-08-01 19:04:18 +010034#include "image_writer.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070035#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080036#include "mirror/array.h"
37#include "mirror/class_loader.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070038#include "mirror/object-inl.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070039#include "os.h"
Brian Carlstromcd60ac72013-01-20 17:09:51 -080040#include "output_stream.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070041#include "safe_map.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070042#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070043#include "handle_scope-inl.h"
Vladimir Markof4da6752014-08-01 19:04:18 +010044#include "utils/arm/assembler_thumb2.h"
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +010045#include "utils/arm64/assembler_arm64.h"
jeffhaoec014232012-09-05 10:42:25 -070046#include "verifier/method_verifier.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070047
48namespace art {
49
Vladimir Marko20f85592015-03-19 10:07:02 +000050class OatWriter::RelativePatcher {
Vladimir Markof4da6752014-08-01 19:04:18 +010051 public:
Vladimir Marko20f85592015-03-19 10:07:02 +000052 virtual ~RelativePatcher() { }
Vladimir Markof4da6752014-08-01 19:04:18 +010053
Vladimir Markoc74658b2015-03-31 10:26:41 +010054 // Reserve space for relative call thunks if needed, return adjusted offset. After all methods
55 // of a class have been processed it's called one last time with compiled_method == nullptr.
Vladimir Markof4da6752014-08-01 19:04:18 +010056 virtual uint32_t ReserveSpace(uint32_t offset, const CompiledMethod* compiled_method) = 0;
57
58 // Write relative call thunks if needed, return adjusted offset.
59 virtual uint32_t WriteThunks(OutputStream* out, uint32_t offset) = 0;
60
61 // Patch method code. The input displacement is relative to the patched location,
62 // the patcher may need to adjust it if the correct base is different.
Vladimir Marko20f85592015-03-19 10:07:02 +000063 virtual void PatchCall(std::vector<uint8_t>* code, uint32_t literal_offset,
64 uint32_t patch_offset, uint32_t target_offset) = 0;
65
66 // Patch a reference to a dex cache location.
67 virtual void PatchDexCacheReference(std::vector<uint8_t>* code, const LinkerPatch& patch,
68 uint32_t patch_offset, uint32_t target_offset) = 0;
Vladimir Markof4da6752014-08-01 19:04:18 +010069
70 protected:
Vladimir Marko20f85592015-03-19 10:07:02 +000071 RelativePatcher() { }
Vladimir Markof4da6752014-08-01 19:04:18 +010072
73 private:
Vladimir Marko20f85592015-03-19 10:07:02 +000074 DISALLOW_COPY_AND_ASSIGN(RelativePatcher);
Vladimir Markof4da6752014-08-01 19:04:18 +010075};
76
Vladimir Marko20f85592015-03-19 10:07:02 +000077class OatWriter::NoRelativePatcher FINAL : public RelativePatcher {
Vladimir Markof4da6752014-08-01 19:04:18 +010078 public:
Vladimir Marko20f85592015-03-19 10:07:02 +000079 NoRelativePatcher() { }
Vladimir Markof4da6752014-08-01 19:04:18 +010080
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070081 uint32_t ReserveSpace(uint32_t offset,
82 const CompiledMethod* compiled_method ATTRIBUTE_UNUSED) OVERRIDE {
Vladimir Markof4da6752014-08-01 19:04:18 +010083 return offset; // No space reserved; no patches expected.
84 }
85
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070086 uint32_t WriteThunks(OutputStream* out ATTRIBUTE_UNUSED, uint32_t offset) OVERRIDE {
Vladimir Markof4da6752014-08-01 19:04:18 +010087 return offset; // No thunks added; no patches expected.
88 }
89
Vladimir Marko20f85592015-03-19 10:07:02 +000090 void PatchCall(std::vector<uint8_t>* code ATTRIBUTE_UNUSED,
91 uint32_t literal_offset ATTRIBUTE_UNUSED,
92 uint32_t patch_offset ATTRIBUTE_UNUSED,
93 uint32_t target_offset ATTRIBUTE_UNUSED) OVERRIDE {
94 LOG(FATAL) << "Unexpected relative call patch.";
95 }
96
97 virtual void PatchDexCacheReference(std::vector<uint8_t>* code ATTRIBUTE_UNUSED,
98 const LinkerPatch& patch ATTRIBUTE_UNUSED,
99 uint32_t patch_offset ATTRIBUTE_UNUSED,
100 uint32_t target_offset ATTRIBUTE_UNUSED) {
101 LOG(FATAL) << "Unexpected relative dex cache array patch.";
Vladimir Markof4da6752014-08-01 19:04:18 +0100102 }
103
104 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000105 DISALLOW_COPY_AND_ASSIGN(NoRelativePatcher);
Vladimir Markof4da6752014-08-01 19:04:18 +0100106};
107
Vladimir Marko20f85592015-03-19 10:07:02 +0000108class OatWriter::X86RelativePatcher FINAL : public RelativePatcher {
Vladimir Markof4da6752014-08-01 19:04:18 +0100109 public:
Vladimir Marko20f85592015-03-19 10:07:02 +0000110 X86RelativePatcher() { }
Vladimir Markof4da6752014-08-01 19:04:18 +0100111
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700112 uint32_t ReserveSpace(uint32_t offset,
113 const CompiledMethod* compiled_method ATTRIBUTE_UNUSED) OVERRIDE {
Vladimir Markof4da6752014-08-01 19:04:18 +0100114 return offset; // No space reserved; no limit on relative call distance.
115 }
116
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700117 uint32_t WriteThunks(OutputStream* out ATTRIBUTE_UNUSED, uint32_t offset) OVERRIDE {
Vladimir Markof4da6752014-08-01 19:04:18 +0100118 return offset; // No thunks added; no limit on relative call distance.
119 }
120
Vladimir Marko20f85592015-03-19 10:07:02 +0000121 void PatchCall(std::vector<uint8_t>* code, uint32_t literal_offset,
122 uint32_t patch_offset, uint32_t target_offset) OVERRIDE {
Vladimir Markof4da6752014-08-01 19:04:18 +0100123 DCHECK_LE(literal_offset + 4u, code->size());
124 // Unsigned arithmetic with its well-defined overflow behavior is just fine here.
125 uint32_t displacement = target_offset - patch_offset;
126 displacement -= kPcDisplacement; // The base PC is at the end of the 4-byte patch.
127
128 typedef __attribute__((__aligned__(1))) int32_t unaligned_int32_t;
129 reinterpret_cast<unaligned_int32_t*>(&(*code)[literal_offset])[0] = displacement;
130 }
131
Vladimir Marko20f85592015-03-19 10:07:02 +0000132 virtual void PatchDexCacheReference(std::vector<uint8_t>* code ATTRIBUTE_UNUSED,
133 const LinkerPatch& patch ATTRIBUTE_UNUSED,
134 uint32_t patch_offset ATTRIBUTE_UNUSED,
135 uint32_t target_offset ATTRIBUTE_UNUSED) {
136 LOG(FATAL) << "Unexpected relative dex cache array patch.";
137 }
138
Vladimir Markof4da6752014-08-01 19:04:18 +0100139 private:
140 // PC displacement from patch location; x86 PC for relative calls points to the next
141 // instruction and the patch location is 4 bytes earlier.
142 static constexpr int32_t kPcDisplacement = 4;
143
Vladimir Marko20f85592015-03-19 10:07:02 +0000144 DISALLOW_COPY_AND_ASSIGN(X86RelativePatcher);
Vladimir Markof4da6752014-08-01 19:04:18 +0100145};
146
Vladimir Marko20f85592015-03-19 10:07:02 +0000147class OatWriter::ArmBaseRelativePatcher : public RelativePatcher {
Vladimir Markof4da6752014-08-01 19:04:18 +0100148 public:
Vladimir Marko20f85592015-03-19 10:07:02 +0000149 ArmBaseRelativePatcher(OatWriter* writer,
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100150 InstructionSet instruction_set, std::vector<uint8_t> thunk_code,
151 uint32_t max_positive_displacement, uint32_t max_negative_displacement)
152 : writer_(writer), instruction_set_(instruction_set), thunk_code_(thunk_code),
153 max_positive_displacement_(max_positive_displacement),
154 max_negative_displacement_(max_negative_displacement),
Vladimir Markof4da6752014-08-01 19:04:18 +0100155 thunk_locations_(), current_thunk_to_write_(0u), unprocessed_patches_() {
156 }
157
158 uint32_t ReserveSpace(uint32_t offset, const CompiledMethod* compiled_method) OVERRIDE {
Vladimir Markoc74658b2015-03-31 10:26:41 +0100159 return ReserveSpaceInternal(offset, compiled_method, 0u);
Vladimir Markof4da6752014-08-01 19:04:18 +0100160 }
161
162 uint32_t WriteThunks(OutputStream* out, uint32_t offset) OVERRIDE {
163 if (current_thunk_to_write_ == thunk_locations_.size()) {
164 return offset;
165 }
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100166 uint32_t aligned_offset = CompiledMethod::AlignCode(offset, instruction_set_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100167 if (UNLIKELY(aligned_offset == thunk_locations_[current_thunk_to_write_])) {
168 ++current_thunk_to_write_;
169 uint32_t aligned_code_delta = aligned_offset - offset;
170 if (aligned_code_delta != 0u && !writer_->WriteCodeAlignment(out, aligned_code_delta)) {
171 return 0u;
172 }
173 if (!out->WriteFully(thunk_code_.data(), thunk_code_.size())) {
174 return 0u;
175 }
176 writer_->size_relative_call_thunks_ += thunk_code_.size();
177 uint32_t thunk_end_offset = aligned_offset + thunk_code_.size();
178 // Align after writing chunk, see the ReserveSpace() above.
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100179 offset = CompiledMethod::AlignCode(thunk_end_offset, instruction_set_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100180 aligned_code_delta = offset - thunk_end_offset;
181 if (aligned_code_delta != 0u && !writer_->WriteCodeAlignment(out, aligned_code_delta)) {
182 return 0u;
183 }
184 }
185 return offset;
186 }
187
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100188 protected:
Vladimir Markoc74658b2015-03-31 10:26:41 +0100189 uint32_t ReserveSpaceInternal(uint32_t offset, const CompiledMethod* compiled_method,
190 uint32_t max_extra_space) {
191 // NOTE: The final thunk can be reserved from InitCodeMethodVisitor::EndClass() while it
192 // may be written early by WriteCodeMethodVisitor::VisitMethod() for a deduplicated chunk
193 // of code. To avoid any alignment discrepancies for the final chunk, we always align the
194 // offset after reserving of writing any chunk.
195 if (UNLIKELY(compiled_method == nullptr)) {
196 uint32_t aligned_offset = CompiledMethod::AlignCode(offset, instruction_set_);
197 bool needs_thunk = ReserveSpaceProcessPatches(aligned_offset);
198 if (needs_thunk) {
199 thunk_locations_.push_back(aligned_offset);
200 offset = CompiledMethod::AlignCode(aligned_offset + thunk_code_.size(), instruction_set_);
201 }
202 return offset;
203 }
204 DCHECK(compiled_method->GetQuickCode() != nullptr);
205 uint32_t quick_code_size = compiled_method->GetQuickCode()->size();
206 uint32_t quick_code_offset = compiled_method->AlignCode(offset) + sizeof(OatQuickMethodHeader);
207 uint32_t next_aligned_offset = compiled_method->AlignCode(quick_code_offset + quick_code_size);
208 // Adjust for extra space required by the subclass.
209 next_aligned_offset = compiled_method->AlignCode(next_aligned_offset + max_extra_space);
210 if (!unprocessed_patches_.empty() &&
211 next_aligned_offset - unprocessed_patches_.front().second > max_positive_displacement_) {
212 bool needs_thunk = ReserveSpaceProcessPatches(next_aligned_offset);
213 if (needs_thunk) {
214 // A single thunk will cover all pending patches.
215 unprocessed_patches_.clear();
216 uint32_t thunk_location = compiled_method->AlignCode(offset);
217 thunk_locations_.push_back(thunk_location);
218 offset = CompiledMethod::AlignCode(thunk_location + thunk_code_.size(), instruction_set_);
219 }
220 }
221 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
222 if (patch.Type() == kLinkerPatchCallRelative) {
223 unprocessed_patches_.emplace_back(patch.TargetMethod(),
224 quick_code_offset + patch.LiteralOffset());
225 }
226 }
227 return offset;
228 }
229
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100230 uint32_t CalculateDisplacement(uint32_t patch_offset, uint32_t target_offset) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100231 // Unsigned arithmetic with its well-defined overflow behavior is just fine here.
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100232 uint32_t displacement = target_offset - patch_offset;
Vladimir Markof4da6752014-08-01 19:04:18 +0100233 // NOTE: With unsigned arithmetic we do mean to use && rather than || below.
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100234 if (displacement > max_positive_displacement_ && displacement < -max_negative_displacement_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100235 // Unwritten thunks have higher offsets, check if it's within range.
236 DCHECK(current_thunk_to_write_ == thunk_locations_.size() ||
237 thunk_locations_[current_thunk_to_write_] > patch_offset);
238 if (current_thunk_to_write_ != thunk_locations_.size() &&
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100239 thunk_locations_[current_thunk_to_write_] - patch_offset < max_positive_displacement_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100240 displacement = thunk_locations_[current_thunk_to_write_] - patch_offset;
241 } else {
242 // We must have a previous thunk then.
243 DCHECK_NE(current_thunk_to_write_, 0u);
244 DCHECK_LT(thunk_locations_[current_thunk_to_write_ - 1], patch_offset);
245 displacement = thunk_locations_[current_thunk_to_write_ - 1] - patch_offset;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100246 DCHECK(displacement >= -max_negative_displacement_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100247 }
248 }
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100249 return displacement;
250 }
251
Vladimir Markoc74658b2015-03-31 10:26:41 +0100252 OatWriter* Writer() const {
253 return writer_;
254 }
255
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100256 private:
257 bool ReserveSpaceProcessPatches(uint32_t next_aligned_offset) {
258 // Process as many patches as possible, stop only on unresolved targets or calls too far back.
259 while (!unprocessed_patches_.empty()) {
260 uint32_t patch_offset = unprocessed_patches_.front().second;
261 auto it = writer_->method_offset_map_.find(unprocessed_patches_.front().first);
262 if (it == writer_->method_offset_map_.end()) {
263 // If still unresolved, check if we have a thunk within range.
264 DCHECK(thunk_locations_.empty() || thunk_locations_.back() <= patch_offset);
265 if (thunk_locations_.empty() ||
266 patch_offset - thunk_locations_.back() > max_negative_displacement_) {
267 return next_aligned_offset - patch_offset > max_positive_displacement_;
268 }
269 } else if (it->second >= patch_offset) {
270 DCHECK_LE(it->second - patch_offset, max_positive_displacement_);
271 } else {
272 // When calling back, check if we have a thunk that's closer than the actual target.
273 uint32_t target_offset = (thunk_locations_.empty() || it->second > thunk_locations_.back())
274 ? it->second
275 : thunk_locations_.back();
276 DCHECK_GT(patch_offset, target_offset);
277 if (patch_offset - target_offset > max_negative_displacement_) {
278 return true;
279 }
280 }
281 unprocessed_patches_.pop_front();
282 }
283 return false;
284 }
285
286 OatWriter* const writer_;
287 const InstructionSet instruction_set_;
288 const std::vector<uint8_t> thunk_code_;
289 const uint32_t max_positive_displacement_;
290 const uint32_t max_negative_displacement_;
291 std::vector<uint32_t> thunk_locations_;
292 size_t current_thunk_to_write_;
293
294 // ReserveSpace() tracks unprocessed patches.
295 typedef std::pair<MethodReference, uint32_t> UnprocessedPatch;
296 std::deque<UnprocessedPatch> unprocessed_patches_;
297
Vladimir Marko20f85592015-03-19 10:07:02 +0000298 DISALLOW_COPY_AND_ASSIGN(ArmBaseRelativePatcher);
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100299};
300
Vladimir Marko20f85592015-03-19 10:07:02 +0000301class OatWriter::Thumb2RelativePatcher FINAL : public ArmBaseRelativePatcher {
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100302 public:
Vladimir Marko20f85592015-03-19 10:07:02 +0000303 explicit Thumb2RelativePatcher(OatWriter* writer)
304 : ArmBaseRelativePatcher(writer, kThumb2, CompileThunkCode(),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100305 kMaxPositiveDisplacement, kMaxNegativeDisplacement) {
306 }
307
Vladimir Marko20f85592015-03-19 10:07:02 +0000308 void PatchCall(std::vector<uint8_t>* code, uint32_t literal_offset,
309 uint32_t patch_offset, uint32_t target_offset) OVERRIDE {
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100310 DCHECK_LE(literal_offset + 4u, code->size());
311 DCHECK_EQ(literal_offset & 1u, 0u);
312 DCHECK_EQ(patch_offset & 1u, 0u);
313 DCHECK_EQ(target_offset & 1u, 1u); // Thumb2 mode bit.
314 uint32_t displacement = CalculateDisplacement(patch_offset, target_offset & ~1u);
Vladimir Markof4da6752014-08-01 19:04:18 +0100315 displacement -= kPcDisplacement; // The base PC is at the end of the 4-byte patch.
316 DCHECK_EQ(displacement & 1u, 0u);
317 DCHECK((displacement >> 24) == 0u || (displacement >> 24) == 255u); // 25-bit signed.
318 uint32_t signbit = (displacement >> 31) & 0x1;
319 uint32_t i1 = (displacement >> 23) & 0x1;
320 uint32_t i2 = (displacement >> 22) & 0x1;
321 uint32_t imm10 = (displacement >> 12) & 0x03ff;
322 uint32_t imm11 = (displacement >> 1) & 0x07ff;
323 uint32_t j1 = i1 ^ (signbit ^ 1);
324 uint32_t j2 = i2 ^ (signbit ^ 1);
325 uint32_t value = (signbit << 26) | (j1 << 13) | (j2 << 11) | (imm10 << 16) | imm11;
326 value |= 0xf000d000; // BL
327
328 uint8_t* addr = &(*code)[literal_offset];
329 // Check that we're just overwriting an existing BL.
330 DCHECK_EQ(addr[1] & 0xf8, 0xf0);
331 DCHECK_EQ(addr[3] & 0xd0, 0xd0);
332 // Write the new BL.
333 addr[0] = (value >> 16) & 0xff;
334 addr[1] = (value >> 24) & 0xff;
335 addr[2] = (value >> 0) & 0xff;
336 addr[3] = (value >> 8) & 0xff;
337 }
338
Vladimir Marko20f85592015-03-19 10:07:02 +0000339 virtual void PatchDexCacheReference(std::vector<uint8_t>* code ATTRIBUTE_UNUSED,
340 const LinkerPatch& patch ATTRIBUTE_UNUSED,
341 uint32_t patch_offset ATTRIBUTE_UNUSED,
342 uint32_t target_offset ATTRIBUTE_UNUSED) {
343 LOG(FATAL) << "Unexpected relative dex cache array patch.";
344 }
345
Vladimir Markof4da6752014-08-01 19:04:18 +0100346 private:
Vladimir Markof4da6752014-08-01 19:04:18 +0100347 static std::vector<uint8_t> CompileThunkCode() {
348 // The thunk just uses the entry point in the ArtMethod. This works even for calls
349 // to the generic JNI and interpreter trampolines.
350 arm::Thumb2Assembler assembler;
351 assembler.LoadFromOffset(
352 arm::kLoadWord, arm::PC, arm::R0,
Mathieu Chartier2d721012014-11-10 11:08:06 -0800353 mirror::ArtMethod::EntryPointFromQuickCompiledCodeOffset(kArmPointerSize).Int32Value());
Vladimir Markof4da6752014-08-01 19:04:18 +0100354 assembler.bkpt(0);
355 std::vector<uint8_t> thunk_code(assembler.CodeSize());
356 MemoryRegion code(thunk_code.data(), thunk_code.size());
357 assembler.FinalizeInstructions(code);
358 return thunk_code;
359 }
360
361 // PC displacement from patch location; Thumb2 PC is always at instruction address + 4.
362 static constexpr int32_t kPcDisplacement = 4;
363
364 // Maximum positive and negative displacement measured from the patch location.
365 // (Signed 25 bit displacement with the last bit 0 has range [-2^24, 2^24-2] measured from
366 // the Thumb2 PC pointing right after the BL, i.e. 4 bytes later than the patch location.)
367 static constexpr uint32_t kMaxPositiveDisplacement = (1u << 24) - 2 + kPcDisplacement;
368 static constexpr uint32_t kMaxNegativeDisplacement = (1u << 24) - kPcDisplacement;
369
Vladimir Marko20f85592015-03-19 10:07:02 +0000370 DISALLOW_COPY_AND_ASSIGN(Thumb2RelativePatcher);
Vladimir Markof4da6752014-08-01 19:04:18 +0100371};
372
Vladimir Marko20f85592015-03-19 10:07:02 +0000373class OatWriter::Arm64RelativePatcher FINAL : public ArmBaseRelativePatcher {
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100374 public:
Vladimir Marko20f85592015-03-19 10:07:02 +0000375 explicit Arm64RelativePatcher(OatWriter* writer)
376 : ArmBaseRelativePatcher(writer, kArm64, CompileThunkCode(),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100377 kMaxPositiveDisplacement, kMaxNegativeDisplacement),
378 fix_cortex_a53_843419_(writer->compiler_driver_->GetInstructionSetFeatures()
379 ->AsArm64InstructionSetFeatures()->NeedFixCortexA53_835769()),
380 reserved_adrp_thunks_(0u),
381 processed_adrp_thunks_(0u) {
382 if (fix_cortex_a53_843419_) {
383 adrp_thunk_locations_.reserve(16u);
384 current_method_thunks_.reserve(16u * kAdrpThunkSize);
385 }
386 }
387
388 uint32_t ReserveSpace(uint32_t offset, const CompiledMethod* compiled_method) OVERRIDE {
389 if (!fix_cortex_a53_843419_) {
390 DCHECK(adrp_thunk_locations_.empty());
391 return ReserveSpaceInternal(offset, compiled_method, 0u);
392 }
393
394 // Add thunks for previous method if any.
395 if (reserved_adrp_thunks_ != adrp_thunk_locations_.size()) {
396 size_t num_adrp_thunks = adrp_thunk_locations_.size() - reserved_adrp_thunks_;
397 offset = CompiledMethod::AlignCode(offset, kArm64) + kAdrpThunkSize * num_adrp_thunks;
398 reserved_adrp_thunks_ = adrp_thunk_locations_.size();
399 }
400
401 // Count the number of ADRP insns as the upper bound on the number of thunks needed
402 // and use it to reserve space for other linker patches.
403 size_t num_adrp = 0u;
404 if (LIKELY(compiled_method != nullptr)) {
405 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
406 if (patch.Type() == kLinkerPatchDexCacheArray &&
407 patch.LiteralOffset() == patch.PcInsnOffset()) { // ADRP patch
408 ++num_adrp;
409 }
410 }
411 }
412 offset = ReserveSpaceInternal(offset, compiled_method, kAdrpThunkSize * num_adrp);
413 if (num_adrp == 0u) {
414 return offset;
415 }
416
417 // Now that we have the actual offset where the code will be placed, locate the ADRP insns
418 // that actually require the thunk.
419 uint32_t quick_code_offset = compiled_method->AlignCode(offset) + sizeof(OatQuickMethodHeader);
420 ArrayRef<const uint8_t> code(*compiled_method->GetQuickCode());
421 uint32_t thunk_offset = compiled_method->AlignCode(quick_code_offset + code.size());
422 DCHECK(compiled_method != nullptr);
423 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
424 if (patch.Type() == kLinkerPatchDexCacheArray &&
425 patch.LiteralOffset() == patch.PcInsnOffset()) { // ADRP patch
426 uint32_t patch_offset = quick_code_offset + patch.LiteralOffset();
427 if (NeedsErratum843419Thunk(code, patch.LiteralOffset(), patch_offset)) {
428 adrp_thunk_locations_.emplace_back(patch_offset, thunk_offset);
429 thunk_offset += kAdrpThunkSize;
430 }
431 }
432 }
433 return offset;
434 }
435
436 uint32_t WriteThunks(OutputStream* out, uint32_t offset) OVERRIDE {
437 if (fix_cortex_a53_843419_) {
438 if (!current_method_thunks_.empty()) {
439 uint32_t aligned_offset = CompiledMethod::AlignCode(offset, kArm64);
440 if (kIsDebugBuild) {
441 CHECK(IsAligned<kAdrpThunkSize>(current_method_thunks_.size()));
442 size_t num_thunks = current_method_thunks_.size() / kAdrpThunkSize;
443 CHECK_LE(num_thunks, processed_adrp_thunks_);
444 for (size_t i = 0u; i != num_thunks; ++i) {
445 const auto& entry = adrp_thunk_locations_[processed_adrp_thunks_ - num_thunks + i];
446 CHECK_EQ(entry.second, aligned_offset + i * kAdrpThunkSize);
447 }
448 }
449 uint32_t aligned_code_delta = aligned_offset - offset;
450 if (aligned_code_delta != 0u && !Writer()->WriteCodeAlignment(out, aligned_code_delta)) {
451 return 0u;
452 }
453 if (!out->WriteFully(&current_method_thunks_[0], current_method_thunks_.size())) {
454 return 0u;
455 }
456 Writer()->size_misc_thunks_ += current_method_thunks_.size();
457 offset = aligned_offset + current_method_thunks_.size();
458 current_method_thunks_.clear();
459 }
460 }
461 return ArmBaseRelativePatcher::WriteThunks(out, offset);
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100462 }
463
Vladimir Marko20f85592015-03-19 10:07:02 +0000464 void PatchCall(std::vector<uint8_t>* code, uint32_t literal_offset,
465 uint32_t patch_offset, uint32_t target_offset) OVERRIDE {
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100466 DCHECK_LE(literal_offset + 4u, code->size());
467 DCHECK_EQ(literal_offset & 3u, 0u);
468 DCHECK_EQ(patch_offset & 3u, 0u);
469 DCHECK_EQ(target_offset & 3u, 0u);
470 uint32_t displacement = CalculateDisplacement(patch_offset, target_offset & ~1u);
471 DCHECK_EQ(displacement & 3u, 0u);
472 DCHECK((displacement >> 27) == 0u || (displacement >> 27) == 31u); // 28-bit signed.
Vladimir Marko20f85592015-03-19 10:07:02 +0000473 uint32_t insn = (displacement & 0x0fffffffu) >> 2;
474 insn |= 0x94000000; // BL
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100475
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100476 // Check that we're just overwriting an existing BL.
Vladimir Marko20f85592015-03-19 10:07:02 +0000477 DCHECK_EQ(GetInsn(code, literal_offset) & 0xfc000000u, 0x94000000u);
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100478 // Write the new BL.
Vladimir Marko20f85592015-03-19 10:07:02 +0000479 SetInsn(code, literal_offset, insn);
480 }
481
482 virtual void PatchDexCacheReference(std::vector<uint8_t>* code ATTRIBUTE_UNUSED,
483 const LinkerPatch& patch ATTRIBUTE_UNUSED,
484 uint32_t patch_offset ATTRIBUTE_UNUSED,
485 uint32_t target_offset ATTRIBUTE_UNUSED) {
486 DCHECK_EQ(patch_offset & 3u, 0u);
487 DCHECK_EQ(target_offset & 3u, 0u);
488 uint32_t literal_offset = patch.LiteralOffset();
489 uint32_t insn = GetInsn(code, literal_offset);
490 uint32_t pc_insn_offset = patch.PcInsnOffset();
491 uint32_t disp = target_offset - ((patch_offset - literal_offset + pc_insn_offset) & ~0xfffu);
492 if (literal_offset == pc_insn_offset) {
493 // Check it's an ADRP with imm == 0 (unset).
494 DCHECK_EQ((insn & 0xffffffe0u), 0x90000000u)
495 << literal_offset << ", " << pc_insn_offset << ", 0x" << std::hex << insn;
Vladimir Markoc74658b2015-03-31 10:26:41 +0100496 if (fix_cortex_a53_843419_ && processed_adrp_thunks_ != adrp_thunk_locations_.size() &&
497 adrp_thunk_locations_[processed_adrp_thunks_].first == patch_offset) {
498 DCHECK(NeedsErratum843419Thunk(ArrayRef<const uint8_t>(*code),
499 literal_offset, patch_offset));
500 uint32_t thunk_offset = adrp_thunk_locations_[processed_adrp_thunks_].second;
501 uint32_t adrp_disp = target_offset - (thunk_offset & ~0xfffu);
502 uint32_t adrp = PatchAdrp(insn, adrp_disp);
503
504 uint32_t out_disp = thunk_offset - patch_offset;
505 DCHECK_EQ(out_disp & 3u, 0u);
506 DCHECK((out_disp >> 27) == 0u || (out_disp >> 27) == 31u); // 28-bit signed.
507 insn = (out_disp & 0x0fffffffu) >> 2;
508 insn |= 0x14000000; // B <thunk>
509
510 uint32_t back_disp = -out_disp;
511 DCHECK_EQ(back_disp & 3u, 0u);
512 DCHECK((back_disp >> 27) == 0u || (back_disp >> 27) == 31u); // 28-bit signed.
513 uint32_t b_back = (back_disp & 0x0fffffffu) >> 2;
514 b_back |= 0x14000000; // B <back>
515 size_t thunks_code_offset = current_method_thunks_.size();
516 current_method_thunks_.resize(thunks_code_offset + kAdrpThunkSize);
517 SetInsn(&current_method_thunks_, thunks_code_offset, adrp);
518 SetInsn(&current_method_thunks_, thunks_code_offset + 4u, b_back);
519 static_assert(kAdrpThunkSize == 2 * 4u, "thunk has 2 instructions");
520
521 processed_adrp_thunks_ += 1u;
522 } else {
523 insn = PatchAdrp(insn, disp);
524 }
525 // Write the new ADRP (or B to the erratum 843419 thunk).
Vladimir Marko20f85592015-03-19 10:07:02 +0000526 SetInsn(code, literal_offset, insn);
527 } else {
528 DCHECK_EQ(insn & 0xfffffc00, 0xb9400000); // LDR 32-bit with imm12 == 0 (unset).
Vladimir Markoc74658b2015-03-31 10:26:41 +0100529 if (kIsDebugBuild) {
530 uint32_t adrp = GetInsn(code, pc_insn_offset);
531 if ((adrp & 0x9f000000u) != 0x90000000u) {
532 CHECK(fix_cortex_a53_843419_);
533 CHECK_EQ(adrp & 0xfc000000u, 0x14000000u); // B <thunk>
534 CHECK(IsAligned<kAdrpThunkSize>(current_method_thunks_.size()));
535 size_t num_thunks = current_method_thunks_.size() / kAdrpThunkSize;
536 CHECK_LE(num_thunks, processed_adrp_thunks_);
537 uint32_t b_offset = patch_offset - literal_offset + pc_insn_offset;
538 for (size_t i = processed_adrp_thunks_ - num_thunks; ; ++i) {
539 CHECK_NE(i, processed_adrp_thunks_);
540 if (adrp_thunk_locations_[i].first == b_offset) {
541 size_t idx = num_thunks - (processed_adrp_thunks_ - i);
542 adrp = GetInsn(&current_method_thunks_, idx * kAdrpThunkSize);
543 break;
544 }
545 }
546 }
547 CHECK_EQ(adrp & 0x9f00001fu, // Check that pc_insn_offset points
548 0x90000000 | ((insn >> 5) & 0x1fu)); // to ADRP with matching register.
549 }
Vladimir Marko20f85592015-03-19 10:07:02 +0000550 uint32_t imm12 = (disp & 0xfffu) >> 2;
551 insn = (insn & ~(0xfffu << 10)) | (imm12 << 10);
552 SetInsn(code, literal_offset, insn);
553 }
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100554 }
555
556 private:
Vladimir Markoc74658b2015-03-31 10:26:41 +0100557 static uint32_t PatchAdrp(uint32_t adrp, uint32_t disp) {
558 return (adrp & 0x9f00001fu) | // Clear offset bits, keep ADRP with destination reg.
559 // Bottom 12 bits are ignored, the next 2 lowest bits are encoded in bits 29-30.
560 ((disp & 0x00003000u) << (29 - 12)) |
561 // The next 16 bits are encoded in bits 5-22.
562 ((disp & 0xffffc000u) >> (12 + 2 - 5)) |
563 // Since the target_offset is based on the beginning of the oat file and the
564 // image space precedes the oat file, the target_offset into image space will
565 // be negative yet passed as uint32_t. Therefore we limit the displacement
566 // to +-2GiB (rather than the maximim +-4GiB) and determine the sign bit from
567 // the highest bit of the displacement. This is encoded in bit 23.
568 ((disp & 0x80000000u) >> (31 - 23));
569 }
570
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100571 static std::vector<uint8_t> CompileThunkCode() {
572 // The thunk just uses the entry point in the ArtMethod. This works even for calls
573 // to the generic JNI and interpreter trampolines.
574 arm64::Arm64Assembler assembler;
Mathieu Chartier2d721012014-11-10 11:08:06 -0800575 Offset offset(mirror::ArtMethod::EntryPointFromQuickCompiledCodeOffset(
576 kArm64PointerSize).Int32Value());
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100577 assembler.JumpTo(ManagedRegister(arm64::X0), offset, ManagedRegister(arm64::IP0));
Serban Constantinescu32f5b4d2014-11-25 20:05:46 +0000578 // Ensure we emit the literal pool.
579 assembler.EmitSlowPaths();
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100580 std::vector<uint8_t> thunk_code(assembler.CodeSize());
581 MemoryRegion code(thunk_code.data(), thunk_code.size());
582 assembler.FinalizeInstructions(code);
583 return thunk_code;
584 }
585
Vladimir Markoc74658b2015-03-31 10:26:41 +0100586 static bool NeedsErratum843419Thunk(ArrayRef<const uint8_t> code, uint32_t literal_offset,
587 uint32_t patch_offset) {
588 DCHECK_EQ(patch_offset & 0x3u, 0u);
589 if ((patch_offset & 0xff8) == 0xff8) { // ...ff8 or ...ffc
590 uint32_t adrp = GetInsn(code, literal_offset);
591 DCHECK_EQ(adrp & 0xff000000, 0x90000000);
592 // TODO: Improve the check. For now, we're just checking if the next insn is
593 // the LDR using the result of the ADRP, otherwise we implement the workaround.
594 uint32_t next_insn = GetInsn(code, literal_offset + 4u);
595 bool ok = (next_insn & 0xffc00000) == 0xb9400000 && // LDR <Wt>, [<Xn>, #pimm]
596 (((next_insn >> 5) ^ adrp) & 0x1f) == 0; // <Xn> == ADRP destination reg
597 return !ok;
598 }
599 return false;
600 }
601
602 static uint32_t GetInsn(ArrayRef<const uint8_t> code, uint32_t offset) {
603 DCHECK_LE(offset + 4u, code.size());
Vladimir Marko20f85592015-03-19 10:07:02 +0000604 DCHECK_EQ(offset & 3u, 0u);
Vladimir Markoc74658b2015-03-31 10:26:41 +0100605 const uint8_t* addr = &code[offset];
Vladimir Marko20f85592015-03-19 10:07:02 +0000606 return
607 (static_cast<uint32_t>(addr[0]) << 0) +
608 (static_cast<uint32_t>(addr[1]) << 8) +
609 (static_cast<uint32_t>(addr[2]) << 16)+
610 (static_cast<uint32_t>(addr[3]) << 24);
611 }
612
Vladimir Markoc74658b2015-03-31 10:26:41 +0100613 template <typename Alloc>
614 static uint32_t GetInsn(std::vector<uint8_t, Alloc>* code, uint32_t offset) {
615 return GetInsn(ArrayRef<const uint8_t>(*code), offset);
616 }
617
Vladimir Marko20f85592015-03-19 10:07:02 +0000618 void SetInsn(std::vector<uint8_t>* code, uint32_t offset, uint32_t value) {
619 DCHECK_LE(offset + 4u, code->size());
620 DCHECK_EQ(offset & 3u, 0u);
621 uint8_t* addr = &(*code)[offset];
622 addr[0] = (value >> 0) & 0xff;
623 addr[1] = (value >> 8) & 0xff;
624 addr[2] = (value >> 16) & 0xff;
625 addr[3] = (value >> 24) & 0xff;
626 }
627
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100628 // Maximum positive and negative displacement measured from the patch location.
629 // (Signed 28 bit displacement with the last bit 0 has range [-2^27, 2^27-4] measured from
630 // the ARM64 PC pointing to the BL.)
631 static constexpr uint32_t kMaxPositiveDisplacement = (1u << 27) - 4u;
632 static constexpr uint32_t kMaxNegativeDisplacement = (1u << 27);
633
Vladimir Markoc74658b2015-03-31 10:26:41 +0100634 // The ADRP thunk for erratum 843419 is 2 instructions, i.e. 8 bytes.
635 static constexpr uint32_t kAdrpThunkSize = 8u;
636
637 const bool fix_cortex_a53_843419_;
638 // Map original patch_offset to thunk offset.
639 std::vector<std::pair<uint32_t, uint32_t>> adrp_thunk_locations_;
640 size_t reserved_adrp_thunks_;
641 size_t processed_adrp_thunks_;
642 std::vector<uint8_t> current_method_thunks_;
643
Vladimir Marko20f85592015-03-19 10:07:02 +0000644 DISALLOW_COPY_AND_ASSIGN(Arm64RelativePatcher);
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100645};
646
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100647#define DCHECK_OFFSET() \
648 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
649 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
650
651#define DCHECK_OFFSET_() \
652 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
653 << "file_offset=" << file_offset << " offset_=" << offset_
654
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700655OatWriter::OatWriter(const std::vector<const DexFile*>& dex_files,
Brian Carlstrom28db0122012-10-18 16:20:41 -0700656 uint32_t image_file_location_oat_checksum,
Ian Rogersef7d42f2014-01-06 12:55:46 -0800657 uintptr_t image_file_location_oat_begin,
Alex Lighta59dd802014-07-02 16:28:08 -0700658 int32_t image_patch_delta,
Ian Rogersca368cb2013-11-15 15:52:08 -0800659 const CompilerDriver* compiler,
Vladimir Markof4da6752014-08-01 19:04:18 +0100660 ImageWriter* image_writer,
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700661 TimingLogger* timings,
662 SafeMap<std::string, std::string>* key_value_store)
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700663 : compiler_driver_(compiler),
Vladimir Markof4da6752014-08-01 19:04:18 +0100664 image_writer_(image_writer),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700665 dex_files_(&dex_files),
Vladimir Markof4da6752014-08-01 19:04:18 +0100666 size_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000667 bss_size_(0u),
Vladimir Markof4da6752014-08-01 19:04:18 +0100668 oat_data_offset_(0u),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700669 image_file_location_oat_checksum_(image_file_location_oat_checksum),
670 image_file_location_oat_begin_(image_file_location_oat_begin),
Alex Lighta59dd802014-07-02 16:28:08 -0700671 image_patch_delta_(image_patch_delta),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700672 key_value_store_(key_value_store),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700673 oat_header_(NULL),
674 size_dex_file_alignment_(0),
675 size_executable_offset_alignment_(0),
676 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700677 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700678 size_dex_file_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700679 size_interpreter_to_interpreter_bridge_(0),
680 size_interpreter_to_compiled_code_bridge_(0),
681 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800682 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700683 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700684 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700685 size_quick_to_interpreter_bridge_(0),
686 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100687 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700688 size_code_(0),
689 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100690 size_relative_call_thunks_(0),
Vladimir Markoc74658b2015-03-31 10:26:41 +0100691 size_misc_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700692 size_mapping_table_(0),
693 size_vmap_table_(0),
694 size_gc_map_(0),
695 size_oat_dex_file_location_size_(0),
696 size_oat_dex_file_location_data_(0),
697 size_oat_dex_file_location_checksum_(0),
698 size_oat_dex_file_offset_(0),
699 size_oat_dex_file_methods_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700700 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700701 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700702 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100703 size_oat_class_method_offsets_(0),
704 method_offset_map_() {
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700705 CHECK(key_value_store != nullptr);
706
Vladimir Markof4da6752014-08-01 19:04:18 +0100707 switch (compiler_driver_->GetInstructionSet()) {
708 case kX86:
709 case kX86_64:
Vladimir Marko20f85592015-03-19 10:07:02 +0000710 relative_patcher_.reset(new X86RelativePatcher);
Vladimir Markof4da6752014-08-01 19:04:18 +0100711 break;
712 case kArm:
713 // Fall through: we generate Thumb2 code for "arm".
714 case kThumb2:
Vladimir Marko20f85592015-03-19 10:07:02 +0000715 relative_patcher_.reset(new Thumb2RelativePatcher(this));
Vladimir Markof4da6752014-08-01 19:04:18 +0100716 break;
717 case kArm64:
Vladimir Marko20f85592015-03-19 10:07:02 +0000718 relative_patcher_.reset(new Arm64RelativePatcher(this));
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100719 break;
Vladimir Markof4da6752014-08-01 19:04:18 +0100720 default:
Vladimir Marko20f85592015-03-19 10:07:02 +0000721 relative_patcher_.reset(new NoRelativePatcher);
Vladimir Markof4da6752014-08-01 19:04:18 +0100722 break;
723 }
724
Ian Rogersca368cb2013-11-15 15:52:08 -0800725 size_t offset;
726 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700727 TimingLogger::ScopedTiming split("InitOatHeader", timings);
Ian Rogersca368cb2013-11-15 15:52:08 -0800728 offset = InitOatHeader();
729 }
730 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700731 TimingLogger::ScopedTiming split("InitOatDexFiles", timings);
Ian Rogersca368cb2013-11-15 15:52:08 -0800732 offset = InitOatDexFiles(offset);
733 }
734 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700735 TimingLogger::ScopedTiming split("InitDexFiles", timings);
Ian Rogersca368cb2013-11-15 15:52:08 -0800736 offset = InitDexFiles(offset);
737 }
738 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700739 TimingLogger::ScopedTiming split("InitOatClasses", timings);
Ian Rogersca368cb2013-11-15 15:52:08 -0800740 offset = InitOatClasses(offset);
741 }
742 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700743 TimingLogger::ScopedTiming split("InitOatMaps", timings);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100744 offset = InitOatMaps(offset);
745 }
746 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700747 TimingLogger::ScopedTiming split("InitOatCode", timings);
Ian Rogersca368cb2013-11-15 15:52:08 -0800748 offset = InitOatCode(offset);
749 }
750 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700751 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings);
Ian Rogersca368cb2013-11-15 15:52:08 -0800752 offset = InitOatCodeDexFiles(offset);
753 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700754 size_ = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700755
756 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Vladimir Markof4da6752014-08-01 19:04:18 +0100757 CHECK_EQ(compiler->IsImage(), image_writer_ != nullptr);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700758 CHECK_EQ(compiler->IsImage(),
759 key_value_store_->find(OatHeader::kImageLocationKey) == key_value_store_->end());
Alex Lighta59dd802014-07-02 16:28:08 -0700760 CHECK_ALIGNED(image_patch_delta_, kPageSize);
Brian Carlstrome24fa612011-09-29 00:53:55 -0700761}
762
Ian Rogers0571d352011-11-03 19:51:38 -0700763OatWriter::~OatWriter() {
764 delete oat_header_;
765 STLDeleteElements(&oat_dex_files_);
Brian Carlstrom389efb02012-01-11 12:06:26 -0800766 STLDeleteElements(&oat_classes_);
Ian Rogers0571d352011-11-03 19:51:38 -0700767}
768
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100769struct OatWriter::GcMapDataAccess {
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800770 static const SwapVector<uint8_t>* GetData(const CompiledMethod* compiled_method) ALWAYS_INLINE {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100771 return compiled_method->GetGcMap();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100772 }
773
774 static uint32_t GetOffset(OatClass* oat_class, size_t method_offsets_index) ALWAYS_INLINE {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800775 uint32_t offset = oat_class->method_headers_[method_offsets_index].gc_map_offset_;
776 return offset == 0u ? 0u :
777 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100778 }
779
780 static void SetOffset(OatClass* oat_class, size_t method_offsets_index, uint32_t offset)
781 ALWAYS_INLINE {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800782 oat_class->method_headers_[method_offsets_index].gc_map_offset_ =
783 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100784 }
785
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800786 static const char* Name() {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100787 return "GC map";
788 }
789};
790
791struct OatWriter::MappingTableDataAccess {
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800792 static const SwapVector<uint8_t>* GetData(const CompiledMethod* compiled_method) ALWAYS_INLINE {
Nicolas Geoffray376b2bb2014-12-09 14:26:32 +0000793 return compiled_method->GetMappingTable();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100794 }
795
796 static uint32_t GetOffset(OatClass* oat_class, size_t method_offsets_index) ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100797 uint32_t offset = oat_class->method_headers_[method_offsets_index].mapping_table_offset_;
798 return offset == 0u ? 0u :
799 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100800 }
801
802 static void SetOffset(OatClass* oat_class, size_t method_offsets_index, uint32_t offset)
803 ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100804 oat_class->method_headers_[method_offsets_index].mapping_table_offset_ =
805 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100806 }
807
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800808 static const char* Name() {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100809 return "mapping table";
810 }
811};
812
813struct OatWriter::VmapTableDataAccess {
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800814 static const SwapVector<uint8_t>* GetData(const CompiledMethod* compiled_method) ALWAYS_INLINE {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800815 return compiled_method->GetVmapTable();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100816 }
817
818 static uint32_t GetOffset(OatClass* oat_class, size_t method_offsets_index) ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100819 uint32_t offset = oat_class->method_headers_[method_offsets_index].vmap_table_offset_;
820 return offset == 0u ? 0u :
821 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100822 }
823
824 static void SetOffset(OatClass* oat_class, size_t method_offsets_index, uint32_t offset)
825 ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100826 oat_class->method_headers_[method_offsets_index].vmap_table_offset_ =
827 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100828 }
829
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800830 static const char* Name() {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100831 return "vmap table";
832 }
833};
834
835class OatWriter::DexMethodVisitor {
836 public:
837 DexMethodVisitor(OatWriter* writer, size_t offset)
838 : writer_(writer),
839 offset_(offset),
840 dex_file_(nullptr),
841 class_def_index_(DexFile::kDexNoIndex) {
842 }
843
844 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
845 DCHECK(dex_file_ == nullptr);
846 DCHECK_EQ(class_def_index_, DexFile::kDexNoIndex);
847 dex_file_ = dex_file;
848 class_def_index_ = class_def_index;
849 return true;
850 }
851
852 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
853
854 virtual bool EndClass() {
855 if (kIsDebugBuild) {
856 dex_file_ = nullptr;
857 class_def_index_ = DexFile::kDexNoIndex;
858 }
859 return true;
860 }
861
862 size_t GetOffset() const {
863 return offset_;
864 }
865
866 protected:
867 virtual ~DexMethodVisitor() { }
868
869 OatWriter* const writer_;
870
871 // The offset is usually advanced for each visited method by the derived class.
872 size_t offset_;
873
874 // The dex file and class def index are set in StartClass().
875 const DexFile* dex_file_;
876 size_t class_def_index_;
877};
878
879class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
880 public:
881 OatDexMethodVisitor(OatWriter* writer, size_t offset)
882 : DexMethodVisitor(writer, offset),
883 oat_class_index_(0u),
884 method_offsets_index_(0u) {
885 }
886
887 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
888 DexMethodVisitor::StartClass(dex_file, class_def_index);
889 DCHECK_LT(oat_class_index_, writer_->oat_classes_.size());
890 method_offsets_index_ = 0u;
891 return true;
892 }
893
894 bool EndClass() {
895 ++oat_class_index_;
896 return DexMethodVisitor::EndClass();
897 }
898
899 protected:
900 size_t oat_class_index_;
901 size_t method_offsets_index_;
902};
903
904class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
905 public:
906 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
907 : DexMethodVisitor(writer, offset),
908 compiled_methods_(),
909 num_non_null_compiled_methods_(0u) {
910 compiled_methods_.reserve(256u);
911 }
912
913 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
914 DexMethodVisitor::StartClass(dex_file, class_def_index);
915 compiled_methods_.clear();
916 num_non_null_compiled_methods_ = 0u;
917 return true;
918 }
919
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700920 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED, const ClassDataItemIterator& it) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100921 // Fill in the compiled_methods_ array for methods that have a
922 // CompiledMethod. We track the number of non-null entries in
923 // num_non_null_compiled_methods_ since we only want to allocate
924 // OatMethodOffsets for the compiled methods.
925 uint32_t method_idx = it.GetMemberIndex();
926 CompiledMethod* compiled_method =
927 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
928 compiled_methods_.push_back(compiled_method);
929 if (compiled_method != nullptr) {
930 ++num_non_null_compiled_methods_;
931 }
932 return true;
933 }
934
935 bool EndClass() {
936 ClassReference class_ref(dex_file_, class_def_index_);
937 CompiledClass* compiled_class = writer_->compiler_driver_->GetCompiledClass(class_ref);
938 mirror::Class::Status status;
939 if (compiled_class != NULL) {
940 status = compiled_class->GetStatus();
941 } else if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
942 status = mirror::Class::kStatusError;
943 } else {
944 status = mirror::Class::kStatusNotReady;
945 }
946
947 OatClass* oat_class = new OatClass(offset_, compiled_methods_,
948 num_non_null_compiled_methods_, status);
949 writer_->oat_classes_.push_back(oat_class);
Vladimir Markof4da6752014-08-01 19:04:18 +0100950 oat_class->UpdateChecksum(writer_->oat_header_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100951 offset_ += oat_class->SizeOf();
952 return DexMethodVisitor::EndClass();
953 }
954
955 private:
956 std::vector<CompiledMethod*> compiled_methods_;
957 size_t num_non_null_compiled_methods_;
958};
959
960class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
961 public:
962 InitCodeMethodVisitor(OatWriter* writer, size_t offset)
963 : OatDexMethodVisitor(writer, offset) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100964 writer_->absolute_patch_locations_.reserve(
965 writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
966 }
967
968 bool EndClass() {
969 OatDexMethodVisitor::EndClass();
970 if (oat_class_index_ == writer_->oat_classes_.size()) {
Vladimir Marko20f85592015-03-19 10:07:02 +0000971 offset_ = writer_->relative_patcher_->ReserveSpace(offset_, nullptr);
Vladimir Markof4da6752014-08-01 19:04:18 +0100972 }
973 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100974 }
975
976 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
977 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
978 OatClass* oat_class = writer_->oat_classes_[oat_class_index_];
979 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
980
981 if (compiled_method != nullptr) {
982 // Derived from CompiledMethod.
983 uint32_t quick_code_offset = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100984
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800985 const SwapVector<uint8_t>* quick_code = compiled_method->GetQuickCode();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800986 CHECK(quick_code != nullptr);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800987 uint32_t code_size = quick_code->size() * sizeof(uint8_t);
988 CHECK_NE(code_size, 0U);
989 uint32_t thumb_offset = compiled_method->CodeDelta();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800990
991 // Deduplicate code arrays.
Vladimir Markoc74658b2015-03-31 10:26:41 +0100992 bool deduped = false;
Elliott Hughes956af0f2014-12-11 14:34:28 -0800993 auto lb = dedupe_map_.lower_bound(compiled_method);
994 if (lb != dedupe_map_.end() && !dedupe_map_.key_comp()(compiled_method, lb->first)) {
995 quick_code_offset = lb->second;
996 deduped = true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100997 } else {
Vladimir Markoc74658b2015-03-31 10:26:41 +0100998 offset_ = writer_->relative_patcher_->ReserveSpace(offset_, compiled_method);
999 offset_ = compiled_method->AlignCode(offset_);
1000 DCHECK_ALIGNED_PARAM(offset_,
1001 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1002 quick_code_offset = offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
Elliott Hughes956af0f2014-12-11 14:34:28 -08001003 dedupe_map_.PutBefore(lb, compiled_method, quick_code_offset);
1004 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001005
Elliott Hughes956af0f2014-12-11 14:34:28 -08001006 MethodReference method_ref(dex_file_, it.GetMemberIndex());
1007 auto method_lb = writer_->method_offset_map_.lower_bound(method_ref);
1008 if (method_lb != writer_->method_offset_map_.end() &&
1009 !writer_->method_offset_map_.key_comp()(method_ref, method_lb->first)) {
1010 // TODO: Should this be a hard failure?
1011 LOG(WARNING) << "Multiple definitions of "
1012 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file)
1013 << ((method_lb->second != quick_code_offset) ? "; OFFSET MISMATCH" : "");
1014 } else {
1015 writer_->method_offset_map_.PutBefore(method_lb, method_ref, quick_code_offset);
1016 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001017
Elliott Hughes956af0f2014-12-11 14:34:28 -08001018 // Update quick method header.
1019 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
1020 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
1021 uint32_t mapping_table_offset = method_header->mapping_table_offset_;
1022 uint32_t vmap_table_offset = method_header->vmap_table_offset_;
1023 uint32_t gc_map_offset = method_header->gc_map_offset_;
1024 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
1025 // to 0-offset and we need to adjust it by code_offset.
1026 uint32_t code_offset = quick_code_offset - thumb_offset;
1027 if (mapping_table_offset != 0u) {
1028 mapping_table_offset += code_offset;
1029 DCHECK_LT(mapping_table_offset, code_offset);
1030 }
1031 if (vmap_table_offset != 0u) {
1032 vmap_table_offset += code_offset;
1033 DCHECK_LT(vmap_table_offset, code_offset);
1034 }
1035 if (gc_map_offset != 0u) {
1036 gc_map_offset += code_offset;
1037 DCHECK_LT(gc_map_offset, code_offset);
1038 }
1039 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
1040 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
1041 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
1042 *method_header = OatQuickMethodHeader(mapping_table_offset, vmap_table_offset,
1043 gc_map_offset, frame_size_in_bytes, core_spill_mask,
1044 fp_spill_mask, code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +01001045
Elliott Hughes956af0f2014-12-11 14:34:28 -08001046 if (!deduped) {
1047 // Update offsets. (Checksum is updated when writing.)
1048 offset_ += sizeof(*method_header); // Method header is prepended before code.
1049 offset_ += code_size;
1050 // Record absolute patch locations.
1051 if (!compiled_method->GetPatches().empty()) {
1052 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
1053 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko20f85592015-03-19 10:07:02 +00001054 if (!patch.IsPcRelative()) {
Elliott Hughes956af0f2014-12-11 14:34:28 -08001055 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +01001056 }
1057 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001058 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001059 }
Alex Light78382fa2014-06-06 15:45:32 -07001060
Elliott Hughes956af0f2014-12-11 14:34:28 -08001061 if (writer_->compiler_driver_->GetCompilerOptions().GetIncludeDebugSymbols()) {
1062 // Record debug information for this function if we are doing that.
Alex Light78382fa2014-06-06 15:45:32 -07001063
Elliott Hughes956af0f2014-12-11 14:34:28 -08001064 std::string name = PrettyMethod(it.GetMemberIndex(), *dex_file_, true);
1065 if (deduped) {
1066 // TODO We should place the DEDUPED tag on the first instance of a deduplicated symbol
1067 // so that it will show up in a debuggerd crash report.
1068 name += " [ DEDUPED ]";
Alex Light78382fa2014-06-06 15:45:32 -07001069 }
Elliott Hughes956af0f2014-12-11 14:34:28 -08001070
1071 const uint32_t quick_code_start = quick_code_offset -
1072 writer_->oat_header_->GetExecutableOffset();
1073 const DexFile::CodeItem *code_item = it.GetMethodCodeItem();
1074 writer_->method_info_.push_back(DebugInfo(name,
1075 dex_file_->GetSourceFile(dex_file_->GetClassDef(class_def_index_)),
1076 quick_code_start, quick_code_start + code_size,
1077 code_item == nullptr ? nullptr : dex_file_->GetDebugInfoStream(code_item),
1078 compiled_method));
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001079 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001080
1081 if (kIsDebugBuild) {
1082 // We expect GC maps except when the class hasn't been verified or the method is native.
1083 const CompilerDriver* compiler_driver = writer_->compiler_driver_;
1084 ClassReference class_ref(dex_file_, class_def_index_);
1085 CompiledClass* compiled_class = compiler_driver->GetCompiledClass(class_ref);
1086 mirror::Class::Status status;
1087 if (compiled_class != NULL) {
1088 status = compiled_class->GetStatus();
1089 } else if (compiler_driver->GetVerificationResults()->IsClassRejected(class_ref)) {
1090 status = mirror::Class::kStatusError;
1091 } else {
1092 status = mirror::Class::kStatusNotReady;
1093 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001094 const SwapVector<uint8_t>* gc_map = compiled_method->GetGcMap();
Nicolas Geoffray39468442014-09-02 15:17:15 +01001095 if (gc_map != nullptr) {
1096 size_t gc_map_size = gc_map->size() * sizeof(gc_map[0]);
Andreas Gampe51829322014-08-25 15:05:04 -07001097 bool is_native = it.MemberIsNative();
Nicolas Geoffray39468442014-09-02 15:17:15 +01001098 CHECK(gc_map_size != 0 || is_native || status < mirror::Class::kStatusVerified)
1099 << gc_map << " " << gc_map_size << " " << (is_native ? "true" : "false") << " "
1100 << (status < mirror::Class::kStatusVerified) << " " << status << " "
1101 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1102 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001103 }
1104
1105 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1106 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
1107 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001108 ++method_offsets_index_;
1109 }
1110
1111 return true;
1112 }
1113
1114 private:
Vladimir Marko20f85592015-03-19 10:07:02 +00001115 struct CodeOffsetsKeyComparator {
1116 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
1117 if (lhs->GetQuickCode() != rhs->GetQuickCode()) {
1118 return lhs->GetQuickCode() < rhs->GetQuickCode();
1119 }
1120 // If the code is the same, all other fields are likely to be the same as well.
1121 if (UNLIKELY(lhs->GetMappingTable() != rhs->GetMappingTable())) {
1122 return lhs->GetMappingTable() < rhs->GetMappingTable();
1123 }
1124 if (UNLIKELY(lhs->GetVmapTable() != rhs->GetVmapTable())) {
1125 return lhs->GetVmapTable() < rhs->GetVmapTable();
1126 }
1127 if (UNLIKELY(lhs->GetGcMap() != rhs->GetGcMap())) {
1128 return lhs->GetGcMap() < rhs->GetGcMap();
1129 }
1130 const auto& lhs_patches = lhs->GetPatches();
1131 const auto& rhs_patches = rhs->GetPatches();
1132 if (UNLIKELY(lhs_patches.size() != rhs_patches.size())) {
1133 return lhs_patches.size() < rhs_patches.size();
1134 }
1135 auto rit = rhs_patches.begin();
1136 for (const LinkerPatch& lpatch : lhs_patches) {
1137 if (UNLIKELY(!(lpatch == *rit))) {
1138 return lpatch < *rit;
1139 }
1140 ++rit;
1141 }
1142 return false;
1143 }
1144 };
1145
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001146 // Deduplication is already done on a pointer basis by the compiler driver,
1147 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +01001148 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001149};
1150
1151template <typename DataAccess>
1152class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
1153 public:
1154 InitMapMethodVisitor(OatWriter* writer, size_t offset)
1155 : OatDexMethodVisitor(writer, offset) {
1156 }
1157
Ian Rogers6a3c1fc2014-10-31 00:33:20 -07001158 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001159 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1160 OatClass* oat_class = writer_->oat_classes_[oat_class_index_];
1161 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1162
1163 if (compiled_method != nullptr) {
1164 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1165 DCHECK_EQ(DataAccess::GetOffset(oat_class, method_offsets_index_), 0u);
1166
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001167 const SwapVector<uint8_t>* map = DataAccess::GetData(compiled_method);
Nicolas Geoffray39468442014-09-02 15:17:15 +01001168 uint32_t map_size = map == nullptr ? 0 : map->size() * sizeof((*map)[0]);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001169 if (map_size != 0u) {
Vladimir Markobd72fc12014-07-09 16:06:40 +01001170 auto lb = dedupe_map_.lower_bound(map);
1171 if (lb != dedupe_map_.end() && !dedupe_map_.key_comp()(map, lb->first)) {
1172 DataAccess::SetOffset(oat_class, method_offsets_index_, lb->second);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001173 } else {
1174 DataAccess::SetOffset(oat_class, method_offsets_index_, offset_);
Vladimir Markobd72fc12014-07-09 16:06:40 +01001175 dedupe_map_.PutBefore(lb, map, offset_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001176 offset_ += map_size;
1177 writer_->oat_header_->UpdateChecksum(&(*map)[0], map_size);
1178 }
1179 }
1180 ++method_offsets_index_;
1181 }
1182
1183 return true;
1184 }
1185
1186 private:
1187 // Deduplication is already done on a pointer basis by the compiler driver,
1188 // so we can simply compare the pointers to find out if things are duplicated.
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001189 SafeMap<const SwapVector<uint8_t>*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001190};
1191
1192class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
1193 public:
1194 InitImageMethodVisitor(OatWriter* writer, size_t offset)
Jeff Haoc7d11882015-02-03 15:08:39 -08001195 : OatDexMethodVisitor(writer, offset),
1196 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001197 }
1198
1199 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
1200 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1201 OatClass* oat_class = writer_->oat_classes_[oat_class_index_];
1202 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1203
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001204 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001205 if (compiled_method != nullptr) {
1206 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1207 offsets = oat_class->method_offsets_[method_offsets_index_];
1208 ++method_offsets_index_;
1209 }
1210
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001211 ClassLinker* linker = Runtime::Current()->GetClassLinker();
1212 InvokeType invoke_type = it.GetMethodInvokeType(dex_file_->GetClassDef(class_def_index_));
1213 // Unchecked as we hold mutator_lock_ on entry.
1214 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001215 StackHandleScope<1> hs(soa.Self());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001216 Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(*dex_file_)));
Vladimir Marko7624d252014-05-02 14:40:15 +01001217 mirror::ArtMethod* method = linker->ResolveMethod(*dex_file_, it.GetMemberIndex(), dex_cache,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07001218 NullHandle<mirror::ClassLoader>(),
1219 NullHandle<mirror::ArtMethod>(),
1220 invoke_type);
Andreas Gamped9efea62014-07-21 22:56:08 -07001221 if (method == nullptr) {
1222 LOG(ERROR) << "Unexpected failure to resolve a method: "
1223 << PrettyMethod(it.GetMemberIndex(), *dex_file_, true);
1224 soa.Self()->AssertPendingException();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001225 mirror::Throwable* exc = soa.Self()->GetException();
Andreas Gamped9efea62014-07-21 22:56:08 -07001226 std::string dump = exc->Dump();
1227 LOG(FATAL) << dump;
1228 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001229 method->SetEntryPointFromQuickCompiledCodePtrSize(reinterpret_cast<void*>(offsets.code_offset_),
1230 pointer_size_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001231
1232 return true;
1233 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001234
1235 protected:
1236 const size_t pointer_size_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001237};
1238
1239class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
1240 public:
1241 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +01001242 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001243 : OatDexMethodVisitor(writer, relative_offset),
1244 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +01001245 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001246 soa_(Thread::Current()),
1247 no_thread_suspension_(soa_.Self(), "OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +01001248 class_linker_(Runtime::Current()->GetClassLinker()),
1249 dex_cache_(nullptr) {
1250 if (writer_->image_writer_ != nullptr) {
1251 // If we're creating the image, the address space must be ready so that we can apply patches.
1252 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
1253 patched_code_.reserve(16 * KB);
1254 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001255 }
1256
Vladimir Markof4da6752014-08-01 19:04:18 +01001257 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001258 }
1259
1260 bool StartClass(const DexFile* dex_file, size_t class_def_index)
1261 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1262 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1263 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
1264 dex_cache_ = class_linker_->FindDexCache(*dex_file);
1265 }
1266 return true;
1267 }
1268
1269 bool EndClass() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1270 bool result = OatDexMethodVisitor::EndClass();
1271 if (oat_class_index_ == writer_->oat_classes_.size()) {
1272 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
Vladimir Marko20f85592015-03-19 10:07:02 +00001273 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001274 if (UNLIKELY(offset_ == 0u)) {
1275 PLOG(ERROR) << "Failed to write final relative call thunks";
1276 result = false;
1277 }
1278 }
1279 return result;
1280 }
1281
1282 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
1283 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001284 OatClass* oat_class = writer_->oat_classes_[oat_class_index_];
1285 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1286
1287 if (compiled_method != NULL) { // ie. not an abstract method
1288 size_t file_offset = file_offset_;
1289 OutputStream* out = out_;
1290
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001291 const SwapVector<uint8_t>* quick_code = compiled_method->GetQuickCode();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001292 if (quick_code != nullptr) {
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001293 // Need a wrapper if we create a copy for patching.
1294 ArrayRef<const uint8_t> wrapped(*quick_code);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001295 uint32_t code_size = quick_code->size() * sizeof(uint8_t);
1296 CHECK_NE(code_size, 0U);
1297
1298 // Deduplicate code arrays.
1299 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001300 if (method_offsets.code_offset_ >= offset_) {
Vladimir Markoc74658b2015-03-31 10:26:41 +01001301 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
1302 if (offset_ == 0u) {
1303 ReportWriteFailure("relative call thunk", it);
1304 return false;
1305 }
1306 uint32_t aligned_offset = compiled_method->AlignCode(offset_);
1307 uint32_t aligned_code_delta = aligned_offset - offset_;
1308 if (aligned_code_delta != 0) {
1309 if (!writer_->WriteCodeAlignment(out, aligned_code_delta)) {
1310 ReportWriteFailure("code alignment padding", it);
1311 return false;
1312 }
1313 offset_ += aligned_code_delta;
1314 DCHECK_OFFSET_();
1315 }
1316 DCHECK_ALIGNED_PARAM(offset_,
1317 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1318 DCHECK_EQ(method_offsets.code_offset_,
1319 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
1320 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001321 const OatQuickMethodHeader& method_header =
1322 oat_class->method_headers_[method_offsets_index_];
1323 writer_->oat_header_->UpdateChecksum(&method_header, sizeof(method_header));
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001324 if (!out->WriteFully(&method_header, sizeof(method_header))) {
1325 ReportWriteFailure("method header", it);
1326 return false;
1327 }
1328 writer_->size_method_header_ += sizeof(method_header);
1329 offset_ += sizeof(method_header);
1330 DCHECK_OFFSET_();
Vladimir Markof4da6752014-08-01 19:04:18 +01001331
1332 if (!compiled_method->GetPatches().empty()) {
Vladimir Marko20f85592015-03-19 10:07:02 +00001333 patched_code_.assign(quick_code->begin(), quick_code->end());
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001334 wrapped = ArrayRef<const uint8_t>(patched_code_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001335 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
1336 if (patch.Type() == kLinkerPatchCallRelative) {
1337 // NOTE: Relative calls across oat files are not supported.
1338 uint32_t target_offset = GetTargetOffset(patch);
1339 uint32_t literal_offset = patch.LiteralOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001340 writer_->relative_patcher_->PatchCall(&patched_code_, literal_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +01001341 offset_ + literal_offset, target_offset);
Vladimir Marko20f85592015-03-19 10:07:02 +00001342 } else if (patch.Type() == kLinkerPatchDexCacheArray) {
1343 uint32_t target_offset = GetDexCacheOffset(patch);
1344 uint32_t literal_offset = patch.LiteralOffset();
1345 writer_->relative_patcher_->PatchDexCacheReference(&patched_code_, patch,
1346 offset_ + literal_offset,
1347 target_offset);
Vladimir Markof4da6752014-08-01 19:04:18 +01001348 } else if (patch.Type() == kLinkerPatchCall) {
1349 uint32_t target_offset = GetTargetOffset(patch);
1350 PatchCodeAddress(&patched_code_, patch.LiteralOffset(), target_offset);
1351 } else if (patch.Type() == kLinkerPatchMethod) {
1352 mirror::ArtMethod* method = GetTargetMethod(patch);
1353 PatchObjectAddress(&patched_code_, patch.LiteralOffset(), method);
1354 } else if (patch.Type() == kLinkerPatchType) {
1355 mirror::Class* type = GetTargetType(patch);
1356 PatchObjectAddress(&patched_code_, patch.LiteralOffset(), type);
1357 }
1358 }
1359 }
1360
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001361 writer_->oat_header_->UpdateChecksum(wrapped.data(), code_size);
1362 if (!out->WriteFully(wrapped.data(), code_size)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001363 ReportWriteFailure("method code", it);
1364 return false;
1365 }
1366 writer_->size_code_ += code_size;
1367 offset_ += code_size;
1368 }
1369 DCHECK_OFFSET_();
1370 }
1371 ++method_offsets_index_;
1372 }
1373
1374 return true;
1375 }
1376
1377 private:
1378 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001379 const size_t file_offset_;
1380 const ScopedObjectAccess soa_;
1381 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001382 ClassLinker* const class_linker_;
1383 mirror::DexCache* dex_cache_;
1384 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001385
1386 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1387 PLOG(ERROR) << "Failed to write " << what << " for "
1388 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1389 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001390
1391 mirror::ArtMethod* GetTargetMethod(const LinkerPatch& patch)
1392 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1393 MethodReference ref = patch.TargetMethod();
1394 mirror::DexCache* dex_cache =
1395 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(*ref.dex_file);
1396 mirror::ArtMethod* method = dex_cache->GetResolvedMethod(ref.dex_method_index);
1397 CHECK(method != nullptr);
1398 return method;
1399 }
1400
1401 uint32_t GetTargetOffset(const LinkerPatch& patch) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1402 auto target_it = writer_->method_offset_map_.find(patch.TargetMethod());
1403 uint32_t target_offset =
1404 (target_it != writer_->method_offset_map_.end()) ? target_it->second : 0u;
1405 // If there's no compiled code, point to the correct trampoline.
1406 if (UNLIKELY(target_offset == 0)) {
1407 mirror::ArtMethod* target = GetTargetMethod(patch);
1408 DCHECK(target != nullptr);
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001409 size_t size = GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet());
1410 const void* oat_code_offset = target->GetEntryPointFromQuickCompiledCodePtrSize(size);
1411 if (oat_code_offset != 0) {
1412 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1413 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1414 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1415 target_offset = PointerToLowMemUInt32(oat_code_offset);
1416 } else {
1417 target_offset = target->IsNative()
1418 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1419 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1420 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001421 }
1422 return target_offset;
1423 }
1424
1425 mirror::Class* GetTargetType(const LinkerPatch& patch)
1426 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1427 mirror::DexCache* dex_cache = (dex_file_ == patch.TargetTypeDexFile())
1428 ? dex_cache_ : class_linker_->FindDexCache(*patch.TargetTypeDexFile());
1429 mirror::Class* type = dex_cache->GetResolvedType(patch.TargetTypeIndex());
1430 CHECK(type != nullptr);
1431 return type;
1432 }
1433
Vladimir Marko20f85592015-03-19 10:07:02 +00001434 uint32_t GetDexCacheOffset(const LinkerPatch& patch) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1435 if (writer_->image_writer_ != nullptr) {
1436 auto* element = writer_->image_writer_->GetDexCacheArrayElementImageAddress(
1437 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
1438 const uint8_t* oat_data = writer_->image_writer_->GetOatFileBegin() + file_offset_;
1439 return reinterpret_cast<const uint8_t*>(element) - oat_data;
1440 } else {
1441 LOG(FATAL) << "Unimplemented.";
1442 UNREACHABLE();
1443 }
1444 }
1445
Vladimir Markof4da6752014-08-01 19:04:18 +01001446 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
1447 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1448 // NOTE: Direct method pointers across oat files don't use linker patches. However, direct
1449 // type pointers across oat files do. (TODO: Investigate why.)
1450 if (writer_->image_writer_ != nullptr) {
1451 object = writer_->image_writer_->GetImageAddress(object);
1452 }
1453 uint32_t address = PointerToLowMemUInt32(object);
1454 DCHECK_LE(offset + 4, code->size());
1455 uint8_t* data = &(*code)[offset];
1456 data[0] = address & 0xffu;
1457 data[1] = (address >> 8) & 0xffu;
1458 data[2] = (address >> 16) & 0xffu;
1459 data[3] = (address >> 24) & 0xffu;
1460 }
1461
1462 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
1463 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001464 uint32_t address = writer_->image_writer_ == nullptr ? target_offset :
1465 PointerToLowMemUInt32(writer_->image_writer_->GetOatFileBegin() +
1466 writer_->oat_data_offset_ + target_offset);
Vladimir Markof4da6752014-08-01 19:04:18 +01001467 DCHECK_LE(offset + 4, code->size());
1468 uint8_t* data = &(*code)[offset];
1469 data[0] = address & 0xffu;
1470 data[1] = (address >> 8) & 0xffu;
1471 data[2] = (address >> 16) & 0xffu;
1472 data[3] = (address >> 24) & 0xffu;
1473 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001474};
1475
1476template <typename DataAccess>
1477class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1478 public:
1479 WriteMapMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001480 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001481 : OatDexMethodVisitor(writer, relative_offset),
1482 out_(out),
1483 file_offset_(file_offset) {
1484 }
1485
1486 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
1487 OatClass* oat_class = writer_->oat_classes_[oat_class_index_];
1488 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1489
1490 if (compiled_method != NULL) { // ie. not an abstract method
1491 size_t file_offset = file_offset_;
1492 OutputStream* out = out_;
1493
1494 uint32_t map_offset = DataAccess::GetOffset(oat_class, method_offsets_index_);
1495 ++method_offsets_index_;
1496
1497 // Write deduplicated map.
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001498 const SwapVector<uint8_t>* map = DataAccess::GetData(compiled_method);
Nicolas Geoffray39468442014-09-02 15:17:15 +01001499 size_t map_size = map == nullptr ? 0 : map->size() * sizeof((*map)[0]);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001500 DCHECK((map_size == 0u && map_offset == 0u) ||
1501 (map_size != 0u && map_offset != 0u && map_offset <= offset_))
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001502 << map_size << " " << map_offset << " " << offset_ << " "
1503 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " for " << DataAccess::Name();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001504 if (map_size != 0u && map_offset == offset_) {
1505 if (UNLIKELY(!out->WriteFully(&(*map)[0], map_size))) {
1506 ReportWriteFailure(it);
1507 return false;
1508 }
1509 offset_ += map_size;
1510 }
1511 DCHECK_OFFSET_();
1512 }
1513
1514 return true;
1515 }
1516
1517 private:
1518 OutputStream* const out_;
1519 size_t const file_offset_;
1520
1521 void ReportWriteFailure(const ClassDataItemIterator& it) {
1522 PLOG(ERROR) << "Failed to write " << DataAccess::Name() << " for "
1523 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1524 }
1525};
1526
1527// Visit all methods from all classes in all dex files with the specified visitor.
1528bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1529 for (const DexFile* dex_file : *dex_files_) {
1530 const size_t class_def_count = dex_file->NumClassDefs();
1531 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1532 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1533 return false;
1534 }
1535 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -07001536 const uint8_t* class_data = dex_file->GetClassData(class_def);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001537 if (class_data != NULL) { // ie not an empty class, such as a marker interface
1538 ClassDataItemIterator it(*dex_file, class_data);
1539 while (it.HasNextStaticField()) {
1540 it.Next();
1541 }
1542 while (it.HasNextInstanceField()) {
1543 it.Next();
1544 }
1545 size_t class_def_method_index = 0u;
1546 while (it.HasNextDirectMethod()) {
1547 if (!visitor->VisitMethod(class_def_method_index, it)) {
1548 return false;
1549 }
1550 ++class_def_method_index;
1551 it.Next();
1552 }
1553 while (it.HasNextVirtualMethod()) {
1554 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1555 return false;
1556 }
1557 ++class_def_method_index;
1558 it.Next();
1559 }
1560 }
1561 if (UNLIKELY(!visitor->EndClass())) {
1562 return false;
1563 }
1564 }
1565 }
1566 return true;
1567}
1568
Brian Carlstrom81f3ca12012-03-17 00:27:35 -07001569size_t OatWriter::InitOatHeader() {
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001570 oat_header_ = OatHeader::Create(compiler_driver_->GetInstructionSet(),
1571 compiler_driver_->GetInstructionSetFeatures(),
1572 dex_files_,
1573 image_file_location_oat_checksum_,
1574 image_file_location_oat_begin_,
1575 key_value_store_);
1576
1577 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001578}
1579
1580size_t OatWriter::InitOatDexFiles(size_t offset) {
1581 // create the OatDexFiles
1582 for (size_t i = 0; i != dex_files_->size(); ++i) {
1583 const DexFile* dex_file = (*dex_files_)[i];
1584 CHECK(dex_file != NULL);
Brian Carlstrom265091e2013-01-30 14:08:26 -08001585 OatDexFile* oat_dex_file = new OatDexFile(offset, *dex_file);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001586 oat_dex_files_.push_back(oat_dex_file);
1587 offset += oat_dex_file->SizeOf();
1588 }
1589 return offset;
1590}
1591
Brian Carlstrom89521892011-12-07 22:05:07 -08001592size_t OatWriter::InitDexFiles(size_t offset) {
1593 // calculate the offsets within OatDexFiles to the DexFiles
1594 for (size_t i = 0; i != dex_files_->size(); ++i) {
1595 // dex files are required to be 4 byte aligned
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001596 size_t original_offset = offset;
Brian Carlstrom89521892011-12-07 22:05:07 -08001597 offset = RoundUp(offset, 4);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001598 size_dex_file_alignment_ += offset - original_offset;
Brian Carlstrom89521892011-12-07 22:05:07 -08001599
1600 // set offset in OatDexFile to DexFile
1601 oat_dex_files_[i]->dex_file_offset_ = offset;
1602
1603 const DexFile* dex_file = (*dex_files_)[i];
1604 offset += dex_file->GetHeader().file_size_;
1605 }
1606 return offset;
1607}
1608
Brian Carlstrom389efb02012-01-11 12:06:26 -08001609size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001610 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001611 InitOatClassesMethodVisitor visitor(this, offset);
1612 bool success = VisitDexMethods(&visitor);
1613 CHECK(success);
1614 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001615
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001616 // Update oat_dex_files_.
1617 auto oat_class_it = oat_classes_.begin();
1618 for (OatDexFile* oat_dex_file : oat_dex_files_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001619 for (uint32_t& method_offset : oat_dex_file->methods_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001620 DCHECK(oat_class_it != oat_classes_.end());
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001621 method_offset = (*oat_class_it)->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001622 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001623 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001624 oat_dex_file->UpdateChecksum(oat_header_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001625 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001626 CHECK(oat_class_it == oat_classes_.end());
1627
1628 return offset;
1629}
1630
1631size_t OatWriter::InitOatMaps(size_t offset) {
1632 #define VISIT(VisitorType) \
1633 do { \
1634 VisitorType visitor(this, offset); \
1635 bool success = VisitDexMethods(&visitor); \
1636 DCHECK(success); \
1637 offset = visitor.GetOffset(); \
1638 } while (false)
1639
1640 VISIT(InitMapMethodVisitor<GcMapDataAccess>);
1641 VISIT(InitMapMethodVisitor<MappingTableDataAccess>);
1642 VISIT(InitMapMethodVisitor<VmapTableDataAccess>);
1643
1644 #undef VISIT
1645
Brian Carlstrome24fa612011-09-29 00:53:55 -07001646 return offset;
1647}
1648
1649size_t OatWriter::InitOatCode(size_t offset) {
1650 // calculate the offsets within OatHeader to executable code
1651 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001652 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001653 // required to be on a new page boundary
1654 offset = RoundUp(offset, kPageSize);
1655 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001656 size_executable_offset_alignment_ = offset - old_offset;
1657 if (compiler_driver_->IsImage()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001658 CHECK_EQ(image_patch_delta_, 0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001659 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001660
Ian Rogers848871b2013-08-05 10:56:33 -07001661 #define DO_TRAMPOLINE(field, fn_name) \
1662 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001663 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1664 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Ian Rogers848871b2013-08-05 10:56:33 -07001665 field.reset(compiler_driver_->Create ## fn_name()); \
1666 offset += field->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001667
Ian Rogers848871b2013-08-05 10:56:33 -07001668 DO_TRAMPOLINE(interpreter_to_interpreter_bridge_, InterpreterToInterpreterBridge);
1669 DO_TRAMPOLINE(interpreter_to_compiled_code_bridge_, InterpreterToCompiledCodeBridge);
1670 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001671 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001672 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001673 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1674 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001675
Ian Rogers848871b2013-08-05 10:56:33 -07001676 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001677 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001678 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1679 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1680 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001681 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001682 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001683 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001684 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Alex Lighta59dd802014-07-02 16:28:08 -07001685 oat_header_->SetImagePatchDelta(image_patch_delta_);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001686 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001687 return offset;
1688}
1689
1690size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001691 #define VISIT(VisitorType) \
1692 do { \
1693 VisitorType visitor(this, offset); \
1694 bool success = VisitDexMethods(&visitor); \
1695 DCHECK(success); \
1696 offset = visitor.GetOffset(); \
1697 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001698
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001699 VISIT(InitCodeMethodVisitor);
Ian Rogers1212a022013-03-04 10:48:41 -08001700 if (compiler_driver_->IsImage()) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001701 VISIT(InitImageMethodVisitor);
Ian Rogers0571d352011-11-03 19:51:38 -07001702 }
Logan Chien8b977d32012-02-21 19:14:55 +08001703
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001704 #undef VISIT
1705
Brian Carlstrome24fa612011-09-29 00:53:55 -07001706 return offset;
1707}
1708
Ian Rogers3d504072014-03-01 09:16:49 -08001709bool OatWriter::Write(OutputStream* out) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001710 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
1711 if (raw_file_offset == (off_t) -1) {
1712 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
1713 return false;
1714 }
1715 const size_t file_offset = static_cast<size_t>(raw_file_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001716
Vladimir Markof4da6752014-08-01 19:04:18 +01001717 // Reserve space for header. It will be written last - after updating the checksum.
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001718 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Markof4da6752014-08-01 19:04:18 +01001719 if (out->Seek(header_size, kSeekCurrent) == (off_t) -1) {
1720 PLOG(ERROR) << "Failed to reserve space for oat header in " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001721 return false;
1722 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001723 size_oat_header_ += sizeof(OatHeader);
1724 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Brian Carlstrom81f3ca12012-03-17 00:27:35 -07001725
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001726 if (!WriteTables(out, file_offset)) {
Ian Rogers3d504072014-03-01 09:16:49 -08001727 LOG(ERROR) << "Failed to write oat tables to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001728 return false;
1729 }
1730
Vladimir Markof4da6752014-08-01 19:04:18 +01001731 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
1732 if (tables_end_offset == (off_t) -1) {
1733 LOG(ERROR) << "Failed to seek to oat code position in " << out->GetLocation();
1734 return false;
1735 }
1736 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001737 relative_offset = WriteMaps(out, file_offset, relative_offset);
1738 if (relative_offset == 0) {
1739 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1740 return false;
1741 }
1742
1743 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001744 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001745 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001746 return false;
1747 }
1748
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001749 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1750 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001751 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001752 return false;
1753 }
1754
Vladimir Markof4da6752014-08-01 19:04:18 +01001755 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
1756 if (oat_end_file_offset == (off_t) -1) {
1757 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1758 return false;
1759 }
1760
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001761 if (kIsDebugBuild) {
1762 uint32_t size_total = 0;
1763 #define DO_STAT(x) \
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001764 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << x << "B)"; \
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001765 size_total += x;
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001766
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001767 DO_STAT(size_dex_file_alignment_);
1768 DO_STAT(size_executable_offset_alignment_);
1769 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001770 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001771 DO_STAT(size_dex_file_);
Ian Rogers848871b2013-08-05 10:56:33 -07001772 DO_STAT(size_interpreter_to_interpreter_bridge_);
1773 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1774 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001775 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001776 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001777 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001778 DO_STAT(size_quick_to_interpreter_bridge_);
1779 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001780 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001781 DO_STAT(size_code_);
1782 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001783 DO_STAT(size_relative_call_thunks_);
Vladimir Markoc74658b2015-03-31 10:26:41 +01001784 DO_STAT(size_misc_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001785 DO_STAT(size_mapping_table_);
1786 DO_STAT(size_vmap_table_);
1787 DO_STAT(size_gc_map_);
1788 DO_STAT(size_oat_dex_file_location_size_);
1789 DO_STAT(size_oat_dex_file_location_data_);
1790 DO_STAT(size_oat_dex_file_location_checksum_);
1791 DO_STAT(size_oat_dex_file_offset_);
1792 DO_STAT(size_oat_dex_file_methods_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001793 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001794 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001795 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001796 DO_STAT(size_oat_class_method_offsets_);
1797 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001798
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001799 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)"; \
Vladimir Markof4da6752014-08-01 19:04:18 +01001800 CHECK_EQ(file_offset + size_total, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001801 CHECK_EQ(size_, size_total);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001802 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001803
Vladimir Markof4da6752014-08-01 19:04:18 +01001804 CHECK_EQ(file_offset + size_, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001805 CHECK_EQ(size_, relative_offset);
1806
Vladimir Markof4da6752014-08-01 19:04:18 +01001807 // Write the header now that the checksum is final.
1808 if (out->Seek(file_offset, kSeekSet) == (off_t) -1) {
1809 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1810 return false;
1811 }
1812 DCHECK_EQ(raw_file_offset, out->Seek(0, kSeekCurrent));
1813 if (!out->WriteFully(oat_header_, header_size)) {
1814 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1815 return false;
1816 }
1817 if (out->Seek(oat_end_file_offset, kSeekSet) == (off_t) -1) {
1818 PLOG(ERROR) << "Failed to seek to end after writing oat header to " << out->GetLocation();
1819 return false;
1820 }
1821 DCHECK_EQ(oat_end_file_offset, out->Seek(0, kSeekCurrent));
1822
Brian Carlstrome24fa612011-09-29 00:53:55 -07001823 return true;
1824}
1825
Ian Rogers3d504072014-03-01 09:16:49 -08001826bool OatWriter::WriteTables(OutputStream* out, const size_t file_offset) {
Brian Carlstrome24fa612011-09-29 00:53:55 -07001827 for (size_t i = 0; i != oat_dex_files_.size(); ++i) {
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001828 if (!oat_dex_files_[i]->Write(this, out, file_offset)) {
Ian Rogers3d504072014-03-01 09:16:49 -08001829 PLOG(ERROR) << "Failed to write oat dex information to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001830 return false;
1831 }
1832 }
Brian Carlstrom89521892011-12-07 22:05:07 -08001833 for (size_t i = 0; i != oat_dex_files_.size(); ++i) {
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001834 uint32_t expected_offset = file_offset + oat_dex_files_[i]->dex_file_offset_;
Ian Rogers3d504072014-03-01 09:16:49 -08001835 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
Brian Carlstrom89521892011-12-07 22:05:07 -08001836 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
1837 const DexFile* dex_file = (*dex_files_)[i];
1838 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
1839 << " Expected: " << expected_offset << " File: " << dex_file->GetLocation();
1840 return false;
1841 }
1842 const DexFile* dex_file = (*dex_files_)[i];
Ian Rogers3d504072014-03-01 09:16:49 -08001843 if (!out->WriteFully(&dex_file->GetHeader(), dex_file->GetHeader().file_size_)) {
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001844 PLOG(ERROR) << "Failed to write dex file " << dex_file->GetLocation()
Ian Rogers3d504072014-03-01 09:16:49 -08001845 << " to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08001846 return false;
1847 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001848 size_dex_file_ += dex_file->GetHeader().file_size_;
Brian Carlstrom89521892011-12-07 22:05:07 -08001849 }
Brian Carlstrom389efb02012-01-11 12:06:26 -08001850 for (size_t i = 0; i != oat_classes_.size(); ++i) {
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001851 if (!oat_classes_[i]->Write(this, out, file_offset)) {
Ian Rogers3d504072014-03-01 09:16:49 -08001852 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001853 return false;
1854 }
1855 }
1856 return true;
1857}
1858
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001859size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
1860 #define VISIT(VisitorType) \
1861 do { \
1862 VisitorType visitor(this, out, file_offset, relative_offset); \
1863 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1864 return 0; \
1865 } \
1866 relative_offset = visitor.GetOffset(); \
1867 } while (false)
1868
1869 size_t gc_maps_offset = relative_offset;
1870 VISIT(WriteMapMethodVisitor<GcMapDataAccess>);
1871 size_gc_map_ = relative_offset - gc_maps_offset;
1872
1873 size_t mapping_tables_offset = relative_offset;
1874 VISIT(WriteMapMethodVisitor<MappingTableDataAccess>);
1875 size_mapping_table_ = relative_offset - mapping_tables_offset;
1876
1877 size_t vmap_tables_offset = relative_offset;
1878 VISIT(WriteMapMethodVisitor<VmapTableDataAccess>);
1879 size_vmap_table_ = relative_offset - vmap_tables_offset;
1880
1881 #undef VISIT
1882
1883 return relative_offset;
1884}
1885
1886size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Ian Rogers3d504072014-03-01 09:16:49 -08001887 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001888 relative_offset += size_executable_offset_alignment_;
1889 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001890 size_t expected_file_offset = file_offset + relative_offset;
1891 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001892 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
Ian Rogers3d504072014-03-01 09:16:49 -08001893 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001894 return 0;
1895 }
Brian Carlstrom265091e2013-01-30 14:08:26 -08001896 DCHECK_OFFSET();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001897 if (compiler_driver_->IsImage()) {
1898 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001899
Ian Rogers848871b2013-08-05 10:56:33 -07001900 #define DO_TRAMPOLINE(field) \
1901 do { \
1902 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
1903 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08001904 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07001905 size_trampoline_alignment_ += alignment_padding; \
Ian Rogers3d504072014-03-01 09:16:49 -08001906 if (!out->WriteFully(&(*field)[0], field->size())) { \
1907 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001908 return false; \
1909 } \
1910 size_ ## field += field->size(); \
1911 relative_offset += alignment_padding + field->size(); \
1912 DCHECK_OFFSET(); \
1913 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001914
Ian Rogers848871b2013-08-05 10:56:33 -07001915 DO_TRAMPOLINE(interpreter_to_interpreter_bridge_);
1916 DO_TRAMPOLINE(interpreter_to_compiled_code_bridge_);
1917 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001918 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001919 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001920 DO_TRAMPOLINE(quick_resolution_trampoline_);
1921 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
1922 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001923 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001924 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001925}
1926
Ian Rogers3d504072014-03-01 09:16:49 -08001927size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001928 const size_t file_offset,
1929 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001930 #define VISIT(VisitorType) \
1931 do { \
1932 VisitorType visitor(this, out, file_offset, relative_offset); \
1933 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1934 return 0; \
1935 } \
1936 relative_offset = visitor.GetOffset(); \
1937 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001938
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001939 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001940
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001941 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08001942
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001943 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001944}
1945
Vladimir Markof4da6752014-08-01 19:04:18 +01001946bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
1947 static const uint8_t kPadding[] = {
1948 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
1949 };
1950 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
1951 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
1952 return false;
1953 }
1954 size_code_alignment_ += aligned_code_delta;
1955 return true;
1956}
1957
Brian Carlstrom265091e2013-01-30 14:08:26 -08001958OatWriter::OatDexFile::OatDexFile(size_t offset, const DexFile& dex_file) {
1959 offset_ = offset;
Elliott Hughes95572412011-12-13 18:14:20 -08001960 const std::string& location(dex_file.GetLocation());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001961 dex_file_location_size_ = location.size();
1962 dex_file_location_data_ = reinterpret_cast<const uint8_t*>(location.data());
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001963 dex_file_location_checksum_ = dex_file.GetLocationChecksum();
Brian Carlstrom89521892011-12-07 22:05:07 -08001964 dex_file_offset_ = 0;
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -08001965 methods_offsets_.resize(dex_file.NumClassDefs());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001966}
1967
1968size_t OatWriter::OatDexFile::SizeOf() const {
1969 return sizeof(dex_file_location_size_)
1970 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001971 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08001972 + sizeof(dex_file_offset_)
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -08001973 + (sizeof(methods_offsets_[0]) * methods_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001974}
1975
Ian Rogers3d504072014-03-01 09:16:49 -08001976void OatWriter::OatDexFile::UpdateChecksum(OatHeader* oat_header) const {
1977 oat_header->UpdateChecksum(&dex_file_location_size_, sizeof(dex_file_location_size_));
1978 oat_header->UpdateChecksum(dex_file_location_data_, dex_file_location_size_);
1979 oat_header->UpdateChecksum(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_));
1980 oat_header->UpdateChecksum(&dex_file_offset_, sizeof(dex_file_offset_));
1981 oat_header->UpdateChecksum(&methods_offsets_[0],
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -08001982 sizeof(methods_offsets_[0]) * methods_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001983}
1984
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001985bool OatWriter::OatDexFile::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08001986 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001987 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08001988 DCHECK_OFFSET_();
Ian Rogers3d504072014-03-01 09:16:49 -08001989 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
1990 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001991 return false;
1992 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001993 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Ian Rogers3d504072014-03-01 09:16:49 -08001994 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
1995 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001996 return false;
1997 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001998 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Ian Rogers3d504072014-03-01 09:16:49 -08001999 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
2000 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002001 return false;
2002 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002003 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Ian Rogers3d504072014-03-01 09:16:49 -08002004 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
2005 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08002006 return false;
2007 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002008 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Ian Rogers3d504072014-03-01 09:16:49 -08002009 if (!out->WriteFully(&methods_offsets_[0],
Brian Carlstromcd60ac72013-01-20 17:09:51 -08002010 sizeof(methods_offsets_[0]) * methods_offsets_.size())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002011 PLOG(ERROR) << "Failed to write methods offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002012 return false;
2013 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002014 oat_writer->size_oat_dex_file_methods_offsets_ +=
2015 sizeof(methods_offsets_[0]) * methods_offsets_.size();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002016 return true;
2017}
2018
Brian Carlstromba150c32013-08-27 17:31:03 -07002019OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002020 const std::vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07002021 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002022 mirror::Class::Status status)
2023 : compiled_methods_(compiled_methods) {
2024 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07002025 CHECK_LE(num_non_null_compiled_methods, num_methods);
2026
Brian Carlstrom265091e2013-01-30 14:08:26 -08002027 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07002028 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
2029
2030 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
2031 // apply when there are 0 methods, we just arbitrarily say that 0
2032 // methods means kOatClassNoneCompiled and that we won't use
2033 // kOatClassAllCompiled unless there is at least one compiled
2034 // method. This means in an interpretter only system, we can assert
2035 // that all classes are kOatClassNoneCompiled.
2036 if (num_non_null_compiled_methods == 0) {
2037 type_ = kOatClassNoneCompiled;
2038 } else if (num_non_null_compiled_methods == num_methods) {
2039 type_ = kOatClassAllCompiled;
2040 } else {
2041 type_ = kOatClassSomeCompiled;
2042 }
2043
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002044 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07002045 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01002046 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07002047
2048 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
2049 if (type_ == kOatClassSomeCompiled) {
2050 method_bitmap_ = new BitVector(num_methods, false, Allocator::GetMallocAllocator());
2051 method_bitmap_size_ = method_bitmap_->GetSizeOf();
2052 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
2053 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
2054 } else {
2055 method_bitmap_ = NULL;
2056 method_bitmap_size_ = 0;
2057 }
2058
2059 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01002060 CompiledMethod* compiled_method = compiled_methods_[i];
Brian Carlstromba150c32013-08-27 17:31:03 -07002061 if (compiled_method == NULL) {
2062 oat_method_offsets_offsets_from_oat_class_[i] = 0;
2063 } else {
2064 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
2065 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
2066 if (type_ == kOatClassSomeCompiled) {
2067 method_bitmap_->SetBit(i);
2068 }
2069 }
2070 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07002071}
2072
Brian Carlstromba150c32013-08-27 17:31:03 -07002073OatWriter::OatClass::~OatClass() {
Mathieu Chartier661974a2014-01-09 11:23:53 -08002074 delete method_bitmap_;
Brian Carlstromba150c32013-08-27 17:31:03 -07002075}
2076
Brian Carlstrom265091e2013-01-30 14:08:26 -08002077size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
2078 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002079 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
2080 if (method_offset == 0) {
2081 return 0;
2082 }
2083 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08002084}
2085
2086size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
2087 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002088 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08002089}
2090
2091size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07002092 return sizeof(status_)
2093 + sizeof(type_)
2094 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
2095 + method_bitmap_size_
2096 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002097}
2098
Ian Rogers3d504072014-03-01 09:16:49 -08002099void OatWriter::OatClass::UpdateChecksum(OatHeader* oat_header) const {
2100 oat_header->UpdateChecksum(&status_, sizeof(status_));
2101 oat_header->UpdateChecksum(&type_, sizeof(type_));
Brian Carlstromba150c32013-08-27 17:31:03 -07002102 if (method_bitmap_size_ != 0) {
2103 CHECK_EQ(kOatClassSomeCompiled, type_);
Ian Rogers3d504072014-03-01 09:16:49 -08002104 oat_header->UpdateChecksum(&method_bitmap_size_, sizeof(method_bitmap_size_));
2105 oat_header->UpdateChecksum(method_bitmap_->GetRawStorage(), method_bitmap_size_);
Brian Carlstromba150c32013-08-27 17:31:03 -07002106 }
Ian Rogers3d504072014-03-01 09:16:49 -08002107 oat_header->UpdateChecksum(&method_offsets_[0],
2108 sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07002109}
2110
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002111bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08002112 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07002113 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08002114 DCHECK_OFFSET_();
Ian Rogers3d504072014-03-01 09:16:49 -08002115 if (!out->WriteFully(&status_, sizeof(status_))) {
2116 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08002117 return false;
2118 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002119 oat_writer->size_oat_class_status_ += sizeof(status_);
Ian Rogers3d504072014-03-01 09:16:49 -08002120 if (!out->WriteFully(&type_, sizeof(type_))) {
2121 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002122 return false;
2123 }
2124 oat_writer->size_oat_class_type_ += sizeof(type_);
2125 if (method_bitmap_size_ != 0) {
2126 CHECK_EQ(kOatClassSomeCompiled, type_);
Ian Rogers3d504072014-03-01 09:16:49 -08002127 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
2128 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002129 return false;
2130 }
2131 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Ian Rogers3d504072014-03-01 09:16:49 -08002132 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
2133 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07002134 return false;
2135 }
2136 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
2137 }
Ian Rogers3d504072014-03-01 09:16:49 -08002138 if (!out->WriteFully(&method_offsets_[0],
Brian Carlstromcd60ac72013-01-20 17:09:51 -08002139 sizeof(method_offsets_[0]) * method_offsets_.size())) {
Ian Rogers3d504072014-03-01 09:16:49 -08002140 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002141 return false;
2142 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07002143 oat_writer->size_oat_class_method_offsets_ += sizeof(method_offsets_[0]) * method_offsets_.size();
Brian Carlstrome24fa612011-09-29 00:53:55 -07002144 return true;
2145}
2146
Brian Carlstrome24fa612011-09-29 00:53:55 -07002147} // namespace art