blob: 05599e17337574a2dfba62256863e412e6d8fd4a [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Brian Carlstrome24fa612011-09-29 00:53:55 -070016
17#include "oat_writer.h"
18
Elliott Hughesa0e18062012-04-13 15:59:59 -070019#include <zlib.h>
20
Ian Rogerse77493c2014-08-20 15:08:45 -070021#include "base/allocator.h"
Brian Carlstromba150c32013-08-27 17:31:03 -070022#include "base/bit_vector.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080023#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080024#include "base/unix_file/fd_file.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070025#include "class_linker.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070026#include "compiled_class.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000027#include "compiled_method.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070028#include "dex_file-inl.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000029#include "dex/verification_results.h"
Vladimir Marko20f85592015-03-19 10:07:02 +000030#include "driver/compiler_driver.h"
31#include "driver/compiler_options.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070032#include "gc/space/space.h"
Vladimir Markof4da6752014-08-01 19:04:18 +010033#include "image_writer.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070034#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080035#include "mirror/array.h"
36#include "mirror/class_loader.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070037#include "mirror/object-inl.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070038#include "os.h"
Brian Carlstromcd60ac72013-01-20 17:09:51 -080039#include "output_stream.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070040#include "safe_map.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070041#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070042#include "handle_scope-inl.h"
Vladimir Markof4da6752014-08-01 19:04:18 +010043#include "utils/arm/assembler_thumb2.h"
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +010044#include "utils/arm64/assembler_arm64.h"
jeffhaoec014232012-09-05 10:42:25 -070045#include "verifier/method_verifier.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070046
47namespace art {
48
Vladimir Marko20f85592015-03-19 10:07:02 +000049class OatWriter::RelativePatcher {
Vladimir Markof4da6752014-08-01 19:04:18 +010050 public:
Vladimir Marko20f85592015-03-19 10:07:02 +000051 virtual ~RelativePatcher() { }
Vladimir Markof4da6752014-08-01 19:04:18 +010052
53 // Reserve space for relative call thunks if needed, return adjusted offset.
54 // After all methods have been processed it's call one last time with compiled_method == nullptr.
55 virtual uint32_t ReserveSpace(uint32_t offset, const CompiledMethod* compiled_method) = 0;
56
57 // Write relative call thunks if needed, return adjusted offset.
58 virtual uint32_t WriteThunks(OutputStream* out, uint32_t offset) = 0;
59
60 // Patch method code. The input displacement is relative to the patched location,
61 // the patcher may need to adjust it if the correct base is different.
Vladimir Marko20f85592015-03-19 10:07:02 +000062 virtual void PatchCall(std::vector<uint8_t>* code, uint32_t literal_offset,
63 uint32_t patch_offset, uint32_t target_offset) = 0;
64
65 // Patch a reference to a dex cache location.
66 virtual void PatchDexCacheReference(std::vector<uint8_t>* code, const LinkerPatch& patch,
67 uint32_t patch_offset, uint32_t target_offset) = 0;
Vladimir Markof4da6752014-08-01 19:04:18 +010068
69 protected:
Vladimir Marko20f85592015-03-19 10:07:02 +000070 RelativePatcher() { }
Vladimir Markof4da6752014-08-01 19:04:18 +010071
72 private:
Vladimir Marko20f85592015-03-19 10:07:02 +000073 DISALLOW_COPY_AND_ASSIGN(RelativePatcher);
Vladimir Markof4da6752014-08-01 19:04:18 +010074};
75
Vladimir Marko20f85592015-03-19 10:07:02 +000076class OatWriter::NoRelativePatcher FINAL : public RelativePatcher {
Vladimir Markof4da6752014-08-01 19:04:18 +010077 public:
Vladimir Marko20f85592015-03-19 10:07:02 +000078 NoRelativePatcher() { }
Vladimir Markof4da6752014-08-01 19:04:18 +010079
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070080 uint32_t ReserveSpace(uint32_t offset,
81 const CompiledMethod* compiled_method ATTRIBUTE_UNUSED) OVERRIDE {
Vladimir Markof4da6752014-08-01 19:04:18 +010082 return offset; // No space reserved; no patches expected.
83 }
84
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070085 uint32_t WriteThunks(OutputStream* out ATTRIBUTE_UNUSED, uint32_t offset) OVERRIDE {
Vladimir Markof4da6752014-08-01 19:04:18 +010086 return offset; // No thunks added; no patches expected.
87 }
88
Vladimir Marko20f85592015-03-19 10:07:02 +000089 void PatchCall(std::vector<uint8_t>* code ATTRIBUTE_UNUSED,
90 uint32_t literal_offset ATTRIBUTE_UNUSED,
91 uint32_t patch_offset ATTRIBUTE_UNUSED,
92 uint32_t target_offset ATTRIBUTE_UNUSED) OVERRIDE {
93 LOG(FATAL) << "Unexpected relative call patch.";
94 }
95
96 virtual void PatchDexCacheReference(std::vector<uint8_t>* code ATTRIBUTE_UNUSED,
97 const LinkerPatch& patch ATTRIBUTE_UNUSED,
98 uint32_t patch_offset ATTRIBUTE_UNUSED,
99 uint32_t target_offset ATTRIBUTE_UNUSED) {
100 LOG(FATAL) << "Unexpected relative dex cache array patch.";
Vladimir Markof4da6752014-08-01 19:04:18 +0100101 }
102
103 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000104 DISALLOW_COPY_AND_ASSIGN(NoRelativePatcher);
Vladimir Markof4da6752014-08-01 19:04:18 +0100105};
106
Vladimir Marko20f85592015-03-19 10:07:02 +0000107class OatWriter::X86RelativePatcher FINAL : public RelativePatcher {
Vladimir Markof4da6752014-08-01 19:04:18 +0100108 public:
Vladimir Marko20f85592015-03-19 10:07:02 +0000109 X86RelativePatcher() { }
Vladimir Markof4da6752014-08-01 19:04:18 +0100110
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700111 uint32_t ReserveSpace(uint32_t offset,
112 const CompiledMethod* compiled_method ATTRIBUTE_UNUSED) OVERRIDE {
Vladimir Markof4da6752014-08-01 19:04:18 +0100113 return offset; // No space reserved; no limit on relative call distance.
114 }
115
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700116 uint32_t WriteThunks(OutputStream* out ATTRIBUTE_UNUSED, uint32_t offset) OVERRIDE {
Vladimir Markof4da6752014-08-01 19:04:18 +0100117 return offset; // No thunks added; no limit on relative call distance.
118 }
119
Vladimir Marko20f85592015-03-19 10:07:02 +0000120 void PatchCall(std::vector<uint8_t>* code, uint32_t literal_offset,
121 uint32_t patch_offset, uint32_t target_offset) OVERRIDE {
Vladimir Markof4da6752014-08-01 19:04:18 +0100122 DCHECK_LE(literal_offset + 4u, code->size());
123 // Unsigned arithmetic with its well-defined overflow behavior is just fine here.
124 uint32_t displacement = target_offset - patch_offset;
125 displacement -= kPcDisplacement; // The base PC is at the end of the 4-byte patch.
126
127 typedef __attribute__((__aligned__(1))) int32_t unaligned_int32_t;
128 reinterpret_cast<unaligned_int32_t*>(&(*code)[literal_offset])[0] = displacement;
129 }
130
Vladimir Marko20f85592015-03-19 10:07:02 +0000131 virtual void PatchDexCacheReference(std::vector<uint8_t>* code ATTRIBUTE_UNUSED,
132 const LinkerPatch& patch ATTRIBUTE_UNUSED,
133 uint32_t patch_offset ATTRIBUTE_UNUSED,
134 uint32_t target_offset ATTRIBUTE_UNUSED) {
135 LOG(FATAL) << "Unexpected relative dex cache array patch.";
136 }
137
Vladimir Markof4da6752014-08-01 19:04:18 +0100138 private:
139 // PC displacement from patch location; x86 PC for relative calls points to the next
140 // instruction and the patch location is 4 bytes earlier.
141 static constexpr int32_t kPcDisplacement = 4;
142
Vladimir Marko20f85592015-03-19 10:07:02 +0000143 DISALLOW_COPY_AND_ASSIGN(X86RelativePatcher);
Vladimir Markof4da6752014-08-01 19:04:18 +0100144};
145
Vladimir Marko20f85592015-03-19 10:07:02 +0000146class OatWriter::ArmBaseRelativePatcher : public RelativePatcher {
Vladimir Markof4da6752014-08-01 19:04:18 +0100147 public:
Vladimir Marko20f85592015-03-19 10:07:02 +0000148 ArmBaseRelativePatcher(OatWriter* writer,
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100149 InstructionSet instruction_set, std::vector<uint8_t> thunk_code,
150 uint32_t max_positive_displacement, uint32_t max_negative_displacement)
151 : writer_(writer), instruction_set_(instruction_set), thunk_code_(thunk_code),
152 max_positive_displacement_(max_positive_displacement),
153 max_negative_displacement_(max_negative_displacement),
Vladimir Markof4da6752014-08-01 19:04:18 +0100154 thunk_locations_(), current_thunk_to_write_(0u), unprocessed_patches_() {
155 }
156
157 uint32_t ReserveSpace(uint32_t offset, const CompiledMethod* compiled_method) OVERRIDE {
158 // NOTE: The final thunk can be reserved from InitCodeMethodVisitor::EndClass() while it
159 // may be written early by WriteCodeMethodVisitor::VisitMethod() for a deduplicated chunk
160 // of code. To avoid any alignment discrepancies for the final chunk, we always align the
161 // offset after reserving of writing any chunk.
162 if (UNLIKELY(compiled_method == nullptr)) {
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100163 uint32_t aligned_offset = CompiledMethod::AlignCode(offset, instruction_set_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100164 bool needs_thunk = ReserveSpaceProcessPatches(aligned_offset);
165 if (needs_thunk) {
166 thunk_locations_.push_back(aligned_offset);
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100167 offset = CompiledMethod::AlignCode(aligned_offset + thunk_code_.size(), instruction_set_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100168 }
169 return offset;
170 }
171 DCHECK(compiled_method->GetQuickCode() != nullptr);
172 uint32_t quick_code_size = compiled_method->GetQuickCode()->size();
173 uint32_t quick_code_offset = compiled_method->AlignCode(offset) + sizeof(OatQuickMethodHeader);
174 uint32_t next_aligned_offset = compiled_method->AlignCode(quick_code_offset + quick_code_size);
175 if (!unprocessed_patches_.empty() &&
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100176 next_aligned_offset - unprocessed_patches_.front().second > max_positive_displacement_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100177 bool needs_thunk = ReserveSpaceProcessPatches(next_aligned_offset);
178 if (needs_thunk) {
179 // A single thunk will cover all pending patches.
180 unprocessed_patches_.clear();
181 uint32_t thunk_location = compiled_method->AlignCode(offset);
182 thunk_locations_.push_back(thunk_location);
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100183 offset = CompiledMethod::AlignCode(thunk_location + thunk_code_.size(), instruction_set_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100184 }
185 }
186 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
187 if (patch.Type() == kLinkerPatchCallRelative) {
188 unprocessed_patches_.emplace_back(patch.TargetMethod(),
189 quick_code_offset + patch.LiteralOffset());
190 }
191 }
192 return offset;
193 }
194
195 uint32_t WriteThunks(OutputStream* out, uint32_t offset) OVERRIDE {
196 if (current_thunk_to_write_ == thunk_locations_.size()) {
197 return offset;
198 }
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100199 uint32_t aligned_offset = CompiledMethod::AlignCode(offset, instruction_set_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100200 if (UNLIKELY(aligned_offset == thunk_locations_[current_thunk_to_write_])) {
201 ++current_thunk_to_write_;
202 uint32_t aligned_code_delta = aligned_offset - offset;
203 if (aligned_code_delta != 0u && !writer_->WriteCodeAlignment(out, aligned_code_delta)) {
204 return 0u;
205 }
206 if (!out->WriteFully(thunk_code_.data(), thunk_code_.size())) {
207 return 0u;
208 }
209 writer_->size_relative_call_thunks_ += thunk_code_.size();
210 uint32_t thunk_end_offset = aligned_offset + thunk_code_.size();
211 // Align after writing chunk, see the ReserveSpace() above.
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100212 offset = CompiledMethod::AlignCode(thunk_end_offset, instruction_set_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100213 aligned_code_delta = offset - thunk_end_offset;
214 if (aligned_code_delta != 0u && !writer_->WriteCodeAlignment(out, aligned_code_delta)) {
215 return 0u;
216 }
217 }
218 return offset;
219 }
220
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100221 protected:
222 uint32_t CalculateDisplacement(uint32_t patch_offset, uint32_t target_offset) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100223 // Unsigned arithmetic with its well-defined overflow behavior is just fine here.
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100224 uint32_t displacement = target_offset - patch_offset;
Vladimir Markof4da6752014-08-01 19:04:18 +0100225 // NOTE: With unsigned arithmetic we do mean to use && rather than || below.
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100226 if (displacement > max_positive_displacement_ && displacement < -max_negative_displacement_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100227 // Unwritten thunks have higher offsets, check if it's within range.
228 DCHECK(current_thunk_to_write_ == thunk_locations_.size() ||
229 thunk_locations_[current_thunk_to_write_] > patch_offset);
230 if (current_thunk_to_write_ != thunk_locations_.size() &&
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100231 thunk_locations_[current_thunk_to_write_] - patch_offset < max_positive_displacement_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100232 displacement = thunk_locations_[current_thunk_to_write_] - patch_offset;
233 } else {
234 // We must have a previous thunk then.
235 DCHECK_NE(current_thunk_to_write_, 0u);
236 DCHECK_LT(thunk_locations_[current_thunk_to_write_ - 1], patch_offset);
237 displacement = thunk_locations_[current_thunk_to_write_ - 1] - patch_offset;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100238 DCHECK(displacement >= -max_negative_displacement_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100239 }
240 }
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100241 return displacement;
242 }
243
244 private:
245 bool ReserveSpaceProcessPatches(uint32_t next_aligned_offset) {
246 // Process as many patches as possible, stop only on unresolved targets or calls too far back.
247 while (!unprocessed_patches_.empty()) {
248 uint32_t patch_offset = unprocessed_patches_.front().second;
249 auto it = writer_->method_offset_map_.find(unprocessed_patches_.front().first);
250 if (it == writer_->method_offset_map_.end()) {
251 // If still unresolved, check if we have a thunk within range.
252 DCHECK(thunk_locations_.empty() || thunk_locations_.back() <= patch_offset);
253 if (thunk_locations_.empty() ||
254 patch_offset - thunk_locations_.back() > max_negative_displacement_) {
255 return next_aligned_offset - patch_offset > max_positive_displacement_;
256 }
257 } else if (it->second >= patch_offset) {
258 DCHECK_LE(it->second - patch_offset, max_positive_displacement_);
259 } else {
260 // When calling back, check if we have a thunk that's closer than the actual target.
261 uint32_t target_offset = (thunk_locations_.empty() || it->second > thunk_locations_.back())
262 ? it->second
263 : thunk_locations_.back();
264 DCHECK_GT(patch_offset, target_offset);
265 if (patch_offset - target_offset > max_negative_displacement_) {
266 return true;
267 }
268 }
269 unprocessed_patches_.pop_front();
270 }
271 return false;
272 }
273
274 OatWriter* const writer_;
275 const InstructionSet instruction_set_;
276 const std::vector<uint8_t> thunk_code_;
277 const uint32_t max_positive_displacement_;
278 const uint32_t max_negative_displacement_;
279 std::vector<uint32_t> thunk_locations_;
280 size_t current_thunk_to_write_;
281
282 // ReserveSpace() tracks unprocessed patches.
283 typedef std::pair<MethodReference, uint32_t> UnprocessedPatch;
284 std::deque<UnprocessedPatch> unprocessed_patches_;
285
Vladimir Marko20f85592015-03-19 10:07:02 +0000286 DISALLOW_COPY_AND_ASSIGN(ArmBaseRelativePatcher);
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100287};
288
Vladimir Marko20f85592015-03-19 10:07:02 +0000289class OatWriter::Thumb2RelativePatcher FINAL : public ArmBaseRelativePatcher {
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100290 public:
Vladimir Marko20f85592015-03-19 10:07:02 +0000291 explicit Thumb2RelativePatcher(OatWriter* writer)
292 : ArmBaseRelativePatcher(writer, kThumb2, CompileThunkCode(),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100293 kMaxPositiveDisplacement, kMaxNegativeDisplacement) {
294 }
295
Vladimir Marko20f85592015-03-19 10:07:02 +0000296 void PatchCall(std::vector<uint8_t>* code, uint32_t literal_offset,
297 uint32_t patch_offset, uint32_t target_offset) OVERRIDE {
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100298 DCHECK_LE(literal_offset + 4u, code->size());
299 DCHECK_EQ(literal_offset & 1u, 0u);
300 DCHECK_EQ(patch_offset & 1u, 0u);
301 DCHECK_EQ(target_offset & 1u, 1u); // Thumb2 mode bit.
302 uint32_t displacement = CalculateDisplacement(patch_offset, target_offset & ~1u);
Vladimir Markof4da6752014-08-01 19:04:18 +0100303 displacement -= kPcDisplacement; // The base PC is at the end of the 4-byte patch.
304 DCHECK_EQ(displacement & 1u, 0u);
305 DCHECK((displacement >> 24) == 0u || (displacement >> 24) == 255u); // 25-bit signed.
306 uint32_t signbit = (displacement >> 31) & 0x1;
307 uint32_t i1 = (displacement >> 23) & 0x1;
308 uint32_t i2 = (displacement >> 22) & 0x1;
309 uint32_t imm10 = (displacement >> 12) & 0x03ff;
310 uint32_t imm11 = (displacement >> 1) & 0x07ff;
311 uint32_t j1 = i1 ^ (signbit ^ 1);
312 uint32_t j2 = i2 ^ (signbit ^ 1);
313 uint32_t value = (signbit << 26) | (j1 << 13) | (j2 << 11) | (imm10 << 16) | imm11;
314 value |= 0xf000d000; // BL
315
316 uint8_t* addr = &(*code)[literal_offset];
317 // Check that we're just overwriting an existing BL.
318 DCHECK_EQ(addr[1] & 0xf8, 0xf0);
319 DCHECK_EQ(addr[3] & 0xd0, 0xd0);
320 // Write the new BL.
321 addr[0] = (value >> 16) & 0xff;
322 addr[1] = (value >> 24) & 0xff;
323 addr[2] = (value >> 0) & 0xff;
324 addr[3] = (value >> 8) & 0xff;
325 }
326
Vladimir Marko20f85592015-03-19 10:07:02 +0000327 virtual void PatchDexCacheReference(std::vector<uint8_t>* code ATTRIBUTE_UNUSED,
328 const LinkerPatch& patch ATTRIBUTE_UNUSED,
329 uint32_t patch_offset ATTRIBUTE_UNUSED,
330 uint32_t target_offset ATTRIBUTE_UNUSED) {
331 LOG(FATAL) << "Unexpected relative dex cache array patch.";
332 }
333
Vladimir Markof4da6752014-08-01 19:04:18 +0100334 private:
Vladimir Markof4da6752014-08-01 19:04:18 +0100335 static std::vector<uint8_t> CompileThunkCode() {
336 // The thunk just uses the entry point in the ArtMethod. This works even for calls
337 // to the generic JNI and interpreter trampolines.
338 arm::Thumb2Assembler assembler;
339 assembler.LoadFromOffset(
340 arm::kLoadWord, arm::PC, arm::R0,
Mathieu Chartier2d721012014-11-10 11:08:06 -0800341 mirror::ArtMethod::EntryPointFromQuickCompiledCodeOffset(kArmPointerSize).Int32Value());
Vladimir Markof4da6752014-08-01 19:04:18 +0100342 assembler.bkpt(0);
343 std::vector<uint8_t> thunk_code(assembler.CodeSize());
344 MemoryRegion code(thunk_code.data(), thunk_code.size());
345 assembler.FinalizeInstructions(code);
346 return thunk_code;
347 }
348
349 // PC displacement from patch location; Thumb2 PC is always at instruction address + 4.
350 static constexpr int32_t kPcDisplacement = 4;
351
352 // Maximum positive and negative displacement measured from the patch location.
353 // (Signed 25 bit displacement with the last bit 0 has range [-2^24, 2^24-2] measured from
354 // the Thumb2 PC pointing right after the BL, i.e. 4 bytes later than the patch location.)
355 static constexpr uint32_t kMaxPositiveDisplacement = (1u << 24) - 2 + kPcDisplacement;
356 static constexpr uint32_t kMaxNegativeDisplacement = (1u << 24) - kPcDisplacement;
357
Vladimir Marko20f85592015-03-19 10:07:02 +0000358 DISALLOW_COPY_AND_ASSIGN(Thumb2RelativePatcher);
Vladimir Markof4da6752014-08-01 19:04:18 +0100359};
360
Vladimir Marko20f85592015-03-19 10:07:02 +0000361class OatWriter::Arm64RelativePatcher FINAL : public ArmBaseRelativePatcher {
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100362 public:
Vladimir Marko20f85592015-03-19 10:07:02 +0000363 explicit Arm64RelativePatcher(OatWriter* writer)
364 : ArmBaseRelativePatcher(writer, kArm64, CompileThunkCode(),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100365 kMaxPositiveDisplacement, kMaxNegativeDisplacement) {
366 }
367
Vladimir Marko20f85592015-03-19 10:07:02 +0000368 void PatchCall(std::vector<uint8_t>* code, uint32_t literal_offset,
369 uint32_t patch_offset, uint32_t target_offset) OVERRIDE {
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100370 DCHECK_LE(literal_offset + 4u, code->size());
371 DCHECK_EQ(literal_offset & 3u, 0u);
372 DCHECK_EQ(patch_offset & 3u, 0u);
373 DCHECK_EQ(target_offset & 3u, 0u);
374 uint32_t displacement = CalculateDisplacement(patch_offset, target_offset & ~1u);
375 DCHECK_EQ(displacement & 3u, 0u);
376 DCHECK((displacement >> 27) == 0u || (displacement >> 27) == 31u); // 28-bit signed.
Vladimir Marko20f85592015-03-19 10:07:02 +0000377 uint32_t insn = (displacement & 0x0fffffffu) >> 2;
378 insn |= 0x94000000; // BL
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100379
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100380 // Check that we're just overwriting an existing BL.
Vladimir Marko20f85592015-03-19 10:07:02 +0000381 DCHECK_EQ(GetInsn(code, literal_offset) & 0xfc000000u, 0x94000000u);
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100382 // Write the new BL.
Vladimir Marko20f85592015-03-19 10:07:02 +0000383 SetInsn(code, literal_offset, insn);
384 }
385
386 virtual void PatchDexCacheReference(std::vector<uint8_t>* code ATTRIBUTE_UNUSED,
387 const LinkerPatch& patch ATTRIBUTE_UNUSED,
388 uint32_t patch_offset ATTRIBUTE_UNUSED,
389 uint32_t target_offset ATTRIBUTE_UNUSED) {
390 DCHECK_EQ(patch_offset & 3u, 0u);
391 DCHECK_EQ(target_offset & 3u, 0u);
392 uint32_t literal_offset = patch.LiteralOffset();
393 uint32_t insn = GetInsn(code, literal_offset);
394 uint32_t pc_insn_offset = patch.PcInsnOffset();
395 uint32_t disp = target_offset - ((patch_offset - literal_offset + pc_insn_offset) & ~0xfffu);
396 if (literal_offset == pc_insn_offset) {
397 // Check it's an ADRP with imm == 0 (unset).
398 DCHECK_EQ((insn & 0xffffffe0u), 0x90000000u)
399 << literal_offset << ", " << pc_insn_offset << ", 0x" << std::hex << insn;
400 insn = (insn & 0x9f00001fu) |
401 ((disp & 0x00003000u) << (29 - 12)) |
402 ((disp & 0xffffc000u) >> (12 + 2 - 5)) |
403 // Since the target_offset is based on the beginning of the oat file and the
404 // image space precedes the oat file, the target_offset into image space will
405 // be negative yet passed as uint32_t. Therefore we limit the displacement
406 // to +-2GiB (rather than the maximim +-4GiB) and determine the sign bit from
407 // the highest bit of the displacement.
408 ((disp & 0x80000000u) >> (31 - 23));
409 // Write the new ADRP.
410 SetInsn(code, literal_offset, insn);
411 } else {
412 DCHECK_EQ(insn & 0xfffffc00, 0xb9400000); // LDR 32-bit with imm12 == 0 (unset).
413 DCHECK_EQ(GetInsn(code, pc_insn_offset) & 0x9f00001fu, // Check that pc_insn_offset points
414 0x90000000 | ((insn >> 5) & 0x1fu)); // to ADRP with matching register.
415 uint32_t imm12 = (disp & 0xfffu) >> 2;
416 insn = (insn & ~(0xfffu << 10)) | (imm12 << 10);
417 SetInsn(code, literal_offset, insn);
418 }
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100419 }
420
421 private:
422 static std::vector<uint8_t> CompileThunkCode() {
423 // The thunk just uses the entry point in the ArtMethod. This works even for calls
424 // to the generic JNI and interpreter trampolines.
425 arm64::Arm64Assembler assembler;
Mathieu Chartier2d721012014-11-10 11:08:06 -0800426 Offset offset(mirror::ArtMethod::EntryPointFromQuickCompiledCodeOffset(
427 kArm64PointerSize).Int32Value());
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100428 assembler.JumpTo(ManagedRegister(arm64::X0), offset, ManagedRegister(arm64::IP0));
Serban Constantinescu32f5b4d2014-11-25 20:05:46 +0000429 // Ensure we emit the literal pool.
430 assembler.EmitSlowPaths();
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100431 std::vector<uint8_t> thunk_code(assembler.CodeSize());
432 MemoryRegion code(thunk_code.data(), thunk_code.size());
433 assembler.FinalizeInstructions(code);
434 return thunk_code;
435 }
436
Vladimir Marko20f85592015-03-19 10:07:02 +0000437 uint32_t GetInsn(std::vector<uint8_t>* code, uint32_t offset) {
438 DCHECK_LE(offset + 4u, code->size());
439 DCHECK_EQ(offset & 3u, 0u);
440 uint8_t* addr = &(*code)[offset];
441 return
442 (static_cast<uint32_t>(addr[0]) << 0) +
443 (static_cast<uint32_t>(addr[1]) << 8) +
444 (static_cast<uint32_t>(addr[2]) << 16)+
445 (static_cast<uint32_t>(addr[3]) << 24);
446 }
447
448 void SetInsn(std::vector<uint8_t>* code, uint32_t offset, uint32_t value) {
449 DCHECK_LE(offset + 4u, code->size());
450 DCHECK_EQ(offset & 3u, 0u);
451 uint8_t* addr = &(*code)[offset];
452 addr[0] = (value >> 0) & 0xff;
453 addr[1] = (value >> 8) & 0xff;
454 addr[2] = (value >> 16) & 0xff;
455 addr[3] = (value >> 24) & 0xff;
456 }
457
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100458 // Maximum positive and negative displacement measured from the patch location.
459 // (Signed 28 bit displacement with the last bit 0 has range [-2^27, 2^27-4] measured from
460 // the ARM64 PC pointing to the BL.)
461 static constexpr uint32_t kMaxPositiveDisplacement = (1u << 27) - 4u;
462 static constexpr uint32_t kMaxNegativeDisplacement = (1u << 27);
463
Vladimir Marko20f85592015-03-19 10:07:02 +0000464 DISALLOW_COPY_AND_ASSIGN(Arm64RelativePatcher);
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100465};
466
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100467#define DCHECK_OFFSET() \
468 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
469 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
470
471#define DCHECK_OFFSET_() \
472 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
473 << "file_offset=" << file_offset << " offset_=" << offset_
474
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700475OatWriter::OatWriter(const std::vector<const DexFile*>& dex_files,
Brian Carlstrom28db0122012-10-18 16:20:41 -0700476 uint32_t image_file_location_oat_checksum,
Ian Rogersef7d42f2014-01-06 12:55:46 -0800477 uintptr_t image_file_location_oat_begin,
Alex Lighta59dd802014-07-02 16:28:08 -0700478 int32_t image_patch_delta,
Ian Rogersca368cb2013-11-15 15:52:08 -0800479 const CompilerDriver* compiler,
Vladimir Markof4da6752014-08-01 19:04:18 +0100480 ImageWriter* image_writer,
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700481 TimingLogger* timings,
482 SafeMap<std::string, std::string>* key_value_store)
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700483 : compiler_driver_(compiler),
Vladimir Markof4da6752014-08-01 19:04:18 +0100484 image_writer_(image_writer),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700485 dex_files_(&dex_files),
Vladimir Markof4da6752014-08-01 19:04:18 +0100486 size_(0u),
Vladimir Marko5c42c292015-02-25 12:02:49 +0000487 bss_size_(0u),
Vladimir Markof4da6752014-08-01 19:04:18 +0100488 oat_data_offset_(0u),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700489 image_file_location_oat_checksum_(image_file_location_oat_checksum),
490 image_file_location_oat_begin_(image_file_location_oat_begin),
Alex Lighta59dd802014-07-02 16:28:08 -0700491 image_patch_delta_(image_patch_delta),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700492 key_value_store_(key_value_store),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700493 oat_header_(NULL),
494 size_dex_file_alignment_(0),
495 size_executable_offset_alignment_(0),
496 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700497 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700498 size_dex_file_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700499 size_interpreter_to_interpreter_bridge_(0),
500 size_interpreter_to_compiled_code_bridge_(0),
501 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800502 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700503 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700504 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700505 size_quick_to_interpreter_bridge_(0),
506 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100507 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700508 size_code_(0),
509 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100510 size_relative_call_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700511 size_mapping_table_(0),
512 size_vmap_table_(0),
513 size_gc_map_(0),
514 size_oat_dex_file_location_size_(0),
515 size_oat_dex_file_location_data_(0),
516 size_oat_dex_file_location_checksum_(0),
517 size_oat_dex_file_offset_(0),
518 size_oat_dex_file_methods_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700519 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700520 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700521 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100522 size_oat_class_method_offsets_(0),
523 method_offset_map_() {
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700524 CHECK(key_value_store != nullptr);
525
Vladimir Markof4da6752014-08-01 19:04:18 +0100526 switch (compiler_driver_->GetInstructionSet()) {
527 case kX86:
528 case kX86_64:
Vladimir Marko20f85592015-03-19 10:07:02 +0000529 relative_patcher_.reset(new X86RelativePatcher);
Vladimir Markof4da6752014-08-01 19:04:18 +0100530 break;
531 case kArm:
532 // Fall through: we generate Thumb2 code for "arm".
533 case kThumb2:
Vladimir Marko20f85592015-03-19 10:07:02 +0000534 relative_patcher_.reset(new Thumb2RelativePatcher(this));
Vladimir Markof4da6752014-08-01 19:04:18 +0100535 break;
536 case kArm64:
Vladimir Marko20f85592015-03-19 10:07:02 +0000537 relative_patcher_.reset(new Arm64RelativePatcher(this));
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100538 break;
Vladimir Markof4da6752014-08-01 19:04:18 +0100539 default:
Vladimir Marko20f85592015-03-19 10:07:02 +0000540 relative_patcher_.reset(new NoRelativePatcher);
Vladimir Markof4da6752014-08-01 19:04:18 +0100541 break;
542 }
543
Ian Rogersca368cb2013-11-15 15:52:08 -0800544 size_t offset;
545 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700546 TimingLogger::ScopedTiming split("InitOatHeader", timings);
Ian Rogersca368cb2013-11-15 15:52:08 -0800547 offset = InitOatHeader();
548 }
549 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700550 TimingLogger::ScopedTiming split("InitOatDexFiles", timings);
Ian Rogersca368cb2013-11-15 15:52:08 -0800551 offset = InitOatDexFiles(offset);
552 }
553 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700554 TimingLogger::ScopedTiming split("InitDexFiles", timings);
Ian Rogersca368cb2013-11-15 15:52:08 -0800555 offset = InitDexFiles(offset);
556 }
557 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700558 TimingLogger::ScopedTiming split("InitOatClasses", timings);
Ian Rogersca368cb2013-11-15 15:52:08 -0800559 offset = InitOatClasses(offset);
560 }
561 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700562 TimingLogger::ScopedTiming split("InitOatMaps", timings);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100563 offset = InitOatMaps(offset);
564 }
565 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700566 TimingLogger::ScopedTiming split("InitOatCode", timings);
Ian Rogersca368cb2013-11-15 15:52:08 -0800567 offset = InitOatCode(offset);
568 }
569 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700570 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings);
Ian Rogersca368cb2013-11-15 15:52:08 -0800571 offset = InitOatCodeDexFiles(offset);
572 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700573 size_ = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700574
575 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Vladimir Markof4da6752014-08-01 19:04:18 +0100576 CHECK_EQ(compiler->IsImage(), image_writer_ != nullptr);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700577 CHECK_EQ(compiler->IsImage(),
578 key_value_store_->find(OatHeader::kImageLocationKey) == key_value_store_->end());
Alex Lighta59dd802014-07-02 16:28:08 -0700579 CHECK_ALIGNED(image_patch_delta_, kPageSize);
Brian Carlstrome24fa612011-09-29 00:53:55 -0700580}
581
Ian Rogers0571d352011-11-03 19:51:38 -0700582OatWriter::~OatWriter() {
583 delete oat_header_;
584 STLDeleteElements(&oat_dex_files_);
Brian Carlstrom389efb02012-01-11 12:06:26 -0800585 STLDeleteElements(&oat_classes_);
Ian Rogers0571d352011-11-03 19:51:38 -0700586}
587
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100588struct OatWriter::GcMapDataAccess {
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800589 static const SwapVector<uint8_t>* GetData(const CompiledMethod* compiled_method) ALWAYS_INLINE {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100590 return compiled_method->GetGcMap();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100591 }
592
593 static uint32_t GetOffset(OatClass* oat_class, size_t method_offsets_index) ALWAYS_INLINE {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800594 uint32_t offset = oat_class->method_headers_[method_offsets_index].gc_map_offset_;
595 return offset == 0u ? 0u :
596 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100597 }
598
599 static void SetOffset(OatClass* oat_class, size_t method_offsets_index, uint32_t offset)
600 ALWAYS_INLINE {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800601 oat_class->method_headers_[method_offsets_index].gc_map_offset_ =
602 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100603 }
604
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800605 static const char* Name() {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100606 return "GC map";
607 }
608};
609
610struct OatWriter::MappingTableDataAccess {
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800611 static const SwapVector<uint8_t>* GetData(const CompiledMethod* compiled_method) ALWAYS_INLINE {
Nicolas Geoffray376b2bb2014-12-09 14:26:32 +0000612 return compiled_method->GetMappingTable();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100613 }
614
615 static uint32_t GetOffset(OatClass* oat_class, size_t method_offsets_index) ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100616 uint32_t offset = oat_class->method_headers_[method_offsets_index].mapping_table_offset_;
617 return offset == 0u ? 0u :
618 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100619 }
620
621 static void SetOffset(OatClass* oat_class, size_t method_offsets_index, uint32_t offset)
622 ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100623 oat_class->method_headers_[method_offsets_index].mapping_table_offset_ =
624 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100625 }
626
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800627 static const char* Name() {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100628 return "mapping table";
629 }
630};
631
632struct OatWriter::VmapTableDataAccess {
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800633 static const SwapVector<uint8_t>* GetData(const CompiledMethod* compiled_method) ALWAYS_INLINE {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800634 return compiled_method->GetVmapTable();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100635 }
636
637 static uint32_t GetOffset(OatClass* oat_class, size_t method_offsets_index) ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100638 uint32_t offset = oat_class->method_headers_[method_offsets_index].vmap_table_offset_;
639 return offset == 0u ? 0u :
640 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100641 }
642
643 static void SetOffset(OatClass* oat_class, size_t method_offsets_index, uint32_t offset)
644 ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100645 oat_class->method_headers_[method_offsets_index].vmap_table_offset_ =
646 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100647 }
648
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800649 static const char* Name() {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100650 return "vmap table";
651 }
652};
653
654class OatWriter::DexMethodVisitor {
655 public:
656 DexMethodVisitor(OatWriter* writer, size_t offset)
657 : writer_(writer),
658 offset_(offset),
659 dex_file_(nullptr),
660 class_def_index_(DexFile::kDexNoIndex) {
661 }
662
663 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
664 DCHECK(dex_file_ == nullptr);
665 DCHECK_EQ(class_def_index_, DexFile::kDexNoIndex);
666 dex_file_ = dex_file;
667 class_def_index_ = class_def_index;
668 return true;
669 }
670
671 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
672
673 virtual bool EndClass() {
674 if (kIsDebugBuild) {
675 dex_file_ = nullptr;
676 class_def_index_ = DexFile::kDexNoIndex;
677 }
678 return true;
679 }
680
681 size_t GetOffset() const {
682 return offset_;
683 }
684
685 protected:
686 virtual ~DexMethodVisitor() { }
687
688 OatWriter* const writer_;
689
690 // The offset is usually advanced for each visited method by the derived class.
691 size_t offset_;
692
693 // The dex file and class def index are set in StartClass().
694 const DexFile* dex_file_;
695 size_t class_def_index_;
696};
697
698class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
699 public:
700 OatDexMethodVisitor(OatWriter* writer, size_t offset)
701 : DexMethodVisitor(writer, offset),
702 oat_class_index_(0u),
703 method_offsets_index_(0u) {
704 }
705
706 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
707 DexMethodVisitor::StartClass(dex_file, class_def_index);
708 DCHECK_LT(oat_class_index_, writer_->oat_classes_.size());
709 method_offsets_index_ = 0u;
710 return true;
711 }
712
713 bool EndClass() {
714 ++oat_class_index_;
715 return DexMethodVisitor::EndClass();
716 }
717
718 protected:
719 size_t oat_class_index_;
720 size_t method_offsets_index_;
721};
722
723class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
724 public:
725 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
726 : DexMethodVisitor(writer, offset),
727 compiled_methods_(),
728 num_non_null_compiled_methods_(0u) {
729 compiled_methods_.reserve(256u);
730 }
731
732 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
733 DexMethodVisitor::StartClass(dex_file, class_def_index);
734 compiled_methods_.clear();
735 num_non_null_compiled_methods_ = 0u;
736 return true;
737 }
738
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700739 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED, const ClassDataItemIterator& it) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100740 // Fill in the compiled_methods_ array for methods that have a
741 // CompiledMethod. We track the number of non-null entries in
742 // num_non_null_compiled_methods_ since we only want to allocate
743 // OatMethodOffsets for the compiled methods.
744 uint32_t method_idx = it.GetMemberIndex();
745 CompiledMethod* compiled_method =
746 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
747 compiled_methods_.push_back(compiled_method);
748 if (compiled_method != nullptr) {
749 ++num_non_null_compiled_methods_;
750 }
751 return true;
752 }
753
754 bool EndClass() {
755 ClassReference class_ref(dex_file_, class_def_index_);
756 CompiledClass* compiled_class = writer_->compiler_driver_->GetCompiledClass(class_ref);
757 mirror::Class::Status status;
758 if (compiled_class != NULL) {
759 status = compiled_class->GetStatus();
760 } else if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
761 status = mirror::Class::kStatusError;
762 } else {
763 status = mirror::Class::kStatusNotReady;
764 }
765
766 OatClass* oat_class = new OatClass(offset_, compiled_methods_,
767 num_non_null_compiled_methods_, status);
768 writer_->oat_classes_.push_back(oat_class);
Vladimir Markof4da6752014-08-01 19:04:18 +0100769 oat_class->UpdateChecksum(writer_->oat_header_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100770 offset_ += oat_class->SizeOf();
771 return DexMethodVisitor::EndClass();
772 }
773
774 private:
775 std::vector<CompiledMethod*> compiled_methods_;
776 size_t num_non_null_compiled_methods_;
777};
778
779class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
780 public:
781 InitCodeMethodVisitor(OatWriter* writer, size_t offset)
782 : OatDexMethodVisitor(writer, offset) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100783 writer_->absolute_patch_locations_.reserve(
784 writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
785 }
786
787 bool EndClass() {
788 OatDexMethodVisitor::EndClass();
789 if (oat_class_index_ == writer_->oat_classes_.size()) {
Vladimir Marko20f85592015-03-19 10:07:02 +0000790 offset_ = writer_->relative_patcher_->ReserveSpace(offset_, nullptr);
Vladimir Markof4da6752014-08-01 19:04:18 +0100791 }
792 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100793 }
794
795 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
796 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
797 OatClass* oat_class = writer_->oat_classes_[oat_class_index_];
798 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
799
800 if (compiled_method != nullptr) {
801 // Derived from CompiledMethod.
802 uint32_t quick_code_offset = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100803
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800804 const SwapVector<uint8_t>* quick_code = compiled_method->GetQuickCode();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800805 CHECK(quick_code != nullptr);
Vladimir Marko20f85592015-03-19 10:07:02 +0000806 offset_ = writer_->relative_patcher_->ReserveSpace(offset_, compiled_method);
Elliott Hughes956af0f2014-12-11 14:34:28 -0800807 offset_ = compiled_method->AlignCode(offset_);
808 DCHECK_ALIGNED_PARAM(offset_,
809 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
810 uint32_t code_size = quick_code->size() * sizeof(uint8_t);
811 CHECK_NE(code_size, 0U);
812 uint32_t thumb_offset = compiled_method->CodeDelta();
813 quick_code_offset = offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
814
815 bool deduped = false;
816
817 // Deduplicate code arrays.
818 auto lb = dedupe_map_.lower_bound(compiled_method);
819 if (lb != dedupe_map_.end() && !dedupe_map_.key_comp()(compiled_method, lb->first)) {
820 quick_code_offset = lb->second;
821 deduped = true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100822 } else {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800823 dedupe_map_.PutBefore(lb, compiled_method, quick_code_offset);
824 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100825
Elliott Hughes956af0f2014-12-11 14:34:28 -0800826 MethodReference method_ref(dex_file_, it.GetMemberIndex());
827 auto method_lb = writer_->method_offset_map_.lower_bound(method_ref);
828 if (method_lb != writer_->method_offset_map_.end() &&
829 !writer_->method_offset_map_.key_comp()(method_ref, method_lb->first)) {
830 // TODO: Should this be a hard failure?
831 LOG(WARNING) << "Multiple definitions of "
832 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file)
833 << ((method_lb->second != quick_code_offset) ? "; OFFSET MISMATCH" : "");
834 } else {
835 writer_->method_offset_map_.PutBefore(method_lb, method_ref, quick_code_offset);
836 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100837
Elliott Hughes956af0f2014-12-11 14:34:28 -0800838 // Update quick method header.
839 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
840 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
841 uint32_t mapping_table_offset = method_header->mapping_table_offset_;
842 uint32_t vmap_table_offset = method_header->vmap_table_offset_;
843 uint32_t gc_map_offset = method_header->gc_map_offset_;
844 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
845 // to 0-offset and we need to adjust it by code_offset.
846 uint32_t code_offset = quick_code_offset - thumb_offset;
847 if (mapping_table_offset != 0u) {
848 mapping_table_offset += code_offset;
849 DCHECK_LT(mapping_table_offset, code_offset);
850 }
851 if (vmap_table_offset != 0u) {
852 vmap_table_offset += code_offset;
853 DCHECK_LT(vmap_table_offset, code_offset);
854 }
855 if (gc_map_offset != 0u) {
856 gc_map_offset += code_offset;
857 DCHECK_LT(gc_map_offset, code_offset);
858 }
859 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
860 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
861 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
862 *method_header = OatQuickMethodHeader(mapping_table_offset, vmap_table_offset,
863 gc_map_offset, frame_size_in_bytes, core_spill_mask,
864 fp_spill_mask, code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +0100865
Elliott Hughes956af0f2014-12-11 14:34:28 -0800866 if (!deduped) {
867 // Update offsets. (Checksum is updated when writing.)
868 offset_ += sizeof(*method_header); // Method header is prepended before code.
869 offset_ += code_size;
870 // Record absolute patch locations.
871 if (!compiled_method->GetPatches().empty()) {
872 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
873 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
Vladimir Marko20f85592015-03-19 10:07:02 +0000874 if (!patch.IsPcRelative()) {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800875 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +0100876 }
877 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100878 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800879 }
Alex Light78382fa2014-06-06 15:45:32 -0700880
Elliott Hughes956af0f2014-12-11 14:34:28 -0800881 if (writer_->compiler_driver_->GetCompilerOptions().GetIncludeDebugSymbols()) {
882 // Record debug information for this function if we are doing that.
Alex Light78382fa2014-06-06 15:45:32 -0700883
Elliott Hughes956af0f2014-12-11 14:34:28 -0800884 std::string name = PrettyMethod(it.GetMemberIndex(), *dex_file_, true);
885 if (deduped) {
886 // TODO We should place the DEDUPED tag on the first instance of a deduplicated symbol
887 // so that it will show up in a debuggerd crash report.
888 name += " [ DEDUPED ]";
Alex Light78382fa2014-06-06 15:45:32 -0700889 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800890
891 const uint32_t quick_code_start = quick_code_offset -
892 writer_->oat_header_->GetExecutableOffset();
893 const DexFile::CodeItem *code_item = it.GetMethodCodeItem();
894 writer_->method_info_.push_back(DebugInfo(name,
895 dex_file_->GetSourceFile(dex_file_->GetClassDef(class_def_index_)),
896 quick_code_start, quick_code_start + code_size,
897 code_item == nullptr ? nullptr : dex_file_->GetDebugInfoStream(code_item),
898 compiled_method));
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100899 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100900
901 if (kIsDebugBuild) {
902 // We expect GC maps except when the class hasn't been verified or the method is native.
903 const CompilerDriver* compiler_driver = writer_->compiler_driver_;
904 ClassReference class_ref(dex_file_, class_def_index_);
905 CompiledClass* compiled_class = compiler_driver->GetCompiledClass(class_ref);
906 mirror::Class::Status status;
907 if (compiled_class != NULL) {
908 status = compiled_class->GetStatus();
909 } else if (compiler_driver->GetVerificationResults()->IsClassRejected(class_ref)) {
910 status = mirror::Class::kStatusError;
911 } else {
912 status = mirror::Class::kStatusNotReady;
913 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800914 const SwapVector<uint8_t>* gc_map = compiled_method->GetGcMap();
Nicolas Geoffray39468442014-09-02 15:17:15 +0100915 if (gc_map != nullptr) {
916 size_t gc_map_size = gc_map->size() * sizeof(gc_map[0]);
Andreas Gampe51829322014-08-25 15:05:04 -0700917 bool is_native = it.MemberIsNative();
Nicolas Geoffray39468442014-09-02 15:17:15 +0100918 CHECK(gc_map_size != 0 || is_native || status < mirror::Class::kStatusVerified)
919 << gc_map << " " << gc_map_size << " " << (is_native ? "true" : "false") << " "
920 << (status < mirror::Class::kStatusVerified) << " " << status << " "
921 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
922 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100923 }
924
925 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
926 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
927 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100928 ++method_offsets_index_;
929 }
930
931 return true;
932 }
933
934 private:
Vladimir Marko20f85592015-03-19 10:07:02 +0000935 struct CodeOffsetsKeyComparator {
936 bool operator()(const CompiledMethod* lhs, const CompiledMethod* rhs) const {
937 if (lhs->GetQuickCode() != rhs->GetQuickCode()) {
938 return lhs->GetQuickCode() < rhs->GetQuickCode();
939 }
940 // If the code is the same, all other fields are likely to be the same as well.
941 if (UNLIKELY(lhs->GetMappingTable() != rhs->GetMappingTable())) {
942 return lhs->GetMappingTable() < rhs->GetMappingTable();
943 }
944 if (UNLIKELY(lhs->GetVmapTable() != rhs->GetVmapTable())) {
945 return lhs->GetVmapTable() < rhs->GetVmapTable();
946 }
947 if (UNLIKELY(lhs->GetGcMap() != rhs->GetGcMap())) {
948 return lhs->GetGcMap() < rhs->GetGcMap();
949 }
950 const auto& lhs_patches = lhs->GetPatches();
951 const auto& rhs_patches = rhs->GetPatches();
952 if (UNLIKELY(lhs_patches.size() != rhs_patches.size())) {
953 return lhs_patches.size() < rhs_patches.size();
954 }
955 auto rit = rhs_patches.begin();
956 for (const LinkerPatch& lpatch : lhs_patches) {
957 if (UNLIKELY(!(lpatch == *rit))) {
958 return lpatch < *rit;
959 }
960 ++rit;
961 }
962 return false;
963 }
964 };
965
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100966 // Deduplication is already done on a pointer basis by the compiler driver,
967 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +0100968 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100969};
970
971template <typename DataAccess>
972class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
973 public:
974 InitMapMethodVisitor(OatWriter* writer, size_t offset)
975 : OatDexMethodVisitor(writer, offset) {
976 }
977
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700978 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100979 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
980 OatClass* oat_class = writer_->oat_classes_[oat_class_index_];
981 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
982
983 if (compiled_method != nullptr) {
984 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
985 DCHECK_EQ(DataAccess::GetOffset(oat_class, method_offsets_index_), 0u);
986
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800987 const SwapVector<uint8_t>* map = DataAccess::GetData(compiled_method);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100988 uint32_t map_size = map == nullptr ? 0 : map->size() * sizeof((*map)[0]);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100989 if (map_size != 0u) {
Vladimir Markobd72fc12014-07-09 16:06:40 +0100990 auto lb = dedupe_map_.lower_bound(map);
991 if (lb != dedupe_map_.end() && !dedupe_map_.key_comp()(map, lb->first)) {
992 DataAccess::SetOffset(oat_class, method_offsets_index_, lb->second);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100993 } else {
994 DataAccess::SetOffset(oat_class, method_offsets_index_, offset_);
Vladimir Markobd72fc12014-07-09 16:06:40 +0100995 dedupe_map_.PutBefore(lb, map, offset_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100996 offset_ += map_size;
997 writer_->oat_header_->UpdateChecksum(&(*map)[0], map_size);
998 }
999 }
1000 ++method_offsets_index_;
1001 }
1002
1003 return true;
1004 }
1005
1006 private:
1007 // Deduplication is already done on a pointer basis by the compiler driver,
1008 // so we can simply compare the pointers to find out if things are duplicated.
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001009 SafeMap<const SwapVector<uint8_t>*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001010};
1011
1012class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
1013 public:
1014 InitImageMethodVisitor(OatWriter* writer, size_t offset)
Jeff Haoc7d11882015-02-03 15:08:39 -08001015 : OatDexMethodVisitor(writer, offset),
1016 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001017 }
1018
1019 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
1020 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1021 OatClass* oat_class = writer_->oat_classes_[oat_class_index_];
1022 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1023
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001024 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001025 if (compiled_method != nullptr) {
1026 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
1027 offsets = oat_class->method_offsets_[method_offsets_index_];
1028 ++method_offsets_index_;
1029 }
1030
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001031 ClassLinker* linker = Runtime::Current()->GetClassLinker();
1032 InvokeType invoke_type = it.GetMethodInvokeType(dex_file_->GetClassDef(class_def_index_));
1033 // Unchecked as we hold mutator_lock_ on entry.
1034 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001035 StackHandleScope<1> hs(soa.Self());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -07001036 Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(*dex_file_)));
Vladimir Marko7624d252014-05-02 14:40:15 +01001037 mirror::ArtMethod* method = linker->ResolveMethod(*dex_file_, it.GetMemberIndex(), dex_cache,
Mathieu Chartier0cd81352014-05-22 16:48:55 -07001038 NullHandle<mirror::ClassLoader>(),
1039 NullHandle<mirror::ArtMethod>(),
1040 invoke_type);
Andreas Gamped9efea62014-07-21 22:56:08 -07001041 if (method == nullptr) {
1042 LOG(ERROR) << "Unexpected failure to resolve a method: "
1043 << PrettyMethod(it.GetMemberIndex(), *dex_file_, true);
1044 soa.Self()->AssertPendingException();
Nicolas Geoffray14691c52015-03-05 10:40:17 +00001045 mirror::Throwable* exc = soa.Self()->GetException();
Andreas Gamped9efea62014-07-21 22:56:08 -07001046 std::string dump = exc->Dump();
1047 LOG(FATAL) << dump;
1048 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001049 method->SetEntryPointFromQuickCompiledCodePtrSize(reinterpret_cast<void*>(offsets.code_offset_),
1050 pointer_size_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001051
1052 return true;
1053 }
Jeff Haoc7d11882015-02-03 15:08:39 -08001054
1055 protected:
1056 const size_t pointer_size_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001057};
1058
1059class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
1060 public:
1061 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +01001062 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001063 : OatDexMethodVisitor(writer, relative_offset),
1064 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +01001065 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001066 soa_(Thread::Current()),
1067 no_thread_suspension_(soa_.Self(), "OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +01001068 class_linker_(Runtime::Current()->GetClassLinker()),
1069 dex_cache_(nullptr) {
1070 if (writer_->image_writer_ != nullptr) {
1071 // If we're creating the image, the address space must be ready so that we can apply patches.
1072 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
1073 patched_code_.reserve(16 * KB);
1074 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001075 }
1076
Vladimir Markof4da6752014-08-01 19:04:18 +01001077 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001078 }
1079
1080 bool StartClass(const DexFile* dex_file, size_t class_def_index)
1081 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1082 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
1083 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
1084 dex_cache_ = class_linker_->FindDexCache(*dex_file);
1085 }
1086 return true;
1087 }
1088
1089 bool EndClass() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1090 bool result = OatDexMethodVisitor::EndClass();
1091 if (oat_class_index_ == writer_->oat_classes_.size()) {
1092 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
Vladimir Marko20f85592015-03-19 10:07:02 +00001093 offset_ = writer_->relative_patcher_->WriteThunks(out_, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001094 if (UNLIKELY(offset_ == 0u)) {
1095 PLOG(ERROR) << "Failed to write final relative call thunks";
1096 result = false;
1097 }
1098 }
1099 return result;
1100 }
1101
1102 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
1103 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001104 OatClass* oat_class = writer_->oat_classes_[oat_class_index_];
1105 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1106
1107 if (compiled_method != NULL) { // ie. not an abstract method
1108 size_t file_offset = file_offset_;
1109 OutputStream* out = out_;
1110
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001111 const SwapVector<uint8_t>* quick_code = compiled_method->GetQuickCode();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001112 if (quick_code != nullptr) {
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001113 // Need a wrapper if we create a copy for patching.
1114 ArrayRef<const uint8_t> wrapped(*quick_code);
1115
Vladimir Marko20f85592015-03-19 10:07:02 +00001116 offset_ = writer_->relative_patcher_->WriteThunks(out, offset_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001117 if (offset_ == 0u) {
1118 ReportWriteFailure("relative call thunk", it);
1119 return false;
1120 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001121 uint32_t aligned_offset = compiled_method->AlignCode(offset_);
1122 uint32_t aligned_code_delta = aligned_offset - offset_;
1123 if (aligned_code_delta != 0) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001124 if (!writer_->WriteCodeAlignment(out, aligned_code_delta)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001125 ReportWriteFailure("code alignment padding", it);
1126 return false;
1127 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001128 offset_ += aligned_code_delta;
1129 DCHECK_OFFSET_();
1130 }
1131 DCHECK_ALIGNED_PARAM(offset_,
1132 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1133 uint32_t code_size = quick_code->size() * sizeof(uint8_t);
1134 CHECK_NE(code_size, 0U);
1135
1136 // Deduplicate code arrays.
1137 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
1138 DCHECK(method_offsets.code_offset_ < offset_ || method_offsets.code_offset_ ==
Vladimir Marko7624d252014-05-02 14:40:15 +01001139 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001140 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1141 if (method_offsets.code_offset_ >= offset_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001142 const OatQuickMethodHeader& method_header =
1143 oat_class->method_headers_[method_offsets_index_];
1144 writer_->oat_header_->UpdateChecksum(&method_header, sizeof(method_header));
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001145 if (!out->WriteFully(&method_header, sizeof(method_header))) {
1146 ReportWriteFailure("method header", it);
1147 return false;
1148 }
1149 writer_->size_method_header_ += sizeof(method_header);
1150 offset_ += sizeof(method_header);
1151 DCHECK_OFFSET_();
Vladimir Markof4da6752014-08-01 19:04:18 +01001152
1153 if (!compiled_method->GetPatches().empty()) {
Vladimir Marko20f85592015-03-19 10:07:02 +00001154 patched_code_.assign(quick_code->begin(), quick_code->end());
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001155 wrapped = ArrayRef<const uint8_t>(patched_code_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001156 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
1157 if (patch.Type() == kLinkerPatchCallRelative) {
1158 // NOTE: Relative calls across oat files are not supported.
1159 uint32_t target_offset = GetTargetOffset(patch);
1160 uint32_t literal_offset = patch.LiteralOffset();
Vladimir Marko20f85592015-03-19 10:07:02 +00001161 writer_->relative_patcher_->PatchCall(&patched_code_, literal_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +01001162 offset_ + literal_offset, target_offset);
Vladimir Marko20f85592015-03-19 10:07:02 +00001163 } else if (patch.Type() == kLinkerPatchDexCacheArray) {
1164 uint32_t target_offset = GetDexCacheOffset(patch);
1165 uint32_t literal_offset = patch.LiteralOffset();
1166 writer_->relative_patcher_->PatchDexCacheReference(&patched_code_, patch,
1167 offset_ + literal_offset,
1168 target_offset);
Vladimir Markof4da6752014-08-01 19:04:18 +01001169 } else if (patch.Type() == kLinkerPatchCall) {
1170 uint32_t target_offset = GetTargetOffset(patch);
1171 PatchCodeAddress(&patched_code_, patch.LiteralOffset(), target_offset);
1172 } else if (patch.Type() == kLinkerPatchMethod) {
1173 mirror::ArtMethod* method = GetTargetMethod(patch);
1174 PatchObjectAddress(&patched_code_, patch.LiteralOffset(), method);
1175 } else if (patch.Type() == kLinkerPatchType) {
1176 mirror::Class* type = GetTargetType(patch);
1177 PatchObjectAddress(&patched_code_, patch.LiteralOffset(), type);
1178 }
1179 }
1180 }
1181
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001182 writer_->oat_header_->UpdateChecksum(wrapped.data(), code_size);
1183 if (!out->WriteFully(wrapped.data(), code_size)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001184 ReportWriteFailure("method code", it);
1185 return false;
1186 }
1187 writer_->size_code_ += code_size;
1188 offset_ += code_size;
1189 }
1190 DCHECK_OFFSET_();
1191 }
1192 ++method_offsets_index_;
1193 }
1194
1195 return true;
1196 }
1197
1198 private:
1199 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001200 const size_t file_offset_;
1201 const ScopedObjectAccess soa_;
1202 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001203 ClassLinker* const class_linker_;
1204 mirror::DexCache* dex_cache_;
1205 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001206
1207 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1208 PLOG(ERROR) << "Failed to write " << what << " for "
1209 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1210 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001211
1212 mirror::ArtMethod* GetTargetMethod(const LinkerPatch& patch)
1213 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1214 MethodReference ref = patch.TargetMethod();
1215 mirror::DexCache* dex_cache =
1216 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(*ref.dex_file);
1217 mirror::ArtMethod* method = dex_cache->GetResolvedMethod(ref.dex_method_index);
1218 CHECK(method != nullptr);
1219 return method;
1220 }
1221
1222 uint32_t GetTargetOffset(const LinkerPatch& patch) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1223 auto target_it = writer_->method_offset_map_.find(patch.TargetMethod());
1224 uint32_t target_offset =
1225 (target_it != writer_->method_offset_map_.end()) ? target_it->second : 0u;
1226 // If there's no compiled code, point to the correct trampoline.
1227 if (UNLIKELY(target_offset == 0)) {
1228 mirror::ArtMethod* target = GetTargetMethod(patch);
1229 DCHECK(target != nullptr);
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001230 size_t size = GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet());
1231 const void* oat_code_offset = target->GetEntryPointFromQuickCompiledCodePtrSize(size);
1232 if (oat_code_offset != 0) {
1233 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1234 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1235 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1236 target_offset = PointerToLowMemUInt32(oat_code_offset);
1237 } else {
1238 target_offset = target->IsNative()
1239 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1240 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1241 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001242 }
1243 return target_offset;
1244 }
1245
1246 mirror::Class* GetTargetType(const LinkerPatch& patch)
1247 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1248 mirror::DexCache* dex_cache = (dex_file_ == patch.TargetTypeDexFile())
1249 ? dex_cache_ : class_linker_->FindDexCache(*patch.TargetTypeDexFile());
1250 mirror::Class* type = dex_cache->GetResolvedType(patch.TargetTypeIndex());
1251 CHECK(type != nullptr);
1252 return type;
1253 }
1254
Vladimir Marko20f85592015-03-19 10:07:02 +00001255 uint32_t GetDexCacheOffset(const LinkerPatch& patch) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1256 if (writer_->image_writer_ != nullptr) {
1257 auto* element = writer_->image_writer_->GetDexCacheArrayElementImageAddress(
1258 patch.TargetDexCacheDexFile(), patch.TargetDexCacheElementOffset());
1259 const uint8_t* oat_data = writer_->image_writer_->GetOatFileBegin() + file_offset_;
1260 return reinterpret_cast<const uint8_t*>(element) - oat_data;
1261 } else {
1262 LOG(FATAL) << "Unimplemented.";
1263 UNREACHABLE();
1264 }
1265 }
1266
Vladimir Markof4da6752014-08-01 19:04:18 +01001267 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
1268 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1269 // NOTE: Direct method pointers across oat files don't use linker patches. However, direct
1270 // type pointers across oat files do. (TODO: Investigate why.)
1271 if (writer_->image_writer_ != nullptr) {
1272 object = writer_->image_writer_->GetImageAddress(object);
1273 }
1274 uint32_t address = PointerToLowMemUInt32(object);
1275 DCHECK_LE(offset + 4, code->size());
1276 uint8_t* data = &(*code)[offset];
1277 data[0] = address & 0xffu;
1278 data[1] = (address >> 8) & 0xffu;
1279 data[2] = (address >> 16) & 0xffu;
1280 data[3] = (address >> 24) & 0xffu;
1281 }
1282
1283 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
1284 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001285 uint32_t address = writer_->image_writer_ == nullptr ? target_offset :
1286 PointerToLowMemUInt32(writer_->image_writer_->GetOatFileBegin() +
1287 writer_->oat_data_offset_ + target_offset);
Vladimir Markof4da6752014-08-01 19:04:18 +01001288 DCHECK_LE(offset + 4, code->size());
1289 uint8_t* data = &(*code)[offset];
1290 data[0] = address & 0xffu;
1291 data[1] = (address >> 8) & 0xffu;
1292 data[2] = (address >> 16) & 0xffu;
1293 data[3] = (address >> 24) & 0xffu;
1294 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001295};
1296
1297template <typename DataAccess>
1298class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1299 public:
1300 WriteMapMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001301 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001302 : OatDexMethodVisitor(writer, relative_offset),
1303 out_(out),
1304 file_offset_(file_offset) {
1305 }
1306
1307 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
1308 OatClass* oat_class = writer_->oat_classes_[oat_class_index_];
1309 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1310
1311 if (compiled_method != NULL) { // ie. not an abstract method
1312 size_t file_offset = file_offset_;
1313 OutputStream* out = out_;
1314
1315 uint32_t map_offset = DataAccess::GetOffset(oat_class, method_offsets_index_);
1316 ++method_offsets_index_;
1317
1318 // Write deduplicated map.
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001319 const SwapVector<uint8_t>* map = DataAccess::GetData(compiled_method);
Nicolas Geoffray39468442014-09-02 15:17:15 +01001320 size_t map_size = map == nullptr ? 0 : map->size() * sizeof((*map)[0]);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001321 DCHECK((map_size == 0u && map_offset == 0u) ||
1322 (map_size != 0u && map_offset != 0u && map_offset <= offset_))
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001323 << map_size << " " << map_offset << " " << offset_ << " "
1324 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " for " << DataAccess::Name();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001325 if (map_size != 0u && map_offset == offset_) {
1326 if (UNLIKELY(!out->WriteFully(&(*map)[0], map_size))) {
1327 ReportWriteFailure(it);
1328 return false;
1329 }
1330 offset_ += map_size;
1331 }
1332 DCHECK_OFFSET_();
1333 }
1334
1335 return true;
1336 }
1337
1338 private:
1339 OutputStream* const out_;
1340 size_t const file_offset_;
1341
1342 void ReportWriteFailure(const ClassDataItemIterator& it) {
1343 PLOG(ERROR) << "Failed to write " << DataAccess::Name() << " for "
1344 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1345 }
1346};
1347
1348// Visit all methods from all classes in all dex files with the specified visitor.
1349bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1350 for (const DexFile* dex_file : *dex_files_) {
1351 const size_t class_def_count = dex_file->NumClassDefs();
1352 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1353 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1354 return false;
1355 }
1356 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -07001357 const uint8_t* class_data = dex_file->GetClassData(class_def);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001358 if (class_data != NULL) { // ie not an empty class, such as a marker interface
1359 ClassDataItemIterator it(*dex_file, class_data);
1360 while (it.HasNextStaticField()) {
1361 it.Next();
1362 }
1363 while (it.HasNextInstanceField()) {
1364 it.Next();
1365 }
1366 size_t class_def_method_index = 0u;
1367 while (it.HasNextDirectMethod()) {
1368 if (!visitor->VisitMethod(class_def_method_index, it)) {
1369 return false;
1370 }
1371 ++class_def_method_index;
1372 it.Next();
1373 }
1374 while (it.HasNextVirtualMethod()) {
1375 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1376 return false;
1377 }
1378 ++class_def_method_index;
1379 it.Next();
1380 }
1381 }
1382 if (UNLIKELY(!visitor->EndClass())) {
1383 return false;
1384 }
1385 }
1386 }
1387 return true;
1388}
1389
Brian Carlstrom81f3ca12012-03-17 00:27:35 -07001390size_t OatWriter::InitOatHeader() {
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001391 oat_header_ = OatHeader::Create(compiler_driver_->GetInstructionSet(),
1392 compiler_driver_->GetInstructionSetFeatures(),
1393 dex_files_,
1394 image_file_location_oat_checksum_,
1395 image_file_location_oat_begin_,
1396 key_value_store_);
1397
1398 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001399}
1400
1401size_t OatWriter::InitOatDexFiles(size_t offset) {
1402 // create the OatDexFiles
1403 for (size_t i = 0; i != dex_files_->size(); ++i) {
1404 const DexFile* dex_file = (*dex_files_)[i];
1405 CHECK(dex_file != NULL);
Brian Carlstrom265091e2013-01-30 14:08:26 -08001406 OatDexFile* oat_dex_file = new OatDexFile(offset, *dex_file);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001407 oat_dex_files_.push_back(oat_dex_file);
1408 offset += oat_dex_file->SizeOf();
1409 }
1410 return offset;
1411}
1412
Brian Carlstrom89521892011-12-07 22:05:07 -08001413size_t OatWriter::InitDexFiles(size_t offset) {
1414 // calculate the offsets within OatDexFiles to the DexFiles
1415 for (size_t i = 0; i != dex_files_->size(); ++i) {
1416 // dex files are required to be 4 byte aligned
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001417 size_t original_offset = offset;
Brian Carlstrom89521892011-12-07 22:05:07 -08001418 offset = RoundUp(offset, 4);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001419 size_dex_file_alignment_ += offset - original_offset;
Brian Carlstrom89521892011-12-07 22:05:07 -08001420
1421 // set offset in OatDexFile to DexFile
1422 oat_dex_files_[i]->dex_file_offset_ = offset;
1423
1424 const DexFile* dex_file = (*dex_files_)[i];
1425 offset += dex_file->GetHeader().file_size_;
1426 }
1427 return offset;
1428}
1429
Brian Carlstrom389efb02012-01-11 12:06:26 -08001430size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001431 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001432 InitOatClassesMethodVisitor visitor(this, offset);
1433 bool success = VisitDexMethods(&visitor);
1434 CHECK(success);
1435 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001436
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001437 // Update oat_dex_files_.
1438 auto oat_class_it = oat_classes_.begin();
1439 for (OatDexFile* oat_dex_file : oat_dex_files_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001440 for (uint32_t& method_offset : oat_dex_file->methods_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001441 DCHECK(oat_class_it != oat_classes_.end());
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001442 method_offset = (*oat_class_it)->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001443 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001444 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001445 oat_dex_file->UpdateChecksum(oat_header_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001446 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001447 CHECK(oat_class_it == oat_classes_.end());
1448
1449 return offset;
1450}
1451
1452size_t OatWriter::InitOatMaps(size_t offset) {
1453 #define VISIT(VisitorType) \
1454 do { \
1455 VisitorType visitor(this, offset); \
1456 bool success = VisitDexMethods(&visitor); \
1457 DCHECK(success); \
1458 offset = visitor.GetOffset(); \
1459 } while (false)
1460
1461 VISIT(InitMapMethodVisitor<GcMapDataAccess>);
1462 VISIT(InitMapMethodVisitor<MappingTableDataAccess>);
1463 VISIT(InitMapMethodVisitor<VmapTableDataAccess>);
1464
1465 #undef VISIT
1466
Brian Carlstrome24fa612011-09-29 00:53:55 -07001467 return offset;
1468}
1469
1470size_t OatWriter::InitOatCode(size_t offset) {
1471 // calculate the offsets within OatHeader to executable code
1472 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001473 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001474 // required to be on a new page boundary
1475 offset = RoundUp(offset, kPageSize);
1476 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001477 size_executable_offset_alignment_ = offset - old_offset;
1478 if (compiler_driver_->IsImage()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001479 CHECK_EQ(image_patch_delta_, 0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001480 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001481
Ian Rogers848871b2013-08-05 10:56:33 -07001482 #define DO_TRAMPOLINE(field, fn_name) \
1483 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001484 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1485 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Ian Rogers848871b2013-08-05 10:56:33 -07001486 field.reset(compiler_driver_->Create ## fn_name()); \
1487 offset += field->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001488
Ian Rogers848871b2013-08-05 10:56:33 -07001489 DO_TRAMPOLINE(interpreter_to_interpreter_bridge_, InterpreterToInterpreterBridge);
1490 DO_TRAMPOLINE(interpreter_to_compiled_code_bridge_, InterpreterToCompiledCodeBridge);
1491 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001492 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001493 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001494 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1495 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001496
Ian Rogers848871b2013-08-05 10:56:33 -07001497 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001498 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001499 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1500 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1501 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001502 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001503 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001504 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001505 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Alex Lighta59dd802014-07-02 16:28:08 -07001506 oat_header_->SetImagePatchDelta(image_patch_delta_);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001507 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001508 return offset;
1509}
1510
1511size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001512 #define VISIT(VisitorType) \
1513 do { \
1514 VisitorType visitor(this, offset); \
1515 bool success = VisitDexMethods(&visitor); \
1516 DCHECK(success); \
1517 offset = visitor.GetOffset(); \
1518 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001519
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001520 VISIT(InitCodeMethodVisitor);
Ian Rogers1212a022013-03-04 10:48:41 -08001521 if (compiler_driver_->IsImage()) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001522 VISIT(InitImageMethodVisitor);
Ian Rogers0571d352011-11-03 19:51:38 -07001523 }
Logan Chien8b977d32012-02-21 19:14:55 +08001524
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001525 #undef VISIT
1526
Brian Carlstrome24fa612011-09-29 00:53:55 -07001527 return offset;
1528}
1529
Ian Rogers3d504072014-03-01 09:16:49 -08001530bool OatWriter::Write(OutputStream* out) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001531 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
1532 if (raw_file_offset == (off_t) -1) {
1533 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
1534 return false;
1535 }
1536 const size_t file_offset = static_cast<size_t>(raw_file_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001537
Vladimir Markof4da6752014-08-01 19:04:18 +01001538 // Reserve space for header. It will be written last - after updating the checksum.
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001539 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Markof4da6752014-08-01 19:04:18 +01001540 if (out->Seek(header_size, kSeekCurrent) == (off_t) -1) {
1541 PLOG(ERROR) << "Failed to reserve space for oat header in " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001542 return false;
1543 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001544 size_oat_header_ += sizeof(OatHeader);
1545 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Brian Carlstrom81f3ca12012-03-17 00:27:35 -07001546
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001547 if (!WriteTables(out, file_offset)) {
Ian Rogers3d504072014-03-01 09:16:49 -08001548 LOG(ERROR) << "Failed to write oat tables to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001549 return false;
1550 }
1551
Vladimir Markof4da6752014-08-01 19:04:18 +01001552 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
1553 if (tables_end_offset == (off_t) -1) {
1554 LOG(ERROR) << "Failed to seek to oat code position in " << out->GetLocation();
1555 return false;
1556 }
1557 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001558 relative_offset = WriteMaps(out, file_offset, relative_offset);
1559 if (relative_offset == 0) {
1560 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1561 return false;
1562 }
1563
1564 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001565 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001566 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001567 return false;
1568 }
1569
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001570 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1571 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001572 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001573 return false;
1574 }
1575
Vladimir Markof4da6752014-08-01 19:04:18 +01001576 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
1577 if (oat_end_file_offset == (off_t) -1) {
1578 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1579 return false;
1580 }
1581
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001582 if (kIsDebugBuild) {
1583 uint32_t size_total = 0;
1584 #define DO_STAT(x) \
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001585 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << x << "B)"; \
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001586 size_total += x;
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001587
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001588 DO_STAT(size_dex_file_alignment_);
1589 DO_STAT(size_executable_offset_alignment_);
1590 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001591 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001592 DO_STAT(size_dex_file_);
Ian Rogers848871b2013-08-05 10:56:33 -07001593 DO_STAT(size_interpreter_to_interpreter_bridge_);
1594 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1595 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001596 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001597 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001598 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001599 DO_STAT(size_quick_to_interpreter_bridge_);
1600 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001601 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001602 DO_STAT(size_code_);
1603 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001604 DO_STAT(size_relative_call_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001605 DO_STAT(size_mapping_table_);
1606 DO_STAT(size_vmap_table_);
1607 DO_STAT(size_gc_map_);
1608 DO_STAT(size_oat_dex_file_location_size_);
1609 DO_STAT(size_oat_dex_file_location_data_);
1610 DO_STAT(size_oat_dex_file_location_checksum_);
1611 DO_STAT(size_oat_dex_file_offset_);
1612 DO_STAT(size_oat_dex_file_methods_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001613 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001614 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001615 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001616 DO_STAT(size_oat_class_method_offsets_);
1617 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001618
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001619 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)"; \
Vladimir Markof4da6752014-08-01 19:04:18 +01001620 CHECK_EQ(file_offset + size_total, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001621 CHECK_EQ(size_, size_total);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001622 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001623
Vladimir Markof4da6752014-08-01 19:04:18 +01001624 CHECK_EQ(file_offset + size_, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001625 CHECK_EQ(size_, relative_offset);
1626
Vladimir Markof4da6752014-08-01 19:04:18 +01001627 // Write the header now that the checksum is final.
1628 if (out->Seek(file_offset, kSeekSet) == (off_t) -1) {
1629 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1630 return false;
1631 }
1632 DCHECK_EQ(raw_file_offset, out->Seek(0, kSeekCurrent));
1633 if (!out->WriteFully(oat_header_, header_size)) {
1634 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1635 return false;
1636 }
1637 if (out->Seek(oat_end_file_offset, kSeekSet) == (off_t) -1) {
1638 PLOG(ERROR) << "Failed to seek to end after writing oat header to " << out->GetLocation();
1639 return false;
1640 }
1641 DCHECK_EQ(oat_end_file_offset, out->Seek(0, kSeekCurrent));
1642
Brian Carlstrome24fa612011-09-29 00:53:55 -07001643 return true;
1644}
1645
Ian Rogers3d504072014-03-01 09:16:49 -08001646bool OatWriter::WriteTables(OutputStream* out, const size_t file_offset) {
Brian Carlstrome24fa612011-09-29 00:53:55 -07001647 for (size_t i = 0; i != oat_dex_files_.size(); ++i) {
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001648 if (!oat_dex_files_[i]->Write(this, out, file_offset)) {
Ian Rogers3d504072014-03-01 09:16:49 -08001649 PLOG(ERROR) << "Failed to write oat dex information to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001650 return false;
1651 }
1652 }
Brian Carlstrom89521892011-12-07 22:05:07 -08001653 for (size_t i = 0; i != oat_dex_files_.size(); ++i) {
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001654 uint32_t expected_offset = file_offset + oat_dex_files_[i]->dex_file_offset_;
Ian Rogers3d504072014-03-01 09:16:49 -08001655 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
Brian Carlstrom89521892011-12-07 22:05:07 -08001656 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
1657 const DexFile* dex_file = (*dex_files_)[i];
1658 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
1659 << " Expected: " << expected_offset << " File: " << dex_file->GetLocation();
1660 return false;
1661 }
1662 const DexFile* dex_file = (*dex_files_)[i];
Ian Rogers3d504072014-03-01 09:16:49 -08001663 if (!out->WriteFully(&dex_file->GetHeader(), dex_file->GetHeader().file_size_)) {
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001664 PLOG(ERROR) << "Failed to write dex file " << dex_file->GetLocation()
Ian Rogers3d504072014-03-01 09:16:49 -08001665 << " to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08001666 return false;
1667 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001668 size_dex_file_ += dex_file->GetHeader().file_size_;
Brian Carlstrom89521892011-12-07 22:05:07 -08001669 }
Brian Carlstrom389efb02012-01-11 12:06:26 -08001670 for (size_t i = 0; i != oat_classes_.size(); ++i) {
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001671 if (!oat_classes_[i]->Write(this, out, file_offset)) {
Ian Rogers3d504072014-03-01 09:16:49 -08001672 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001673 return false;
1674 }
1675 }
1676 return true;
1677}
1678
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001679size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
1680 #define VISIT(VisitorType) \
1681 do { \
1682 VisitorType visitor(this, out, file_offset, relative_offset); \
1683 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1684 return 0; \
1685 } \
1686 relative_offset = visitor.GetOffset(); \
1687 } while (false)
1688
1689 size_t gc_maps_offset = relative_offset;
1690 VISIT(WriteMapMethodVisitor<GcMapDataAccess>);
1691 size_gc_map_ = relative_offset - gc_maps_offset;
1692
1693 size_t mapping_tables_offset = relative_offset;
1694 VISIT(WriteMapMethodVisitor<MappingTableDataAccess>);
1695 size_mapping_table_ = relative_offset - mapping_tables_offset;
1696
1697 size_t vmap_tables_offset = relative_offset;
1698 VISIT(WriteMapMethodVisitor<VmapTableDataAccess>);
1699 size_vmap_table_ = relative_offset - vmap_tables_offset;
1700
1701 #undef VISIT
1702
1703 return relative_offset;
1704}
1705
1706size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Ian Rogers3d504072014-03-01 09:16:49 -08001707 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001708 relative_offset += size_executable_offset_alignment_;
1709 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001710 size_t expected_file_offset = file_offset + relative_offset;
1711 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001712 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
Ian Rogers3d504072014-03-01 09:16:49 -08001713 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001714 return 0;
1715 }
Brian Carlstrom265091e2013-01-30 14:08:26 -08001716 DCHECK_OFFSET();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001717 if (compiler_driver_->IsImage()) {
1718 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001719
Ian Rogers848871b2013-08-05 10:56:33 -07001720 #define DO_TRAMPOLINE(field) \
1721 do { \
1722 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
1723 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08001724 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07001725 size_trampoline_alignment_ += alignment_padding; \
Ian Rogers3d504072014-03-01 09:16:49 -08001726 if (!out->WriteFully(&(*field)[0], field->size())) { \
1727 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001728 return false; \
1729 } \
1730 size_ ## field += field->size(); \
1731 relative_offset += alignment_padding + field->size(); \
1732 DCHECK_OFFSET(); \
1733 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001734
Ian Rogers848871b2013-08-05 10:56:33 -07001735 DO_TRAMPOLINE(interpreter_to_interpreter_bridge_);
1736 DO_TRAMPOLINE(interpreter_to_compiled_code_bridge_);
1737 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001738 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001739 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001740 DO_TRAMPOLINE(quick_resolution_trampoline_);
1741 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
1742 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001743 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001744 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001745}
1746
Ian Rogers3d504072014-03-01 09:16:49 -08001747size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001748 const size_t file_offset,
1749 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001750 #define VISIT(VisitorType) \
1751 do { \
1752 VisitorType visitor(this, out, file_offset, relative_offset); \
1753 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1754 return 0; \
1755 } \
1756 relative_offset = visitor.GetOffset(); \
1757 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001758
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001759 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001760
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001761 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08001762
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001763 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001764}
1765
Vladimir Markof4da6752014-08-01 19:04:18 +01001766bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
1767 static const uint8_t kPadding[] = {
1768 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
1769 };
1770 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
1771 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
1772 return false;
1773 }
1774 size_code_alignment_ += aligned_code_delta;
1775 return true;
1776}
1777
Brian Carlstrom265091e2013-01-30 14:08:26 -08001778OatWriter::OatDexFile::OatDexFile(size_t offset, const DexFile& dex_file) {
1779 offset_ = offset;
Elliott Hughes95572412011-12-13 18:14:20 -08001780 const std::string& location(dex_file.GetLocation());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001781 dex_file_location_size_ = location.size();
1782 dex_file_location_data_ = reinterpret_cast<const uint8_t*>(location.data());
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001783 dex_file_location_checksum_ = dex_file.GetLocationChecksum();
Brian Carlstrom89521892011-12-07 22:05:07 -08001784 dex_file_offset_ = 0;
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -08001785 methods_offsets_.resize(dex_file.NumClassDefs());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001786}
1787
1788size_t OatWriter::OatDexFile::SizeOf() const {
1789 return sizeof(dex_file_location_size_)
1790 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001791 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08001792 + sizeof(dex_file_offset_)
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -08001793 + (sizeof(methods_offsets_[0]) * methods_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001794}
1795
Ian Rogers3d504072014-03-01 09:16:49 -08001796void OatWriter::OatDexFile::UpdateChecksum(OatHeader* oat_header) const {
1797 oat_header->UpdateChecksum(&dex_file_location_size_, sizeof(dex_file_location_size_));
1798 oat_header->UpdateChecksum(dex_file_location_data_, dex_file_location_size_);
1799 oat_header->UpdateChecksum(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_));
1800 oat_header->UpdateChecksum(&dex_file_offset_, sizeof(dex_file_offset_));
1801 oat_header->UpdateChecksum(&methods_offsets_[0],
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -08001802 sizeof(methods_offsets_[0]) * methods_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001803}
1804
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001805bool OatWriter::OatDexFile::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08001806 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001807 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08001808 DCHECK_OFFSET_();
Ian Rogers3d504072014-03-01 09:16:49 -08001809 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
1810 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001811 return false;
1812 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001813 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Ian Rogers3d504072014-03-01 09:16:49 -08001814 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
1815 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001816 return false;
1817 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001818 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Ian Rogers3d504072014-03-01 09:16:49 -08001819 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
1820 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001821 return false;
1822 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001823 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Ian Rogers3d504072014-03-01 09:16:49 -08001824 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
1825 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08001826 return false;
1827 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001828 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Ian Rogers3d504072014-03-01 09:16:49 -08001829 if (!out->WriteFully(&methods_offsets_[0],
Brian Carlstromcd60ac72013-01-20 17:09:51 -08001830 sizeof(methods_offsets_[0]) * methods_offsets_.size())) {
Ian Rogers3d504072014-03-01 09:16:49 -08001831 PLOG(ERROR) << "Failed to write methods offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001832 return false;
1833 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001834 oat_writer->size_oat_dex_file_methods_offsets_ +=
1835 sizeof(methods_offsets_[0]) * methods_offsets_.size();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001836 return true;
1837}
1838
Brian Carlstromba150c32013-08-27 17:31:03 -07001839OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001840 const std::vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07001841 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001842 mirror::Class::Status status)
1843 : compiled_methods_(compiled_methods) {
1844 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07001845 CHECK_LE(num_non_null_compiled_methods, num_methods);
1846
Brian Carlstrom265091e2013-01-30 14:08:26 -08001847 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07001848 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
1849
1850 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
1851 // apply when there are 0 methods, we just arbitrarily say that 0
1852 // methods means kOatClassNoneCompiled and that we won't use
1853 // kOatClassAllCompiled unless there is at least one compiled
1854 // method. This means in an interpretter only system, we can assert
1855 // that all classes are kOatClassNoneCompiled.
1856 if (num_non_null_compiled_methods == 0) {
1857 type_ = kOatClassNoneCompiled;
1858 } else if (num_non_null_compiled_methods == num_methods) {
1859 type_ = kOatClassAllCompiled;
1860 } else {
1861 type_ = kOatClassSomeCompiled;
1862 }
1863
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001864 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07001865 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01001866 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07001867
1868 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
1869 if (type_ == kOatClassSomeCompiled) {
1870 method_bitmap_ = new BitVector(num_methods, false, Allocator::GetMallocAllocator());
1871 method_bitmap_size_ = method_bitmap_->GetSizeOf();
1872 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
1873 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
1874 } else {
1875 method_bitmap_ = NULL;
1876 method_bitmap_size_ = 0;
1877 }
1878
1879 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001880 CompiledMethod* compiled_method = compiled_methods_[i];
Brian Carlstromba150c32013-08-27 17:31:03 -07001881 if (compiled_method == NULL) {
1882 oat_method_offsets_offsets_from_oat_class_[i] = 0;
1883 } else {
1884 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
1885 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
1886 if (type_ == kOatClassSomeCompiled) {
1887 method_bitmap_->SetBit(i);
1888 }
1889 }
1890 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001891}
1892
Brian Carlstromba150c32013-08-27 17:31:03 -07001893OatWriter::OatClass::~OatClass() {
Mathieu Chartier661974a2014-01-09 11:23:53 -08001894 delete method_bitmap_;
Brian Carlstromba150c32013-08-27 17:31:03 -07001895}
1896
Brian Carlstrom265091e2013-01-30 14:08:26 -08001897size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
1898 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07001899 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
1900 if (method_offset == 0) {
1901 return 0;
1902 }
1903 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08001904}
1905
1906size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
1907 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07001908 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08001909}
1910
1911size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07001912 return sizeof(status_)
1913 + sizeof(type_)
1914 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
1915 + method_bitmap_size_
1916 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001917}
1918
Ian Rogers3d504072014-03-01 09:16:49 -08001919void OatWriter::OatClass::UpdateChecksum(OatHeader* oat_header) const {
1920 oat_header->UpdateChecksum(&status_, sizeof(status_));
1921 oat_header->UpdateChecksum(&type_, sizeof(type_));
Brian Carlstromba150c32013-08-27 17:31:03 -07001922 if (method_bitmap_size_ != 0) {
1923 CHECK_EQ(kOatClassSomeCompiled, type_);
Ian Rogers3d504072014-03-01 09:16:49 -08001924 oat_header->UpdateChecksum(&method_bitmap_size_, sizeof(method_bitmap_size_));
1925 oat_header->UpdateChecksum(method_bitmap_->GetRawStorage(), method_bitmap_size_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001926 }
Ian Rogers3d504072014-03-01 09:16:49 -08001927 oat_header->UpdateChecksum(&method_offsets_[0],
1928 sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001929}
1930
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001931bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08001932 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001933 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08001934 DCHECK_OFFSET_();
Ian Rogers3d504072014-03-01 09:16:49 -08001935 if (!out->WriteFully(&status_, sizeof(status_))) {
1936 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001937 return false;
1938 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001939 oat_writer->size_oat_class_status_ += sizeof(status_);
Ian Rogers3d504072014-03-01 09:16:49 -08001940 if (!out->WriteFully(&type_, sizeof(type_))) {
1941 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07001942 return false;
1943 }
1944 oat_writer->size_oat_class_type_ += sizeof(type_);
1945 if (method_bitmap_size_ != 0) {
1946 CHECK_EQ(kOatClassSomeCompiled, type_);
Ian Rogers3d504072014-03-01 09:16:49 -08001947 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
1948 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07001949 return false;
1950 }
1951 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Ian Rogers3d504072014-03-01 09:16:49 -08001952 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
1953 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07001954 return false;
1955 }
1956 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
1957 }
Ian Rogers3d504072014-03-01 09:16:49 -08001958 if (!out->WriteFully(&method_offsets_[0],
Brian Carlstromcd60ac72013-01-20 17:09:51 -08001959 sizeof(method_offsets_[0]) * method_offsets_.size())) {
Ian Rogers3d504072014-03-01 09:16:49 -08001960 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001961 return false;
1962 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001963 oat_writer->size_oat_class_method_offsets_ += sizeof(method_offsets_[0]) * method_offsets_.size();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001964 return true;
1965}
1966
Brian Carlstrome24fa612011-09-29 00:53:55 -07001967} // namespace art