blob: 841109105dd7eaf5ff0bb928f21a4803c8f43995 [file] [log] [blame]
Elliott Hughes2faa5f12012-01-30 14:42:07 -08001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Brian Carlstrome24fa612011-09-29 00:53:55 -070016
17#include "oat_writer.h"
18
Elliott Hughesa0e18062012-04-13 15:59:59 -070019#include <zlib.h>
20
Ian Rogerse77493c2014-08-20 15:08:45 -070021#include "base/allocator.h"
Brian Carlstromba150c32013-08-27 17:31:03 -070022#include "base/bit_vector.h"
Elliott Hughes1aa246d2012-12-13 09:29:36 -080023#include "base/stl_util.h"
Elliott Hughes76160052012-12-12 16:31:20 -080024#include "base/unix_file/fd_file.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070025#include "class_linker.h"
Mingyao Yang98d1cc82014-05-15 17:02:16 -070026#include "compiled_class.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070027#include "dex_file-inl.h"
Vladimir Markoc7f83202014-01-24 17:55:18 +000028#include "dex/verification_results.h"
Ian Rogers1d54e732013-05-02 21:10:01 -070029#include "gc/space/space.h"
Vladimir Markof4da6752014-08-01 19:04:18 +010030#include "image_writer.h"
Brian Carlstromea46f952013-07-30 01:26:50 -070031#include "mirror/art_method-inl.h"
Ian Rogers2dd0e2c2013-01-24 12:42:14 -080032#include "mirror/array.h"
33#include "mirror/class_loader.h"
Ian Rogers4f6ad8a2013-03-18 15:27:28 -070034#include "mirror/object-inl.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070035#include "os.h"
Brian Carlstromcd60ac72013-01-20 17:09:51 -080036#include "output_stream.h"
Elliott Hughesa0e18062012-04-13 15:59:59 -070037#include "safe_map.h"
Ian Rogers00f7d0e2012-07-19 15:28:27 -070038#include "scoped_thread_state_change.h"
Mathieu Chartiereb8167a2014-05-07 15:43:14 -070039#include "handle_scope-inl.h"
Vladimir Markof4da6752014-08-01 19:04:18 +010040#include "utils/arm/assembler_thumb2.h"
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +010041#include "utils/arm64/assembler_arm64.h"
jeffhaoec014232012-09-05 10:42:25 -070042#include "verifier/method_verifier.h"
Brian Carlstrome24fa612011-09-29 00:53:55 -070043
44namespace art {
45
Vladimir Markof4da6752014-08-01 19:04:18 +010046class OatWriter::RelativeCallPatcher {
47 public:
48 virtual ~RelativeCallPatcher() { }
49
50 // Reserve space for relative call thunks if needed, return adjusted offset.
51 // After all methods have been processed it's call one last time with compiled_method == nullptr.
52 virtual uint32_t ReserveSpace(uint32_t offset, const CompiledMethod* compiled_method) = 0;
53
54 // Write relative call thunks if needed, return adjusted offset.
55 virtual uint32_t WriteThunks(OutputStream* out, uint32_t offset) = 0;
56
57 // Patch method code. The input displacement is relative to the patched location,
58 // the patcher may need to adjust it if the correct base is different.
59 virtual void Patch(std::vector<uint8_t>* code, uint32_t literal_offset, uint32_t patch_offset,
60 uint32_t target_offset) = 0;
61
62 protected:
63 RelativeCallPatcher() { }
64
65 private:
66 DISALLOW_COPY_AND_ASSIGN(RelativeCallPatcher);
67};
68
69class OatWriter::NoRelativeCallPatcher FINAL : public RelativeCallPatcher {
70 public:
71 NoRelativeCallPatcher() { }
72
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070073 uint32_t ReserveSpace(uint32_t offset,
74 const CompiledMethod* compiled_method ATTRIBUTE_UNUSED) OVERRIDE {
Vladimir Markof4da6752014-08-01 19:04:18 +010075 return offset; // No space reserved; no patches expected.
76 }
77
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070078 uint32_t WriteThunks(OutputStream* out ATTRIBUTE_UNUSED, uint32_t offset) OVERRIDE {
Vladimir Markof4da6752014-08-01 19:04:18 +010079 return offset; // No thunks added; no patches expected.
80 }
81
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070082 void Patch(std::vector<uint8_t>* code ATTRIBUTE_UNUSED, uint32_t literal_offset ATTRIBUTE_UNUSED,
83 uint32_t patch_offset ATTRIBUTE_UNUSED,
84 uint32_t target_offset ATTRIBUTE_UNUSED) OVERRIDE {
Vladimir Markof4da6752014-08-01 19:04:18 +010085 LOG(FATAL) << "Unexpected relative patch.";
86 }
87
88 private:
89 DISALLOW_COPY_AND_ASSIGN(NoRelativeCallPatcher);
90};
91
92class OatWriter::X86RelativeCallPatcher FINAL : public RelativeCallPatcher {
93 public:
94 X86RelativeCallPatcher() { }
95
Ian Rogers6a3c1fc2014-10-31 00:33:20 -070096 uint32_t ReserveSpace(uint32_t offset,
97 const CompiledMethod* compiled_method ATTRIBUTE_UNUSED) OVERRIDE {
Vladimir Markof4da6752014-08-01 19:04:18 +010098 return offset; // No space reserved; no limit on relative call distance.
99 }
100
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700101 uint32_t WriteThunks(OutputStream* out ATTRIBUTE_UNUSED, uint32_t offset) OVERRIDE {
Vladimir Markof4da6752014-08-01 19:04:18 +0100102 return offset; // No thunks added; no limit on relative call distance.
103 }
104
105 void Patch(std::vector<uint8_t>* code, uint32_t literal_offset, uint32_t patch_offset,
106 uint32_t target_offset) OVERRIDE {
107 DCHECK_LE(literal_offset + 4u, code->size());
108 // Unsigned arithmetic with its well-defined overflow behavior is just fine here.
109 uint32_t displacement = target_offset - patch_offset;
110 displacement -= kPcDisplacement; // The base PC is at the end of the 4-byte patch.
111
112 typedef __attribute__((__aligned__(1))) int32_t unaligned_int32_t;
113 reinterpret_cast<unaligned_int32_t*>(&(*code)[literal_offset])[0] = displacement;
114 }
115
116 private:
117 // PC displacement from patch location; x86 PC for relative calls points to the next
118 // instruction and the patch location is 4 bytes earlier.
119 static constexpr int32_t kPcDisplacement = 4;
120
121 DISALLOW_COPY_AND_ASSIGN(X86RelativeCallPatcher);
122};
123
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100124class OatWriter::ArmBaseRelativeCallPatcher : public RelativeCallPatcher {
Vladimir Markof4da6752014-08-01 19:04:18 +0100125 public:
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100126 ArmBaseRelativeCallPatcher(OatWriter* writer,
127 InstructionSet instruction_set, std::vector<uint8_t> thunk_code,
128 uint32_t max_positive_displacement, uint32_t max_negative_displacement)
129 : writer_(writer), instruction_set_(instruction_set), thunk_code_(thunk_code),
130 max_positive_displacement_(max_positive_displacement),
131 max_negative_displacement_(max_negative_displacement),
Vladimir Markof4da6752014-08-01 19:04:18 +0100132 thunk_locations_(), current_thunk_to_write_(0u), unprocessed_patches_() {
133 }
134
135 uint32_t ReserveSpace(uint32_t offset, const CompiledMethod* compiled_method) OVERRIDE {
136 // NOTE: The final thunk can be reserved from InitCodeMethodVisitor::EndClass() while it
137 // may be written early by WriteCodeMethodVisitor::VisitMethod() for a deduplicated chunk
138 // of code. To avoid any alignment discrepancies for the final chunk, we always align the
139 // offset after reserving of writing any chunk.
140 if (UNLIKELY(compiled_method == nullptr)) {
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100141 uint32_t aligned_offset = CompiledMethod::AlignCode(offset, instruction_set_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100142 bool needs_thunk = ReserveSpaceProcessPatches(aligned_offset);
143 if (needs_thunk) {
144 thunk_locations_.push_back(aligned_offset);
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100145 offset = CompiledMethod::AlignCode(aligned_offset + thunk_code_.size(), instruction_set_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100146 }
147 return offset;
148 }
149 DCHECK(compiled_method->GetQuickCode() != nullptr);
150 uint32_t quick_code_size = compiled_method->GetQuickCode()->size();
151 uint32_t quick_code_offset = compiled_method->AlignCode(offset) + sizeof(OatQuickMethodHeader);
152 uint32_t next_aligned_offset = compiled_method->AlignCode(quick_code_offset + quick_code_size);
153 if (!unprocessed_patches_.empty() &&
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100154 next_aligned_offset - unprocessed_patches_.front().second > max_positive_displacement_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100155 bool needs_thunk = ReserveSpaceProcessPatches(next_aligned_offset);
156 if (needs_thunk) {
157 // A single thunk will cover all pending patches.
158 unprocessed_patches_.clear();
159 uint32_t thunk_location = compiled_method->AlignCode(offset);
160 thunk_locations_.push_back(thunk_location);
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100161 offset = CompiledMethod::AlignCode(thunk_location + thunk_code_.size(), instruction_set_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100162 }
163 }
164 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
165 if (patch.Type() == kLinkerPatchCallRelative) {
166 unprocessed_patches_.emplace_back(patch.TargetMethod(),
167 quick_code_offset + patch.LiteralOffset());
168 }
169 }
170 return offset;
171 }
172
173 uint32_t WriteThunks(OutputStream* out, uint32_t offset) OVERRIDE {
174 if (current_thunk_to_write_ == thunk_locations_.size()) {
175 return offset;
176 }
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100177 uint32_t aligned_offset = CompiledMethod::AlignCode(offset, instruction_set_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100178 if (UNLIKELY(aligned_offset == thunk_locations_[current_thunk_to_write_])) {
179 ++current_thunk_to_write_;
180 uint32_t aligned_code_delta = aligned_offset - offset;
181 if (aligned_code_delta != 0u && !writer_->WriteCodeAlignment(out, aligned_code_delta)) {
182 return 0u;
183 }
184 if (!out->WriteFully(thunk_code_.data(), thunk_code_.size())) {
185 return 0u;
186 }
187 writer_->size_relative_call_thunks_ += thunk_code_.size();
188 uint32_t thunk_end_offset = aligned_offset + thunk_code_.size();
189 // Align after writing chunk, see the ReserveSpace() above.
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100190 offset = CompiledMethod::AlignCode(thunk_end_offset, instruction_set_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100191 aligned_code_delta = offset - thunk_end_offset;
192 if (aligned_code_delta != 0u && !writer_->WriteCodeAlignment(out, aligned_code_delta)) {
193 return 0u;
194 }
195 }
196 return offset;
197 }
198
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100199 protected:
200 uint32_t CalculateDisplacement(uint32_t patch_offset, uint32_t target_offset) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100201 // Unsigned arithmetic with its well-defined overflow behavior is just fine here.
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100202 uint32_t displacement = target_offset - patch_offset;
Vladimir Markof4da6752014-08-01 19:04:18 +0100203 // NOTE: With unsigned arithmetic we do mean to use && rather than || below.
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100204 if (displacement > max_positive_displacement_ && displacement < -max_negative_displacement_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100205 // Unwritten thunks have higher offsets, check if it's within range.
206 DCHECK(current_thunk_to_write_ == thunk_locations_.size() ||
207 thunk_locations_[current_thunk_to_write_] > patch_offset);
208 if (current_thunk_to_write_ != thunk_locations_.size() &&
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100209 thunk_locations_[current_thunk_to_write_] - patch_offset < max_positive_displacement_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100210 displacement = thunk_locations_[current_thunk_to_write_] - patch_offset;
211 } else {
212 // We must have a previous thunk then.
213 DCHECK_NE(current_thunk_to_write_, 0u);
214 DCHECK_LT(thunk_locations_[current_thunk_to_write_ - 1], patch_offset);
215 displacement = thunk_locations_[current_thunk_to_write_ - 1] - patch_offset;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100216 DCHECK(displacement >= -max_negative_displacement_);
Vladimir Markof4da6752014-08-01 19:04:18 +0100217 }
218 }
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100219 return displacement;
220 }
221
222 private:
223 bool ReserveSpaceProcessPatches(uint32_t next_aligned_offset) {
224 // Process as many patches as possible, stop only on unresolved targets or calls too far back.
225 while (!unprocessed_patches_.empty()) {
226 uint32_t patch_offset = unprocessed_patches_.front().second;
227 auto it = writer_->method_offset_map_.find(unprocessed_patches_.front().first);
228 if (it == writer_->method_offset_map_.end()) {
229 // If still unresolved, check if we have a thunk within range.
230 DCHECK(thunk_locations_.empty() || thunk_locations_.back() <= patch_offset);
231 if (thunk_locations_.empty() ||
232 patch_offset - thunk_locations_.back() > max_negative_displacement_) {
233 return next_aligned_offset - patch_offset > max_positive_displacement_;
234 }
235 } else if (it->second >= patch_offset) {
236 DCHECK_LE(it->second - patch_offset, max_positive_displacement_);
237 } else {
238 // When calling back, check if we have a thunk that's closer than the actual target.
239 uint32_t target_offset = (thunk_locations_.empty() || it->second > thunk_locations_.back())
240 ? it->second
241 : thunk_locations_.back();
242 DCHECK_GT(patch_offset, target_offset);
243 if (patch_offset - target_offset > max_negative_displacement_) {
244 return true;
245 }
246 }
247 unprocessed_patches_.pop_front();
248 }
249 return false;
250 }
251
252 OatWriter* const writer_;
253 const InstructionSet instruction_set_;
254 const std::vector<uint8_t> thunk_code_;
255 const uint32_t max_positive_displacement_;
256 const uint32_t max_negative_displacement_;
257 std::vector<uint32_t> thunk_locations_;
258 size_t current_thunk_to_write_;
259
260 // ReserveSpace() tracks unprocessed patches.
261 typedef std::pair<MethodReference, uint32_t> UnprocessedPatch;
262 std::deque<UnprocessedPatch> unprocessed_patches_;
263
264 DISALLOW_COPY_AND_ASSIGN(ArmBaseRelativeCallPatcher);
265};
266
267class OatWriter::Thumb2RelativeCallPatcher FINAL : public ArmBaseRelativeCallPatcher {
268 public:
269 explicit Thumb2RelativeCallPatcher(OatWriter* writer)
270 : ArmBaseRelativeCallPatcher(writer, kThumb2, CompileThunkCode(),
271 kMaxPositiveDisplacement, kMaxNegativeDisplacement) {
272 }
273
274 void Patch(std::vector<uint8_t>* code, uint32_t literal_offset, uint32_t patch_offset,
275 uint32_t target_offset) OVERRIDE {
276 DCHECK_LE(literal_offset + 4u, code->size());
277 DCHECK_EQ(literal_offset & 1u, 0u);
278 DCHECK_EQ(patch_offset & 1u, 0u);
279 DCHECK_EQ(target_offset & 1u, 1u); // Thumb2 mode bit.
280 uint32_t displacement = CalculateDisplacement(patch_offset, target_offset & ~1u);
Vladimir Markof4da6752014-08-01 19:04:18 +0100281 displacement -= kPcDisplacement; // The base PC is at the end of the 4-byte patch.
282 DCHECK_EQ(displacement & 1u, 0u);
283 DCHECK((displacement >> 24) == 0u || (displacement >> 24) == 255u); // 25-bit signed.
284 uint32_t signbit = (displacement >> 31) & 0x1;
285 uint32_t i1 = (displacement >> 23) & 0x1;
286 uint32_t i2 = (displacement >> 22) & 0x1;
287 uint32_t imm10 = (displacement >> 12) & 0x03ff;
288 uint32_t imm11 = (displacement >> 1) & 0x07ff;
289 uint32_t j1 = i1 ^ (signbit ^ 1);
290 uint32_t j2 = i2 ^ (signbit ^ 1);
291 uint32_t value = (signbit << 26) | (j1 << 13) | (j2 << 11) | (imm10 << 16) | imm11;
292 value |= 0xf000d000; // BL
293
294 uint8_t* addr = &(*code)[literal_offset];
295 // Check that we're just overwriting an existing BL.
296 DCHECK_EQ(addr[1] & 0xf8, 0xf0);
297 DCHECK_EQ(addr[3] & 0xd0, 0xd0);
298 // Write the new BL.
299 addr[0] = (value >> 16) & 0xff;
300 addr[1] = (value >> 24) & 0xff;
301 addr[2] = (value >> 0) & 0xff;
302 addr[3] = (value >> 8) & 0xff;
303 }
304
305 private:
Vladimir Markof4da6752014-08-01 19:04:18 +0100306 static std::vector<uint8_t> CompileThunkCode() {
307 // The thunk just uses the entry point in the ArtMethod. This works even for calls
308 // to the generic JNI and interpreter trampolines.
309 arm::Thumb2Assembler assembler;
310 assembler.LoadFromOffset(
311 arm::kLoadWord, arm::PC, arm::R0,
Mathieu Chartier2d721012014-11-10 11:08:06 -0800312 mirror::ArtMethod::EntryPointFromQuickCompiledCodeOffset(kArmPointerSize).Int32Value());
Vladimir Markof4da6752014-08-01 19:04:18 +0100313 assembler.bkpt(0);
314 std::vector<uint8_t> thunk_code(assembler.CodeSize());
315 MemoryRegion code(thunk_code.data(), thunk_code.size());
316 assembler.FinalizeInstructions(code);
317 return thunk_code;
318 }
319
320 // PC displacement from patch location; Thumb2 PC is always at instruction address + 4.
321 static constexpr int32_t kPcDisplacement = 4;
322
323 // Maximum positive and negative displacement measured from the patch location.
324 // (Signed 25 bit displacement with the last bit 0 has range [-2^24, 2^24-2] measured from
325 // the Thumb2 PC pointing right after the BL, i.e. 4 bytes later than the patch location.)
326 static constexpr uint32_t kMaxPositiveDisplacement = (1u << 24) - 2 + kPcDisplacement;
327 static constexpr uint32_t kMaxNegativeDisplacement = (1u << 24) - kPcDisplacement;
328
Vladimir Markof4da6752014-08-01 19:04:18 +0100329 DISALLOW_COPY_AND_ASSIGN(Thumb2RelativeCallPatcher);
330};
331
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100332class OatWriter::Arm64RelativeCallPatcher FINAL : public ArmBaseRelativeCallPatcher {
333 public:
334 explicit Arm64RelativeCallPatcher(OatWriter* writer)
335 : ArmBaseRelativeCallPatcher(writer, kArm64, CompileThunkCode(),
336 kMaxPositiveDisplacement, kMaxNegativeDisplacement) {
337 }
338
339 void Patch(std::vector<uint8_t>* code, uint32_t literal_offset, uint32_t patch_offset,
340 uint32_t target_offset) OVERRIDE {
341 DCHECK_LE(literal_offset + 4u, code->size());
342 DCHECK_EQ(literal_offset & 3u, 0u);
343 DCHECK_EQ(patch_offset & 3u, 0u);
344 DCHECK_EQ(target_offset & 3u, 0u);
345 uint32_t displacement = CalculateDisplacement(patch_offset, target_offset & ~1u);
346 DCHECK_EQ(displacement & 3u, 0u);
347 DCHECK((displacement >> 27) == 0u || (displacement >> 27) == 31u); // 28-bit signed.
348 uint32_t value = (displacement & 0x0fffffffu) >> 2;
349 value |= 0x94000000; // BL
350
351 uint8_t* addr = &(*code)[literal_offset];
352 // Check that we're just overwriting an existing BL.
353 DCHECK_EQ(addr[3] & 0xfc, 0x94);
354 // Write the new BL.
355 addr[0] = (value >> 0) & 0xff;
356 addr[1] = (value >> 8) & 0xff;
357 addr[2] = (value >> 16) & 0xff;
358 addr[3] = (value >> 24) & 0xff;
359 }
360
361 private:
362 static std::vector<uint8_t> CompileThunkCode() {
363 // The thunk just uses the entry point in the ArtMethod. This works even for calls
364 // to the generic JNI and interpreter trampolines.
365 arm64::Arm64Assembler assembler;
Mathieu Chartier2d721012014-11-10 11:08:06 -0800366 Offset offset(mirror::ArtMethod::EntryPointFromQuickCompiledCodeOffset(
367 kArm64PointerSize).Int32Value());
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100368 assembler.JumpTo(ManagedRegister(arm64::X0), offset, ManagedRegister(arm64::IP0));
Serban Constantinescu32f5b4d2014-11-25 20:05:46 +0000369 // Ensure we emit the literal pool.
370 assembler.EmitSlowPaths();
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100371 std::vector<uint8_t> thunk_code(assembler.CodeSize());
372 MemoryRegion code(thunk_code.data(), thunk_code.size());
373 assembler.FinalizeInstructions(code);
374 return thunk_code;
375 }
376
377 // Maximum positive and negative displacement measured from the patch location.
378 // (Signed 28 bit displacement with the last bit 0 has range [-2^27, 2^27-4] measured from
379 // the ARM64 PC pointing to the BL.)
380 static constexpr uint32_t kMaxPositiveDisplacement = (1u << 27) - 4u;
381 static constexpr uint32_t kMaxNegativeDisplacement = (1u << 27);
382
383 DISALLOW_COPY_AND_ASSIGN(Arm64RelativeCallPatcher);
384};
385
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100386#define DCHECK_OFFSET() \
387 DCHECK_EQ(static_cast<off_t>(file_offset + relative_offset), out->Seek(0, kSeekCurrent)) \
388 << "file_offset=" << file_offset << " relative_offset=" << relative_offset
389
390#define DCHECK_OFFSET_() \
391 DCHECK_EQ(static_cast<off_t>(file_offset + offset_), out->Seek(0, kSeekCurrent)) \
392 << "file_offset=" << file_offset << " offset_=" << offset_
393
Brian Carlstrom3320cf42011-10-04 14:58:28 -0700394OatWriter::OatWriter(const std::vector<const DexFile*>& dex_files,
Brian Carlstrom28db0122012-10-18 16:20:41 -0700395 uint32_t image_file_location_oat_checksum,
Ian Rogersef7d42f2014-01-06 12:55:46 -0800396 uintptr_t image_file_location_oat_begin,
Alex Lighta59dd802014-07-02 16:28:08 -0700397 int32_t image_patch_delta,
Ian Rogersca368cb2013-11-15 15:52:08 -0800398 const CompilerDriver* compiler,
Vladimir Markof4da6752014-08-01 19:04:18 +0100399 ImageWriter* image_writer,
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700400 TimingLogger* timings,
401 SafeMap<std::string, std::string>* key_value_store)
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700402 : compiler_driver_(compiler),
Vladimir Markof4da6752014-08-01 19:04:18 +0100403 image_writer_(image_writer),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700404 dex_files_(&dex_files),
Vladimir Markof4da6752014-08-01 19:04:18 +0100405 size_(0u),
406 oat_data_offset_(0u),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700407 image_file_location_oat_checksum_(image_file_location_oat_checksum),
408 image_file_location_oat_begin_(image_file_location_oat_begin),
Alex Lighta59dd802014-07-02 16:28:08 -0700409 image_patch_delta_(image_patch_delta),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700410 key_value_store_(key_value_store),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700411 oat_header_(NULL),
412 size_dex_file_alignment_(0),
413 size_executable_offset_alignment_(0),
414 size_oat_header_(0),
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700415 size_oat_header_key_value_store_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700416 size_dex_file_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700417 size_interpreter_to_interpreter_bridge_(0),
418 size_interpreter_to_compiled_code_bridge_(0),
419 size_jni_dlsym_lookup_(0),
Andreas Gampe2da88232014-02-27 12:26:20 -0800420 size_quick_generic_jni_trampoline_(0),
Jeff Hao88474b42013-10-23 16:24:40 -0700421 size_quick_imt_conflict_trampoline_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700422 size_quick_resolution_trampoline_(0),
Ian Rogers848871b2013-08-05 10:56:33 -0700423 size_quick_to_interpreter_bridge_(0),
424 size_trampoline_alignment_(0),
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100425 size_method_header_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700426 size_code_(0),
427 size_code_alignment_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100428 size_relative_call_thunks_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700429 size_mapping_table_(0),
430 size_vmap_table_(0),
431 size_gc_map_(0),
432 size_oat_dex_file_location_size_(0),
433 size_oat_dex_file_location_data_(0),
434 size_oat_dex_file_location_checksum_(0),
435 size_oat_dex_file_offset_(0),
436 size_oat_dex_file_methods_offsets_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700437 size_oat_class_type_(0),
Jeff Hao0aba0ba2013-06-03 14:49:28 -0700438 size_oat_class_status_(0),
Brian Carlstromba150c32013-08-27 17:31:03 -0700439 size_oat_class_method_bitmaps_(0),
Vladimir Markof4da6752014-08-01 19:04:18 +0100440 size_oat_class_method_offsets_(0),
441 method_offset_map_() {
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700442 CHECK(key_value_store != nullptr);
443
Vladimir Markof4da6752014-08-01 19:04:18 +0100444 switch (compiler_driver_->GetInstructionSet()) {
445 case kX86:
446 case kX86_64:
447 relative_call_patcher_.reset(new X86RelativeCallPatcher);
448 break;
449 case kArm:
450 // Fall through: we generate Thumb2 code for "arm".
451 case kThumb2:
452 relative_call_patcher_.reset(new Thumb2RelativeCallPatcher(this));
453 break;
454 case kArm64:
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100455 relative_call_patcher_.reset(new Arm64RelativeCallPatcher(this));
456 break;
Vladimir Markof4da6752014-08-01 19:04:18 +0100457 default:
458 relative_call_patcher_.reset(new NoRelativeCallPatcher);
459 break;
460 }
461
Ian Rogersca368cb2013-11-15 15:52:08 -0800462 size_t offset;
463 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700464 TimingLogger::ScopedTiming split("InitOatHeader", timings);
Ian Rogersca368cb2013-11-15 15:52:08 -0800465 offset = InitOatHeader();
466 }
467 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700468 TimingLogger::ScopedTiming split("InitOatDexFiles", timings);
Ian Rogersca368cb2013-11-15 15:52:08 -0800469 offset = InitOatDexFiles(offset);
470 }
471 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700472 TimingLogger::ScopedTiming split("InitDexFiles", timings);
Ian Rogersca368cb2013-11-15 15:52:08 -0800473 offset = InitDexFiles(offset);
474 }
475 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700476 TimingLogger::ScopedTiming split("InitOatClasses", timings);
Ian Rogersca368cb2013-11-15 15:52:08 -0800477 offset = InitOatClasses(offset);
478 }
479 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700480 TimingLogger::ScopedTiming split("InitOatMaps", timings);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100481 offset = InitOatMaps(offset);
482 }
483 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700484 TimingLogger::ScopedTiming split("InitOatCode", timings);
Ian Rogersca368cb2013-11-15 15:52:08 -0800485 offset = InitOatCode(offset);
486 }
487 {
Mathieu Chartierf5997b42014-06-20 10:37:54 -0700488 TimingLogger::ScopedTiming split("InitOatCodeDexFiles", timings);
Ian Rogersca368cb2013-11-15 15:52:08 -0800489 offset = InitOatCodeDexFiles(offset);
490 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -0700491 size_ = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -0700492
493 CHECK_EQ(dex_files_->size(), oat_dex_files_.size());
Vladimir Markof4da6752014-08-01 19:04:18 +0100494 CHECK_EQ(compiler->IsImage(), image_writer_ != nullptr);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -0700495 CHECK_EQ(compiler->IsImage(),
496 key_value_store_->find(OatHeader::kImageLocationKey) == key_value_store_->end());
Alex Lighta59dd802014-07-02 16:28:08 -0700497 CHECK_ALIGNED(image_patch_delta_, kPageSize);
Brian Carlstrome24fa612011-09-29 00:53:55 -0700498}
499
Ian Rogers0571d352011-11-03 19:51:38 -0700500OatWriter::~OatWriter() {
501 delete oat_header_;
502 STLDeleteElements(&oat_dex_files_);
Brian Carlstrom389efb02012-01-11 12:06:26 -0800503 STLDeleteElements(&oat_classes_);
Ian Rogers0571d352011-11-03 19:51:38 -0700504}
505
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100506struct OatWriter::GcMapDataAccess {
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800507 static const SwapVector<uint8_t>* GetData(const CompiledMethod* compiled_method) ALWAYS_INLINE {
Nicolas Geoffray39468442014-09-02 15:17:15 +0100508 return compiled_method->GetGcMap();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100509 }
510
511 static uint32_t GetOffset(OatClass* oat_class, size_t method_offsets_index) ALWAYS_INLINE {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800512 uint32_t offset = oat_class->method_headers_[method_offsets_index].gc_map_offset_;
513 return offset == 0u ? 0u :
514 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100515 }
516
517 static void SetOffset(OatClass* oat_class, size_t method_offsets_index, uint32_t offset)
518 ALWAYS_INLINE {
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800519 oat_class->method_headers_[method_offsets_index].gc_map_offset_ =
520 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100521 }
522
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800523 static const char* Name() {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100524 return "GC map";
525 }
526};
527
528struct OatWriter::MappingTableDataAccess {
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800529 static const SwapVector<uint8_t>* GetData(const CompiledMethod* compiled_method) ALWAYS_INLINE {
Nicolas Geoffray376b2bb2014-12-09 14:26:32 +0000530 return compiled_method->GetMappingTable();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100531 }
532
533 static uint32_t GetOffset(OatClass* oat_class, size_t method_offsets_index) ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100534 uint32_t offset = oat_class->method_headers_[method_offsets_index].mapping_table_offset_;
535 return offset == 0u ? 0u :
536 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100537 }
538
539 static void SetOffset(OatClass* oat_class, size_t method_offsets_index, uint32_t offset)
540 ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100541 oat_class->method_headers_[method_offsets_index].mapping_table_offset_ =
542 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100543 }
544
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800545 static const char* Name() {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100546 return "mapping table";
547 }
548};
549
550struct OatWriter::VmapTableDataAccess {
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800551 static const SwapVector<uint8_t>* GetData(const CompiledMethod* compiled_method) ALWAYS_INLINE {
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800552 return compiled_method->GetVmapTable();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100553 }
554
555 static uint32_t GetOffset(OatClass* oat_class, size_t method_offsets_index) ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100556 uint32_t offset = oat_class->method_headers_[method_offsets_index].vmap_table_offset_;
557 return offset == 0u ? 0u :
558 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100559 }
560
561 static void SetOffset(OatClass* oat_class, size_t method_offsets_index, uint32_t offset)
562 ALWAYS_INLINE {
Vladimir Marko8a630572014-04-09 18:45:35 +0100563 oat_class->method_headers_[method_offsets_index].vmap_table_offset_ =
564 (oat_class->method_offsets_[method_offsets_index].code_offset_ & ~1) - offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100565 }
566
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800567 static const char* Name() {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100568 return "vmap table";
569 }
570};
571
572class OatWriter::DexMethodVisitor {
573 public:
574 DexMethodVisitor(OatWriter* writer, size_t offset)
575 : writer_(writer),
576 offset_(offset),
577 dex_file_(nullptr),
578 class_def_index_(DexFile::kDexNoIndex) {
579 }
580
581 virtual bool StartClass(const DexFile* dex_file, size_t class_def_index) {
582 DCHECK(dex_file_ == nullptr);
583 DCHECK_EQ(class_def_index_, DexFile::kDexNoIndex);
584 dex_file_ = dex_file;
585 class_def_index_ = class_def_index;
586 return true;
587 }
588
589 virtual bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) = 0;
590
591 virtual bool EndClass() {
592 if (kIsDebugBuild) {
593 dex_file_ = nullptr;
594 class_def_index_ = DexFile::kDexNoIndex;
595 }
596 return true;
597 }
598
599 size_t GetOffset() const {
600 return offset_;
601 }
602
603 protected:
604 virtual ~DexMethodVisitor() { }
605
606 OatWriter* const writer_;
607
608 // The offset is usually advanced for each visited method by the derived class.
609 size_t offset_;
610
611 // The dex file and class def index are set in StartClass().
612 const DexFile* dex_file_;
613 size_t class_def_index_;
614};
615
616class OatWriter::OatDexMethodVisitor : public DexMethodVisitor {
617 public:
618 OatDexMethodVisitor(OatWriter* writer, size_t offset)
619 : DexMethodVisitor(writer, offset),
620 oat_class_index_(0u),
621 method_offsets_index_(0u) {
622 }
623
624 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
625 DexMethodVisitor::StartClass(dex_file, class_def_index);
626 DCHECK_LT(oat_class_index_, writer_->oat_classes_.size());
627 method_offsets_index_ = 0u;
628 return true;
629 }
630
631 bool EndClass() {
632 ++oat_class_index_;
633 return DexMethodVisitor::EndClass();
634 }
635
636 protected:
637 size_t oat_class_index_;
638 size_t method_offsets_index_;
639};
640
641class OatWriter::InitOatClassesMethodVisitor : public DexMethodVisitor {
642 public:
643 InitOatClassesMethodVisitor(OatWriter* writer, size_t offset)
644 : DexMethodVisitor(writer, offset),
645 compiled_methods_(),
646 num_non_null_compiled_methods_(0u) {
647 compiled_methods_.reserve(256u);
648 }
649
650 bool StartClass(const DexFile* dex_file, size_t class_def_index) {
651 DexMethodVisitor::StartClass(dex_file, class_def_index);
652 compiled_methods_.clear();
653 num_non_null_compiled_methods_ = 0u;
654 return true;
655 }
656
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700657 bool VisitMethod(size_t class_def_method_index ATTRIBUTE_UNUSED, const ClassDataItemIterator& it) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100658 // Fill in the compiled_methods_ array for methods that have a
659 // CompiledMethod. We track the number of non-null entries in
660 // num_non_null_compiled_methods_ since we only want to allocate
661 // OatMethodOffsets for the compiled methods.
662 uint32_t method_idx = it.GetMemberIndex();
663 CompiledMethod* compiled_method =
664 writer_->compiler_driver_->GetCompiledMethod(MethodReference(dex_file_, method_idx));
665 compiled_methods_.push_back(compiled_method);
666 if (compiled_method != nullptr) {
667 ++num_non_null_compiled_methods_;
668 }
669 return true;
670 }
671
672 bool EndClass() {
673 ClassReference class_ref(dex_file_, class_def_index_);
674 CompiledClass* compiled_class = writer_->compiler_driver_->GetCompiledClass(class_ref);
675 mirror::Class::Status status;
676 if (compiled_class != NULL) {
677 status = compiled_class->GetStatus();
678 } else if (writer_->compiler_driver_->GetVerificationResults()->IsClassRejected(class_ref)) {
679 status = mirror::Class::kStatusError;
680 } else {
681 status = mirror::Class::kStatusNotReady;
682 }
683
684 OatClass* oat_class = new OatClass(offset_, compiled_methods_,
685 num_non_null_compiled_methods_, status);
686 writer_->oat_classes_.push_back(oat_class);
Vladimir Markof4da6752014-08-01 19:04:18 +0100687 oat_class->UpdateChecksum(writer_->oat_header_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100688 offset_ += oat_class->SizeOf();
689 return DexMethodVisitor::EndClass();
690 }
691
692 private:
693 std::vector<CompiledMethod*> compiled_methods_;
694 size_t num_non_null_compiled_methods_;
695};
696
697class OatWriter::InitCodeMethodVisitor : public OatDexMethodVisitor {
698 public:
699 InitCodeMethodVisitor(OatWriter* writer, size_t offset)
700 : OatDexMethodVisitor(writer, offset) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100701 writer_->absolute_patch_locations_.reserve(
702 writer_->compiler_driver_->GetNonRelativeLinkerPatchCount());
703 }
704
705 bool EndClass() {
706 OatDexMethodVisitor::EndClass();
707 if (oat_class_index_ == writer_->oat_classes_.size()) {
708 offset_ = writer_->relative_call_patcher_->ReserveSpace(offset_, nullptr);
709 }
710 return true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100711 }
712
713 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
714 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
715 OatClass* oat_class = writer_->oat_classes_[oat_class_index_];
716 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
717
718 if (compiled_method != nullptr) {
719 // Derived from CompiledMethod.
720 uint32_t quick_code_offset = 0;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100721
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800722 const SwapVector<uint8_t>* quick_code = compiled_method->GetQuickCode();
Elliott Hughes956af0f2014-12-11 14:34:28 -0800723 CHECK(quick_code != nullptr);
724 offset_ = writer_->relative_call_patcher_->ReserveSpace(offset_, compiled_method);
725 offset_ = compiled_method->AlignCode(offset_);
726 DCHECK_ALIGNED_PARAM(offset_,
727 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
728 uint32_t code_size = quick_code->size() * sizeof(uint8_t);
729 CHECK_NE(code_size, 0U);
730 uint32_t thumb_offset = compiled_method->CodeDelta();
731 quick_code_offset = offset_ + sizeof(OatQuickMethodHeader) + thumb_offset;
732
733 bool deduped = false;
734
735 // Deduplicate code arrays.
736 auto lb = dedupe_map_.lower_bound(compiled_method);
737 if (lb != dedupe_map_.end() && !dedupe_map_.key_comp()(compiled_method, lb->first)) {
738 quick_code_offset = lb->second;
739 deduped = true;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100740 } else {
Elliott Hughes956af0f2014-12-11 14:34:28 -0800741 dedupe_map_.PutBefore(lb, compiled_method, quick_code_offset);
742 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100743
Elliott Hughes956af0f2014-12-11 14:34:28 -0800744 MethodReference method_ref(dex_file_, it.GetMemberIndex());
745 auto method_lb = writer_->method_offset_map_.lower_bound(method_ref);
746 if (method_lb != writer_->method_offset_map_.end() &&
747 !writer_->method_offset_map_.key_comp()(method_ref, method_lb->first)) {
748 // TODO: Should this be a hard failure?
749 LOG(WARNING) << "Multiple definitions of "
750 << PrettyMethod(method_ref.dex_method_index, *method_ref.dex_file)
751 << ((method_lb->second != quick_code_offset) ? "; OFFSET MISMATCH" : "");
752 } else {
753 writer_->method_offset_map_.PutBefore(method_lb, method_ref, quick_code_offset);
754 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100755
Elliott Hughes956af0f2014-12-11 14:34:28 -0800756 // Update quick method header.
757 DCHECK_LT(method_offsets_index_, oat_class->method_headers_.size());
758 OatQuickMethodHeader* method_header = &oat_class->method_headers_[method_offsets_index_];
759 uint32_t mapping_table_offset = method_header->mapping_table_offset_;
760 uint32_t vmap_table_offset = method_header->vmap_table_offset_;
761 uint32_t gc_map_offset = method_header->gc_map_offset_;
762 // The code offset was 0 when the mapping/vmap table offset was set, so it's set
763 // to 0-offset and we need to adjust it by code_offset.
764 uint32_t code_offset = quick_code_offset - thumb_offset;
765 if (mapping_table_offset != 0u) {
766 mapping_table_offset += code_offset;
767 DCHECK_LT(mapping_table_offset, code_offset);
768 }
769 if (vmap_table_offset != 0u) {
770 vmap_table_offset += code_offset;
771 DCHECK_LT(vmap_table_offset, code_offset);
772 }
773 if (gc_map_offset != 0u) {
774 gc_map_offset += code_offset;
775 DCHECK_LT(gc_map_offset, code_offset);
776 }
777 uint32_t frame_size_in_bytes = compiled_method->GetFrameSizeInBytes();
778 uint32_t core_spill_mask = compiled_method->GetCoreSpillMask();
779 uint32_t fp_spill_mask = compiled_method->GetFpSpillMask();
780 *method_header = OatQuickMethodHeader(mapping_table_offset, vmap_table_offset,
781 gc_map_offset, frame_size_in_bytes, core_spill_mask,
782 fp_spill_mask, code_size);
Vladimir Marko7624d252014-05-02 14:40:15 +0100783
Elliott Hughes956af0f2014-12-11 14:34:28 -0800784 if (!deduped) {
785 // Update offsets. (Checksum is updated when writing.)
786 offset_ += sizeof(*method_header); // Method header is prepended before code.
787 offset_ += code_size;
788 // Record absolute patch locations.
789 if (!compiled_method->GetPatches().empty()) {
790 uintptr_t base_loc = offset_ - code_size - writer_->oat_header_->GetExecutableOffset();
791 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
792 if (patch.Type() != kLinkerPatchCallRelative) {
793 writer_->absolute_patch_locations_.push_back(base_loc + patch.LiteralOffset());
Vladimir Markof4da6752014-08-01 19:04:18 +0100794 }
795 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100796 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800797 }
Alex Light78382fa2014-06-06 15:45:32 -0700798
Elliott Hughes956af0f2014-12-11 14:34:28 -0800799 if (writer_->compiler_driver_->GetCompilerOptions().GetIncludeDebugSymbols()) {
800 // Record debug information for this function if we are doing that.
Alex Light78382fa2014-06-06 15:45:32 -0700801
Elliott Hughes956af0f2014-12-11 14:34:28 -0800802 std::string name = PrettyMethod(it.GetMemberIndex(), *dex_file_, true);
803 if (deduped) {
804 // TODO We should place the DEDUPED tag on the first instance of a deduplicated symbol
805 // so that it will show up in a debuggerd crash report.
806 name += " [ DEDUPED ]";
Alex Light78382fa2014-06-06 15:45:32 -0700807 }
Elliott Hughes956af0f2014-12-11 14:34:28 -0800808
809 const uint32_t quick_code_start = quick_code_offset -
810 writer_->oat_header_->GetExecutableOffset();
811 const DexFile::CodeItem *code_item = it.GetMethodCodeItem();
812 writer_->method_info_.push_back(DebugInfo(name,
813 dex_file_->GetSourceFile(dex_file_->GetClassDef(class_def_index_)),
814 quick_code_start, quick_code_start + code_size,
815 code_item == nullptr ? nullptr : dex_file_->GetDebugInfoStream(code_item),
816 compiled_method));
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100817 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100818
819 if (kIsDebugBuild) {
820 // We expect GC maps except when the class hasn't been verified or the method is native.
821 const CompilerDriver* compiler_driver = writer_->compiler_driver_;
822 ClassReference class_ref(dex_file_, class_def_index_);
823 CompiledClass* compiled_class = compiler_driver->GetCompiledClass(class_ref);
824 mirror::Class::Status status;
825 if (compiled_class != NULL) {
826 status = compiled_class->GetStatus();
827 } else if (compiler_driver->GetVerificationResults()->IsClassRejected(class_ref)) {
828 status = mirror::Class::kStatusError;
829 } else {
830 status = mirror::Class::kStatusNotReady;
831 }
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800832 const SwapVector<uint8_t>* gc_map = compiled_method->GetGcMap();
Nicolas Geoffray39468442014-09-02 15:17:15 +0100833 if (gc_map != nullptr) {
834 size_t gc_map_size = gc_map->size() * sizeof(gc_map[0]);
Andreas Gampe51829322014-08-25 15:05:04 -0700835 bool is_native = it.MemberIsNative();
Nicolas Geoffray39468442014-09-02 15:17:15 +0100836 CHECK(gc_map_size != 0 || is_native || status < mirror::Class::kStatusVerified)
837 << gc_map << " " << gc_map_size << " " << (is_native ? "true" : "false") << " "
838 << (status < mirror::Class::kStatusVerified) << " " << status << " "
839 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
840 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100841 }
842
843 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
844 OatMethodOffsets* offsets = &oat_class->method_offsets_[method_offsets_index_];
845 offsets->code_offset_ = quick_code_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100846 ++method_offsets_index_;
847 }
848
849 return true;
850 }
851
852 private:
853 // Deduplication is already done on a pointer basis by the compiler driver,
854 // so we can simply compare the pointers to find out if things are duplicated.
Vladimir Marko8a630572014-04-09 18:45:35 +0100855 SafeMap<const CompiledMethod*, uint32_t, CodeOffsetsKeyComparator> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100856};
857
858template <typename DataAccess>
859class OatWriter::InitMapMethodVisitor : public OatDexMethodVisitor {
860 public:
861 InitMapMethodVisitor(OatWriter* writer, size_t offset)
862 : OatDexMethodVisitor(writer, offset) {
863 }
864
Ian Rogers6a3c1fc2014-10-31 00:33:20 -0700865 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it ATTRIBUTE_UNUSED)
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100866 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
867 OatClass* oat_class = writer_->oat_classes_[oat_class_index_];
868 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
869
870 if (compiled_method != nullptr) {
871 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
872 DCHECK_EQ(DataAccess::GetOffset(oat_class, method_offsets_index_), 0u);
873
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800874 const SwapVector<uint8_t>* map = DataAccess::GetData(compiled_method);
Nicolas Geoffray39468442014-09-02 15:17:15 +0100875 uint32_t map_size = map == nullptr ? 0 : map->size() * sizeof((*map)[0]);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100876 if (map_size != 0u) {
Vladimir Markobd72fc12014-07-09 16:06:40 +0100877 auto lb = dedupe_map_.lower_bound(map);
878 if (lb != dedupe_map_.end() && !dedupe_map_.key_comp()(map, lb->first)) {
879 DataAccess::SetOffset(oat_class, method_offsets_index_, lb->second);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100880 } else {
881 DataAccess::SetOffset(oat_class, method_offsets_index_, offset_);
Vladimir Markobd72fc12014-07-09 16:06:40 +0100882 dedupe_map_.PutBefore(lb, map, offset_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100883 offset_ += map_size;
884 writer_->oat_header_->UpdateChecksum(&(*map)[0], map_size);
885 }
886 }
887 ++method_offsets_index_;
888 }
889
890 return true;
891 }
892
893 private:
894 // Deduplication is already done on a pointer basis by the compiler driver,
895 // so we can simply compare the pointers to find out if things are duplicated.
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800896 SafeMap<const SwapVector<uint8_t>*, uint32_t> dedupe_map_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100897};
898
899class OatWriter::InitImageMethodVisitor : public OatDexMethodVisitor {
900 public:
901 InitImageMethodVisitor(OatWriter* writer, size_t offset)
Jeff Haoc7d11882015-02-03 15:08:39 -0800902 : OatDexMethodVisitor(writer, offset),
903 pointer_size_(GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet())) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100904 }
905
906 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
907 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
908 OatClass* oat_class = writer_->oat_classes_[oat_class_index_];
909 CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
910
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800911 OatMethodOffsets offsets(0u);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100912 if (compiled_method != nullptr) {
913 DCHECK_LT(method_offsets_index_, oat_class->method_offsets_.size());
914 offsets = oat_class->method_offsets_[method_offsets_index_];
915 ++method_offsets_index_;
916 }
917
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100918 ClassLinker* linker = Runtime::Current()->GetClassLinker();
919 InvokeType invoke_type = it.GetMethodInvokeType(dex_file_->GetClassDef(class_def_index_));
920 // Unchecked as we hold mutator_lock_ on entry.
921 ScopedObjectAccessUnchecked soa(Thread::Current());
Mathieu Chartier957ca1c2014-11-21 16:51:29 -0800922 StackHandleScope<1> hs(soa.Self());
Mathieu Chartiereb8167a2014-05-07 15:43:14 -0700923 Handle<mirror::DexCache> dex_cache(hs.NewHandle(linker->FindDexCache(*dex_file_)));
Vladimir Marko7624d252014-05-02 14:40:15 +0100924 mirror::ArtMethod* method = linker->ResolveMethod(*dex_file_, it.GetMemberIndex(), dex_cache,
Mathieu Chartier0cd81352014-05-22 16:48:55 -0700925 NullHandle<mirror::ClassLoader>(),
926 NullHandle<mirror::ArtMethod>(),
927 invoke_type);
Andreas Gamped9efea62014-07-21 22:56:08 -0700928 if (method == nullptr) {
929 LOG(ERROR) << "Unexpected failure to resolve a method: "
930 << PrettyMethod(it.GetMemberIndex(), *dex_file_, true);
931 soa.Self()->AssertPendingException();
932 mirror::Throwable* exc = soa.Self()->GetException(nullptr);
933 std::string dump = exc->Dump();
934 LOG(FATAL) << dump;
935 }
Jeff Haoc7d11882015-02-03 15:08:39 -0800936 method->SetEntryPointFromQuickCompiledCodePtrSize(reinterpret_cast<void*>(offsets.code_offset_),
937 pointer_size_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100938
939 return true;
940 }
Jeff Haoc7d11882015-02-03 15:08:39 -0800941
942 protected:
943 const size_t pointer_size_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100944};
945
946class OatWriter::WriteCodeMethodVisitor : public OatDexMethodVisitor {
947 public:
948 WriteCodeMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Vladimir Markof4da6752014-08-01 19:04:18 +0100949 size_t relative_offset) SHARED_LOCK_FUNCTION(Locks::mutator_lock_)
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100950 : OatDexMethodVisitor(writer, relative_offset),
951 out_(out),
Vladimir Markof4da6752014-08-01 19:04:18 +0100952 file_offset_(file_offset),
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +0100953 soa_(Thread::Current()),
954 no_thread_suspension_(soa_.Self(), "OatWriter patching"),
Vladimir Markof4da6752014-08-01 19:04:18 +0100955 class_linker_(Runtime::Current()->GetClassLinker()),
956 dex_cache_(nullptr) {
957 if (writer_->image_writer_ != nullptr) {
958 // If we're creating the image, the address space must be ready so that we can apply patches.
959 CHECK(writer_->image_writer_->IsImageAddressSpaceReady());
960 patched_code_.reserve(16 * KB);
961 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100962 }
963
Vladimir Markof4da6752014-08-01 19:04:18 +0100964 ~WriteCodeMethodVisitor() UNLOCK_FUNCTION(Locks::mutator_lock_) {
Vladimir Markof4da6752014-08-01 19:04:18 +0100965 }
966
967 bool StartClass(const DexFile* dex_file, size_t class_def_index)
968 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
969 OatDexMethodVisitor::StartClass(dex_file, class_def_index);
970 if (dex_cache_ == nullptr || dex_cache_->GetDexFile() != dex_file) {
971 dex_cache_ = class_linker_->FindDexCache(*dex_file);
972 }
973 return true;
974 }
975
976 bool EndClass() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
977 bool result = OatDexMethodVisitor::EndClass();
978 if (oat_class_index_ == writer_->oat_classes_.size()) {
979 DCHECK(result); // OatDexMethodVisitor::EndClass() never fails.
980 offset_ = writer_->relative_call_patcher_->WriteThunks(out_, offset_);
981 if (UNLIKELY(offset_ == 0u)) {
982 PLOG(ERROR) << "Failed to write final relative call thunks";
983 result = false;
984 }
985 }
986 return result;
987 }
988
989 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it)
990 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100991 OatClass* oat_class = writer_->oat_classes_[oat_class_index_];
992 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
993
994 if (compiled_method != NULL) { // ie. not an abstract method
995 size_t file_offset = file_offset_;
996 OutputStream* out = out_;
997
Andreas Gampee21dc3d2014-12-08 16:59:43 -0800998 const SwapVector<uint8_t>* quick_code = compiled_method->GetQuickCode();
Vladimir Marko96c6ab92014-04-08 14:00:50 +0100999 if (quick_code != nullptr) {
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001000 // Need a wrapper if we create a copy for patching.
1001 ArrayRef<const uint8_t> wrapped(*quick_code);
1002
Vladimir Markof4da6752014-08-01 19:04:18 +01001003 offset_ = writer_->relative_call_patcher_->WriteThunks(out, offset_);
1004 if (offset_ == 0u) {
1005 ReportWriteFailure("relative call thunk", it);
1006 return false;
1007 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001008 uint32_t aligned_offset = compiled_method->AlignCode(offset_);
1009 uint32_t aligned_code_delta = aligned_offset - offset_;
1010 if (aligned_code_delta != 0) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001011 if (!writer_->WriteCodeAlignment(out, aligned_code_delta)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001012 ReportWriteFailure("code alignment padding", it);
1013 return false;
1014 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001015 offset_ += aligned_code_delta;
1016 DCHECK_OFFSET_();
1017 }
1018 DCHECK_ALIGNED_PARAM(offset_,
1019 GetInstructionSetAlignment(compiled_method->GetInstructionSet()));
1020 uint32_t code_size = quick_code->size() * sizeof(uint8_t);
1021 CHECK_NE(code_size, 0U);
1022
1023 // Deduplicate code arrays.
1024 const OatMethodOffsets& method_offsets = oat_class->method_offsets_[method_offsets_index_];
1025 DCHECK(method_offsets.code_offset_ < offset_ || method_offsets.code_offset_ ==
Vladimir Marko7624d252014-05-02 14:40:15 +01001026 offset_ + sizeof(OatQuickMethodHeader) + compiled_method->CodeDelta())
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001027 << PrettyMethod(it.GetMemberIndex(), *dex_file_);
1028 if (method_offsets.code_offset_ >= offset_) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001029 const OatQuickMethodHeader& method_header =
1030 oat_class->method_headers_[method_offsets_index_];
1031 writer_->oat_header_->UpdateChecksum(&method_header, sizeof(method_header));
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001032 if (!out->WriteFully(&method_header, sizeof(method_header))) {
1033 ReportWriteFailure("method header", it);
1034 return false;
1035 }
1036 writer_->size_method_header_ += sizeof(method_header);
1037 offset_ += sizeof(method_header);
1038 DCHECK_OFFSET_();
Vladimir Markof4da6752014-08-01 19:04:18 +01001039
1040 if (!compiled_method->GetPatches().empty()) {
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001041 patched_code_ = std::vector<uint8_t>(quick_code->begin(), quick_code->end());
1042 wrapped = ArrayRef<const uint8_t>(patched_code_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001043 for (const LinkerPatch& patch : compiled_method->GetPatches()) {
1044 if (patch.Type() == kLinkerPatchCallRelative) {
1045 // NOTE: Relative calls across oat files are not supported.
1046 uint32_t target_offset = GetTargetOffset(patch);
1047 uint32_t literal_offset = patch.LiteralOffset();
1048 writer_->relative_call_patcher_->Patch(&patched_code_, literal_offset,
1049 offset_ + literal_offset, target_offset);
1050 } else if (patch.Type() == kLinkerPatchCall) {
1051 uint32_t target_offset = GetTargetOffset(patch);
1052 PatchCodeAddress(&patched_code_, patch.LiteralOffset(), target_offset);
1053 } else if (patch.Type() == kLinkerPatchMethod) {
1054 mirror::ArtMethod* method = GetTargetMethod(patch);
1055 PatchObjectAddress(&patched_code_, patch.LiteralOffset(), method);
1056 } else if (patch.Type() == kLinkerPatchType) {
1057 mirror::Class* type = GetTargetType(patch);
1058 PatchObjectAddress(&patched_code_, patch.LiteralOffset(), type);
1059 }
1060 }
1061 }
1062
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001063 writer_->oat_header_->UpdateChecksum(wrapped.data(), code_size);
1064 if (!out->WriteFully(wrapped.data(), code_size)) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001065 ReportWriteFailure("method code", it);
1066 return false;
1067 }
1068 writer_->size_code_ += code_size;
1069 offset_ += code_size;
1070 }
1071 DCHECK_OFFSET_();
1072 }
1073 ++method_offsets_index_;
1074 }
1075
1076 return true;
1077 }
1078
1079 private:
1080 OutputStream* const out_;
Vladimir Marko7c2ad5a2014-09-24 12:42:55 +01001081 const size_t file_offset_;
1082 const ScopedObjectAccess soa_;
1083 const ScopedAssertNoThreadSuspension no_thread_suspension_;
Vladimir Markof4da6752014-08-01 19:04:18 +01001084 ClassLinker* const class_linker_;
1085 mirror::DexCache* dex_cache_;
1086 std::vector<uint8_t> patched_code_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001087
1088 void ReportWriteFailure(const char* what, const ClassDataItemIterator& it) {
1089 PLOG(ERROR) << "Failed to write " << what << " for "
1090 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1091 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001092
1093 mirror::ArtMethod* GetTargetMethod(const LinkerPatch& patch)
1094 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1095 MethodReference ref = patch.TargetMethod();
1096 mirror::DexCache* dex_cache =
1097 (dex_file_ == ref.dex_file) ? dex_cache_ : class_linker_->FindDexCache(*ref.dex_file);
1098 mirror::ArtMethod* method = dex_cache->GetResolvedMethod(ref.dex_method_index);
1099 CHECK(method != nullptr);
1100 return method;
1101 }
1102
1103 uint32_t GetTargetOffset(const LinkerPatch& patch) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1104 auto target_it = writer_->method_offset_map_.find(patch.TargetMethod());
1105 uint32_t target_offset =
1106 (target_it != writer_->method_offset_map_.end()) ? target_it->second : 0u;
1107 // If there's no compiled code, point to the correct trampoline.
1108 if (UNLIKELY(target_offset == 0)) {
1109 mirror::ArtMethod* target = GetTargetMethod(patch);
1110 DCHECK(target != nullptr);
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001111 size_t size = GetInstructionSetPointerSize(writer_->compiler_driver_->GetInstructionSet());
1112 const void* oat_code_offset = target->GetEntryPointFromQuickCompiledCodePtrSize(size);
1113 if (oat_code_offset != 0) {
1114 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickResolutionStub(oat_code_offset));
1115 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickToInterpreterBridge(oat_code_offset));
1116 DCHECK(!Runtime::Current()->GetClassLinker()->IsQuickGenericJniStub(oat_code_offset));
1117 target_offset = PointerToLowMemUInt32(oat_code_offset);
1118 } else {
1119 target_offset = target->IsNative()
1120 ? writer_->oat_header_->GetQuickGenericJniTrampolineOffset()
1121 : writer_->oat_header_->GetQuickToInterpreterBridgeOffset();
1122 }
Vladimir Markof4da6752014-08-01 19:04:18 +01001123 }
1124 return target_offset;
1125 }
1126
1127 mirror::Class* GetTargetType(const LinkerPatch& patch)
1128 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1129 mirror::DexCache* dex_cache = (dex_file_ == patch.TargetTypeDexFile())
1130 ? dex_cache_ : class_linker_->FindDexCache(*patch.TargetTypeDexFile());
1131 mirror::Class* type = dex_cache->GetResolvedType(patch.TargetTypeIndex());
1132 CHECK(type != nullptr);
1133 return type;
1134 }
1135
1136 void PatchObjectAddress(std::vector<uint8_t>* code, uint32_t offset, mirror::Object* object)
1137 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
1138 // NOTE: Direct method pointers across oat files don't use linker patches. However, direct
1139 // type pointers across oat files do. (TODO: Investigate why.)
1140 if (writer_->image_writer_ != nullptr) {
1141 object = writer_->image_writer_->GetImageAddress(object);
1142 }
1143 uint32_t address = PointerToLowMemUInt32(object);
1144 DCHECK_LE(offset + 4, code->size());
1145 uint8_t* data = &(*code)[offset];
1146 data[0] = address & 0xffu;
1147 data[1] = (address >> 8) & 0xffu;
1148 data[2] = (address >> 16) & 0xffu;
1149 data[3] = (address >> 24) & 0xffu;
1150 }
1151
1152 void PatchCodeAddress(std::vector<uint8_t>* code, uint32_t offset, uint32_t target_offset)
1153 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
Jeff Haoa0acc2d2015-01-27 11:22:04 -08001154 uint32_t address = writer_->image_writer_ == nullptr ? target_offset :
1155 PointerToLowMemUInt32(writer_->image_writer_->GetOatFileBegin() +
1156 writer_->oat_data_offset_ + target_offset);
Vladimir Markof4da6752014-08-01 19:04:18 +01001157 DCHECK_LE(offset + 4, code->size());
1158 uint8_t* data = &(*code)[offset];
1159 data[0] = address & 0xffu;
1160 data[1] = (address >> 8) & 0xffu;
1161 data[2] = (address >> 16) & 0xffu;
1162 data[3] = (address >> 24) & 0xffu;
1163 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001164};
1165
1166template <typename DataAccess>
1167class OatWriter::WriteMapMethodVisitor : public OatDexMethodVisitor {
1168 public:
1169 WriteMapMethodVisitor(OatWriter* writer, OutputStream* out, const size_t file_offset,
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001170 size_t relative_offset)
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001171 : OatDexMethodVisitor(writer, relative_offset),
1172 out_(out),
1173 file_offset_(file_offset) {
1174 }
1175
1176 bool VisitMethod(size_t class_def_method_index, const ClassDataItemIterator& it) {
1177 OatClass* oat_class = writer_->oat_classes_[oat_class_index_];
1178 const CompiledMethod* compiled_method = oat_class->GetCompiledMethod(class_def_method_index);
1179
1180 if (compiled_method != NULL) { // ie. not an abstract method
1181 size_t file_offset = file_offset_;
1182 OutputStream* out = out_;
1183
1184 uint32_t map_offset = DataAccess::GetOffset(oat_class, method_offsets_index_);
1185 ++method_offsets_index_;
1186
1187 // Write deduplicated map.
Andreas Gampee21dc3d2014-12-08 16:59:43 -08001188 const SwapVector<uint8_t>* map = DataAccess::GetData(compiled_method);
Nicolas Geoffray39468442014-09-02 15:17:15 +01001189 size_t map_size = map == nullptr ? 0 : map->size() * sizeof((*map)[0]);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001190 DCHECK((map_size == 0u && map_offset == 0u) ||
1191 (map_size != 0u && map_offset != 0u && map_offset <= offset_))
Mathieu Chartier957ca1c2014-11-21 16:51:29 -08001192 << map_size << " " << map_offset << " " << offset_ << " "
1193 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " for " << DataAccess::Name();
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001194 if (map_size != 0u && map_offset == offset_) {
1195 if (UNLIKELY(!out->WriteFully(&(*map)[0], map_size))) {
1196 ReportWriteFailure(it);
1197 return false;
1198 }
1199 offset_ += map_size;
1200 }
1201 DCHECK_OFFSET_();
1202 }
1203
1204 return true;
1205 }
1206
1207 private:
1208 OutputStream* const out_;
1209 size_t const file_offset_;
1210
1211 void ReportWriteFailure(const ClassDataItemIterator& it) {
1212 PLOG(ERROR) << "Failed to write " << DataAccess::Name() << " for "
1213 << PrettyMethod(it.GetMemberIndex(), *dex_file_) << " to " << out_->GetLocation();
1214 }
1215};
1216
1217// Visit all methods from all classes in all dex files with the specified visitor.
1218bool OatWriter::VisitDexMethods(DexMethodVisitor* visitor) {
1219 for (const DexFile* dex_file : *dex_files_) {
1220 const size_t class_def_count = dex_file->NumClassDefs();
1221 for (size_t class_def_index = 0; class_def_index != class_def_count; ++class_def_index) {
1222 if (UNLIKELY(!visitor->StartClass(dex_file, class_def_index))) {
1223 return false;
1224 }
1225 const DexFile::ClassDef& class_def = dex_file->GetClassDef(class_def_index);
Ian Rogers13735952014-10-08 12:43:28 -07001226 const uint8_t* class_data = dex_file->GetClassData(class_def);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001227 if (class_data != NULL) { // ie not an empty class, such as a marker interface
1228 ClassDataItemIterator it(*dex_file, class_data);
1229 while (it.HasNextStaticField()) {
1230 it.Next();
1231 }
1232 while (it.HasNextInstanceField()) {
1233 it.Next();
1234 }
1235 size_t class_def_method_index = 0u;
1236 while (it.HasNextDirectMethod()) {
1237 if (!visitor->VisitMethod(class_def_method_index, it)) {
1238 return false;
1239 }
1240 ++class_def_method_index;
1241 it.Next();
1242 }
1243 while (it.HasNextVirtualMethod()) {
1244 if (UNLIKELY(!visitor->VisitMethod(class_def_method_index, it))) {
1245 return false;
1246 }
1247 ++class_def_method_index;
1248 it.Next();
1249 }
1250 }
1251 if (UNLIKELY(!visitor->EndClass())) {
1252 return false;
1253 }
1254 }
1255 }
1256 return true;
1257}
1258
Brian Carlstrom81f3ca12012-03-17 00:27:35 -07001259size_t OatWriter::InitOatHeader() {
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001260 oat_header_ = OatHeader::Create(compiler_driver_->GetInstructionSet(),
1261 compiler_driver_->GetInstructionSetFeatures(),
1262 dex_files_,
1263 image_file_location_oat_checksum_,
1264 image_file_location_oat_begin_,
1265 key_value_store_);
1266
1267 return oat_header_->GetHeaderSize();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001268}
1269
1270size_t OatWriter::InitOatDexFiles(size_t offset) {
1271 // create the OatDexFiles
1272 for (size_t i = 0; i != dex_files_->size(); ++i) {
1273 const DexFile* dex_file = (*dex_files_)[i];
1274 CHECK(dex_file != NULL);
Brian Carlstrom265091e2013-01-30 14:08:26 -08001275 OatDexFile* oat_dex_file = new OatDexFile(offset, *dex_file);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001276 oat_dex_files_.push_back(oat_dex_file);
1277 offset += oat_dex_file->SizeOf();
1278 }
1279 return offset;
1280}
1281
Brian Carlstrom89521892011-12-07 22:05:07 -08001282size_t OatWriter::InitDexFiles(size_t offset) {
1283 // calculate the offsets within OatDexFiles to the DexFiles
1284 for (size_t i = 0; i != dex_files_->size(); ++i) {
1285 // dex files are required to be 4 byte aligned
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001286 size_t original_offset = offset;
Brian Carlstrom89521892011-12-07 22:05:07 -08001287 offset = RoundUp(offset, 4);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001288 size_dex_file_alignment_ += offset - original_offset;
Brian Carlstrom89521892011-12-07 22:05:07 -08001289
1290 // set offset in OatDexFile to DexFile
1291 oat_dex_files_[i]->dex_file_offset_ = offset;
1292
1293 const DexFile* dex_file = (*dex_files_)[i];
1294 offset += dex_file->GetHeader().file_size_;
1295 }
1296 return offset;
1297}
1298
Brian Carlstrom389efb02012-01-11 12:06:26 -08001299size_t OatWriter::InitOatClasses(size_t offset) {
Brian Carlstrom389efb02012-01-11 12:06:26 -08001300 // calculate the offsets within OatDexFiles to OatClasses
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001301 InitOatClassesMethodVisitor visitor(this, offset);
1302 bool success = VisitDexMethods(&visitor);
1303 CHECK(success);
1304 offset = visitor.GetOffset();
Brian Carlstromba150c32013-08-27 17:31:03 -07001305
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001306 // Update oat_dex_files_.
1307 auto oat_class_it = oat_classes_.begin();
1308 for (OatDexFile* oat_dex_file : oat_dex_files_) {
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001309 for (uint32_t& method_offset : oat_dex_file->methods_offsets_) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001310 DCHECK(oat_class_it != oat_classes_.end());
Andreas Gampe277ccbd2014-11-03 21:36:10 -08001311 method_offset = (*oat_class_it)->offset_;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001312 ++oat_class_it;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001313 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001314 oat_dex_file->UpdateChecksum(oat_header_);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001315 }
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001316 CHECK(oat_class_it == oat_classes_.end());
1317
1318 return offset;
1319}
1320
1321size_t OatWriter::InitOatMaps(size_t offset) {
1322 #define VISIT(VisitorType) \
1323 do { \
1324 VisitorType visitor(this, offset); \
1325 bool success = VisitDexMethods(&visitor); \
1326 DCHECK(success); \
1327 offset = visitor.GetOffset(); \
1328 } while (false)
1329
1330 VISIT(InitMapMethodVisitor<GcMapDataAccess>);
1331 VISIT(InitMapMethodVisitor<MappingTableDataAccess>);
1332 VISIT(InitMapMethodVisitor<VmapTableDataAccess>);
1333
1334 #undef VISIT
1335
Brian Carlstrome24fa612011-09-29 00:53:55 -07001336 return offset;
1337}
1338
1339size_t OatWriter::InitOatCode(size_t offset) {
1340 // calculate the offsets within OatHeader to executable code
1341 size_t old_offset = offset;
Dave Allison50abf0a2014-06-23 13:19:59 -07001342 size_t adjusted_offset = offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001343 // required to be on a new page boundary
1344 offset = RoundUp(offset, kPageSize);
1345 oat_header_->SetExecutableOffset(offset);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001346 size_executable_offset_alignment_ = offset - old_offset;
1347 if (compiler_driver_->IsImage()) {
Alex Lighta59dd802014-07-02 16:28:08 -07001348 CHECK_EQ(image_patch_delta_, 0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001349 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001350
Ian Rogers848871b2013-08-05 10:56:33 -07001351 #define DO_TRAMPOLINE(field, fn_name) \
1352 offset = CompiledCode::AlignCode(offset, instruction_set); \
Dave Allison50abf0a2014-06-23 13:19:59 -07001353 adjusted_offset = offset + CompiledCode::CodeDelta(instruction_set); \
1354 oat_header_->Set ## fn_name ## Offset(adjusted_offset); \
Ian Rogers848871b2013-08-05 10:56:33 -07001355 field.reset(compiler_driver_->Create ## fn_name()); \
1356 offset += field->size();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001357
Ian Rogers848871b2013-08-05 10:56:33 -07001358 DO_TRAMPOLINE(interpreter_to_interpreter_bridge_, InterpreterToInterpreterBridge);
1359 DO_TRAMPOLINE(interpreter_to_compiled_code_bridge_, InterpreterToCompiledCodeBridge);
1360 DO_TRAMPOLINE(jni_dlsym_lookup_, JniDlsymLookup);
Andreas Gampe2da88232014-02-27 12:26:20 -08001361 DO_TRAMPOLINE(quick_generic_jni_trampoline_, QuickGenericJniTrampoline);
Jeff Hao88474b42013-10-23 16:24:40 -07001362 DO_TRAMPOLINE(quick_imt_conflict_trampoline_, QuickImtConflictTrampoline);
Ian Rogers848871b2013-08-05 10:56:33 -07001363 DO_TRAMPOLINE(quick_resolution_trampoline_, QuickResolutionTrampoline);
1364 DO_TRAMPOLINE(quick_to_interpreter_bridge_, QuickToInterpreterBridge);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001365
Ian Rogers848871b2013-08-05 10:56:33 -07001366 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001367 } else {
Ian Rogers848871b2013-08-05 10:56:33 -07001368 oat_header_->SetInterpreterToInterpreterBridgeOffset(0);
1369 oat_header_->SetInterpreterToCompiledCodeBridgeOffset(0);
1370 oat_header_->SetJniDlsymLookupOffset(0);
Andreas Gampe2da88232014-02-27 12:26:20 -08001371 oat_header_->SetQuickGenericJniTrampolineOffset(0);
Jeff Hao88474b42013-10-23 16:24:40 -07001372 oat_header_->SetQuickImtConflictTrampolineOffset(0);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001373 oat_header_->SetQuickResolutionTrampolineOffset(0);
Ian Rogers848871b2013-08-05 10:56:33 -07001374 oat_header_->SetQuickToInterpreterBridgeOffset(0);
Alex Lighta59dd802014-07-02 16:28:08 -07001375 oat_header_->SetImagePatchDelta(image_patch_delta_);
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001376 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001377 return offset;
1378}
1379
1380size_t OatWriter::InitOatCodeDexFiles(size_t offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001381 #define VISIT(VisitorType) \
1382 do { \
1383 VisitorType visitor(this, offset); \
1384 bool success = VisitDexMethods(&visitor); \
1385 DCHECK(success); \
1386 offset = visitor.GetOffset(); \
1387 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001388
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001389 VISIT(InitCodeMethodVisitor);
Ian Rogers1212a022013-03-04 10:48:41 -08001390 if (compiler_driver_->IsImage()) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001391 VISIT(InitImageMethodVisitor);
Ian Rogers0571d352011-11-03 19:51:38 -07001392 }
Logan Chien8b977d32012-02-21 19:14:55 +08001393
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001394 #undef VISIT
1395
Brian Carlstrome24fa612011-09-29 00:53:55 -07001396 return offset;
1397}
1398
Ian Rogers3d504072014-03-01 09:16:49 -08001399bool OatWriter::Write(OutputStream* out) {
Vladimir Markof4da6752014-08-01 19:04:18 +01001400 const off_t raw_file_offset = out->Seek(0, kSeekCurrent);
1401 if (raw_file_offset == (off_t) -1) {
1402 LOG(ERROR) << "Failed to get file offset in " << out->GetLocation();
1403 return false;
1404 }
1405 const size_t file_offset = static_cast<size_t>(raw_file_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001406
Vladimir Markof4da6752014-08-01 19:04:18 +01001407 // Reserve space for header. It will be written last - after updating the checksum.
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001408 size_t header_size = oat_header_->GetHeaderSize();
Vladimir Markof4da6752014-08-01 19:04:18 +01001409 if (out->Seek(header_size, kSeekCurrent) == (off_t) -1) {
1410 PLOG(ERROR) << "Failed to reserve space for oat header in " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001411 return false;
1412 }
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001413 size_oat_header_ += sizeof(OatHeader);
1414 size_oat_header_key_value_store_ += oat_header_->GetHeaderSize() - sizeof(OatHeader);
Brian Carlstrom81f3ca12012-03-17 00:27:35 -07001415
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001416 if (!WriteTables(out, file_offset)) {
Ian Rogers3d504072014-03-01 09:16:49 -08001417 LOG(ERROR) << "Failed to write oat tables to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001418 return false;
1419 }
1420
Vladimir Markof4da6752014-08-01 19:04:18 +01001421 off_t tables_end_offset = out->Seek(0, kSeekCurrent);
1422 if (tables_end_offset == (off_t) -1) {
1423 LOG(ERROR) << "Failed to seek to oat code position in " << out->GetLocation();
1424 return false;
1425 }
1426 size_t relative_offset = static_cast<size_t>(tables_end_offset) - file_offset;
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001427 relative_offset = WriteMaps(out, file_offset, relative_offset);
1428 if (relative_offset == 0) {
1429 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
1430 return false;
1431 }
1432
1433 relative_offset = WriteCode(out, file_offset, relative_offset);
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001434 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001435 LOG(ERROR) << "Failed to write oat code to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001436 return false;
1437 }
1438
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001439 relative_offset = WriteCodeDexFiles(out, file_offset, relative_offset);
1440 if (relative_offset == 0) {
Ian Rogers3d504072014-03-01 09:16:49 -08001441 LOG(ERROR) << "Failed to write oat code for dex files to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001442 return false;
1443 }
1444
Vladimir Markof4da6752014-08-01 19:04:18 +01001445 const off_t oat_end_file_offset = out->Seek(0, kSeekCurrent);
1446 if (oat_end_file_offset == (off_t) -1) {
1447 LOG(ERROR) << "Failed to get oat end file offset in " << out->GetLocation();
1448 return false;
1449 }
1450
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001451 if (kIsDebugBuild) {
1452 uint32_t size_total = 0;
1453 #define DO_STAT(x) \
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001454 VLOG(compiler) << #x "=" << PrettySize(x) << " (" << x << "B)"; \
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001455 size_total += x;
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001456
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001457 DO_STAT(size_dex_file_alignment_);
1458 DO_STAT(size_executable_offset_alignment_);
1459 DO_STAT(size_oat_header_);
Andreas Gampe22f8e5c2014-07-09 11:38:21 -07001460 DO_STAT(size_oat_header_key_value_store_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001461 DO_STAT(size_dex_file_);
Ian Rogers848871b2013-08-05 10:56:33 -07001462 DO_STAT(size_interpreter_to_interpreter_bridge_);
1463 DO_STAT(size_interpreter_to_compiled_code_bridge_);
1464 DO_STAT(size_jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001465 DO_STAT(size_quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001466 DO_STAT(size_quick_imt_conflict_trampoline_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001467 DO_STAT(size_quick_resolution_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001468 DO_STAT(size_quick_to_interpreter_bridge_);
1469 DO_STAT(size_trampoline_alignment_);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001470 DO_STAT(size_method_header_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001471 DO_STAT(size_code_);
1472 DO_STAT(size_code_alignment_);
Vladimir Markof4da6752014-08-01 19:04:18 +01001473 DO_STAT(size_relative_call_thunks_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001474 DO_STAT(size_mapping_table_);
1475 DO_STAT(size_vmap_table_);
1476 DO_STAT(size_gc_map_);
1477 DO_STAT(size_oat_dex_file_location_size_);
1478 DO_STAT(size_oat_dex_file_location_data_);
1479 DO_STAT(size_oat_dex_file_location_checksum_);
1480 DO_STAT(size_oat_dex_file_offset_);
1481 DO_STAT(size_oat_dex_file_methods_offsets_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001482 DO_STAT(size_oat_class_type_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001483 DO_STAT(size_oat_class_status_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001484 DO_STAT(size_oat_class_method_bitmaps_);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001485 DO_STAT(size_oat_class_method_offsets_);
1486 #undef DO_STAT
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001487
Anwar Ghuloum75a43f12013-08-13 17:22:14 -07001488 VLOG(compiler) << "size_total=" << PrettySize(size_total) << " (" << size_total << "B)"; \
Vladimir Markof4da6752014-08-01 19:04:18 +01001489 CHECK_EQ(file_offset + size_total, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001490 CHECK_EQ(size_, size_total);
Ian Rogers4bdbbc82013-06-10 16:02:31 -07001491 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001492
Vladimir Markof4da6752014-08-01 19:04:18 +01001493 CHECK_EQ(file_offset + size_, static_cast<size_t>(oat_end_file_offset));
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001494 CHECK_EQ(size_, relative_offset);
1495
Vladimir Markof4da6752014-08-01 19:04:18 +01001496 // Write the header now that the checksum is final.
1497 if (out->Seek(file_offset, kSeekSet) == (off_t) -1) {
1498 PLOG(ERROR) << "Failed to seek to oat header position in " << out->GetLocation();
1499 return false;
1500 }
1501 DCHECK_EQ(raw_file_offset, out->Seek(0, kSeekCurrent));
1502 if (!out->WriteFully(oat_header_, header_size)) {
1503 PLOG(ERROR) << "Failed to write oat header to " << out->GetLocation();
1504 return false;
1505 }
1506 if (out->Seek(oat_end_file_offset, kSeekSet) == (off_t) -1) {
1507 PLOG(ERROR) << "Failed to seek to end after writing oat header to " << out->GetLocation();
1508 return false;
1509 }
1510 DCHECK_EQ(oat_end_file_offset, out->Seek(0, kSeekCurrent));
1511
Brian Carlstrome24fa612011-09-29 00:53:55 -07001512 return true;
1513}
1514
Ian Rogers3d504072014-03-01 09:16:49 -08001515bool OatWriter::WriteTables(OutputStream* out, const size_t file_offset) {
Brian Carlstrome24fa612011-09-29 00:53:55 -07001516 for (size_t i = 0; i != oat_dex_files_.size(); ++i) {
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001517 if (!oat_dex_files_[i]->Write(this, out, file_offset)) {
Ian Rogers3d504072014-03-01 09:16:49 -08001518 PLOG(ERROR) << "Failed to write oat dex information to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001519 return false;
1520 }
1521 }
Brian Carlstrom89521892011-12-07 22:05:07 -08001522 for (size_t i = 0; i != oat_dex_files_.size(); ++i) {
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001523 uint32_t expected_offset = file_offset + oat_dex_files_[i]->dex_file_offset_;
Ian Rogers3d504072014-03-01 09:16:49 -08001524 off_t actual_offset = out->Seek(expected_offset, kSeekSet);
Brian Carlstrom89521892011-12-07 22:05:07 -08001525 if (static_cast<uint32_t>(actual_offset) != expected_offset) {
1526 const DexFile* dex_file = (*dex_files_)[i];
1527 PLOG(ERROR) << "Failed to seek to dex file section. Actual: " << actual_offset
1528 << " Expected: " << expected_offset << " File: " << dex_file->GetLocation();
1529 return false;
1530 }
1531 const DexFile* dex_file = (*dex_files_)[i];
Ian Rogers3d504072014-03-01 09:16:49 -08001532 if (!out->WriteFully(&dex_file->GetHeader(), dex_file->GetHeader().file_size_)) {
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001533 PLOG(ERROR) << "Failed to write dex file " << dex_file->GetLocation()
Ian Rogers3d504072014-03-01 09:16:49 -08001534 << " to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08001535 return false;
1536 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001537 size_dex_file_ += dex_file->GetHeader().file_size_;
Brian Carlstrom89521892011-12-07 22:05:07 -08001538 }
Brian Carlstrom389efb02012-01-11 12:06:26 -08001539 for (size_t i = 0; i != oat_classes_.size(); ++i) {
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001540 if (!oat_classes_[i]->Write(this, out, file_offset)) {
Ian Rogers3d504072014-03-01 09:16:49 -08001541 PLOG(ERROR) << "Failed to write oat methods information to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001542 return false;
1543 }
1544 }
1545 return true;
1546}
1547
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001548size_t OatWriter::WriteMaps(OutputStream* out, const size_t file_offset, size_t relative_offset) {
1549 #define VISIT(VisitorType) \
1550 do { \
1551 VisitorType visitor(this, out, file_offset, relative_offset); \
1552 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1553 return 0; \
1554 } \
1555 relative_offset = visitor.GetOffset(); \
1556 } while (false)
1557
1558 size_t gc_maps_offset = relative_offset;
1559 VISIT(WriteMapMethodVisitor<GcMapDataAccess>);
1560 size_gc_map_ = relative_offset - gc_maps_offset;
1561
1562 size_t mapping_tables_offset = relative_offset;
1563 VISIT(WriteMapMethodVisitor<MappingTableDataAccess>);
1564 size_mapping_table_ = relative_offset - mapping_tables_offset;
1565
1566 size_t vmap_tables_offset = relative_offset;
1567 VISIT(WriteMapMethodVisitor<VmapTableDataAccess>);
1568 size_vmap_table_ = relative_offset - vmap_tables_offset;
1569
1570 #undef VISIT
1571
1572 return relative_offset;
1573}
1574
1575size_t OatWriter::WriteCode(OutputStream* out, const size_t file_offset, size_t relative_offset) {
Ian Rogers3d504072014-03-01 09:16:49 -08001576 off_t new_offset = out->Seek(size_executable_offset_alignment_, kSeekCurrent);
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001577 relative_offset += size_executable_offset_alignment_;
1578 DCHECK_EQ(relative_offset, oat_header_->GetExecutableOffset());
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001579 size_t expected_file_offset = file_offset + relative_offset;
1580 if (static_cast<uint32_t>(new_offset) != expected_file_offset) {
Brian Carlstrom3320cf42011-10-04 14:58:28 -07001581 PLOG(ERROR) << "Failed to seek to oat code section. Actual: " << new_offset
Ian Rogers3d504072014-03-01 09:16:49 -08001582 << " Expected: " << expected_file_offset << " File: " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001583 return 0;
1584 }
Brian Carlstrom265091e2013-01-30 14:08:26 -08001585 DCHECK_OFFSET();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001586 if (compiler_driver_->IsImage()) {
1587 InstructionSet instruction_set = compiler_driver_->GetInstructionSet();
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001588
Ian Rogers848871b2013-08-05 10:56:33 -07001589 #define DO_TRAMPOLINE(field) \
1590 do { \
1591 uint32_t aligned_offset = CompiledCode::AlignCode(relative_offset, instruction_set); \
1592 uint32_t alignment_padding = aligned_offset - relative_offset; \
Ian Rogers3d504072014-03-01 09:16:49 -08001593 out->Seek(alignment_padding, kSeekCurrent); \
Ian Rogers848871b2013-08-05 10:56:33 -07001594 size_trampoline_alignment_ += alignment_padding; \
Ian Rogers3d504072014-03-01 09:16:49 -08001595 if (!out->WriteFully(&(*field)[0], field->size())) { \
1596 PLOG(ERROR) << "Failed to write " # field " to " << out->GetLocation(); \
Ian Rogers848871b2013-08-05 10:56:33 -07001597 return false; \
1598 } \
1599 size_ ## field += field->size(); \
1600 relative_offset += alignment_padding + field->size(); \
1601 DCHECK_OFFSET(); \
1602 } while (false)
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001603
Ian Rogers848871b2013-08-05 10:56:33 -07001604 DO_TRAMPOLINE(interpreter_to_interpreter_bridge_);
1605 DO_TRAMPOLINE(interpreter_to_compiled_code_bridge_);
1606 DO_TRAMPOLINE(jni_dlsym_lookup_);
Andreas Gampe2da88232014-02-27 12:26:20 -08001607 DO_TRAMPOLINE(quick_generic_jni_trampoline_);
Jeff Hao88474b42013-10-23 16:24:40 -07001608 DO_TRAMPOLINE(quick_imt_conflict_trampoline_);
Ian Rogers848871b2013-08-05 10:56:33 -07001609 DO_TRAMPOLINE(quick_resolution_trampoline_);
1610 DO_TRAMPOLINE(quick_to_interpreter_bridge_);
1611 #undef DO_TRAMPOLINE
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001612 }
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001613 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001614}
1615
Ian Rogers3d504072014-03-01 09:16:49 -08001616size_t OatWriter::WriteCodeDexFiles(OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001617 const size_t file_offset,
1618 size_t relative_offset) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001619 #define VISIT(VisitorType) \
1620 do { \
1621 VisitorType visitor(this, out, file_offset, relative_offset); \
1622 if (UNLIKELY(!VisitDexMethods(&visitor))) { \
1623 return 0; \
1624 } \
1625 relative_offset = visitor.GetOffset(); \
1626 } while (false)
Brian Carlstrome24fa612011-09-29 00:53:55 -07001627
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001628 VISIT(WriteCodeMethodVisitor);
Brian Carlstrome24fa612011-09-29 00:53:55 -07001629
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001630 #undef VISIT
Brian Carlstrom265091e2013-01-30 14:08:26 -08001631
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001632 return relative_offset;
Brian Carlstrome24fa612011-09-29 00:53:55 -07001633}
1634
Vladimir Markof4da6752014-08-01 19:04:18 +01001635bool OatWriter::WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta) {
1636 static const uint8_t kPadding[] = {
1637 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u
1638 };
1639 DCHECK_LE(aligned_code_delta, sizeof(kPadding));
1640 if (UNLIKELY(!out->WriteFully(kPadding, aligned_code_delta))) {
1641 return false;
1642 }
1643 size_code_alignment_ += aligned_code_delta;
1644 return true;
1645}
1646
Brian Carlstrom265091e2013-01-30 14:08:26 -08001647OatWriter::OatDexFile::OatDexFile(size_t offset, const DexFile& dex_file) {
1648 offset_ = offset;
Elliott Hughes95572412011-12-13 18:14:20 -08001649 const std::string& location(dex_file.GetLocation());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001650 dex_file_location_size_ = location.size();
1651 dex_file_location_data_ = reinterpret_cast<const uint8_t*>(location.data());
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001652 dex_file_location_checksum_ = dex_file.GetLocationChecksum();
Brian Carlstrom89521892011-12-07 22:05:07 -08001653 dex_file_offset_ = 0;
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -08001654 methods_offsets_.resize(dex_file.NumClassDefs());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001655}
1656
1657size_t OatWriter::OatDexFile::SizeOf() const {
1658 return sizeof(dex_file_location_size_)
1659 + dex_file_location_size_
Brian Carlstrom5b332c82012-02-01 15:02:31 -08001660 + sizeof(dex_file_location_checksum_)
Brian Carlstrom89521892011-12-07 22:05:07 -08001661 + sizeof(dex_file_offset_)
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -08001662 + (sizeof(methods_offsets_[0]) * methods_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001663}
1664
Ian Rogers3d504072014-03-01 09:16:49 -08001665void OatWriter::OatDexFile::UpdateChecksum(OatHeader* oat_header) const {
1666 oat_header->UpdateChecksum(&dex_file_location_size_, sizeof(dex_file_location_size_));
1667 oat_header->UpdateChecksum(dex_file_location_data_, dex_file_location_size_);
1668 oat_header->UpdateChecksum(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_));
1669 oat_header->UpdateChecksum(&dex_file_offset_, sizeof(dex_file_offset_));
1670 oat_header->UpdateChecksum(&methods_offsets_[0],
Brian Carlstrom6e3b1d92012-01-11 01:36:32 -08001671 sizeof(methods_offsets_[0]) * methods_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001672}
1673
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001674bool OatWriter::OatDexFile::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08001675 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001676 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08001677 DCHECK_OFFSET_();
Ian Rogers3d504072014-03-01 09:16:49 -08001678 if (!out->WriteFully(&dex_file_location_size_, sizeof(dex_file_location_size_))) {
1679 PLOG(ERROR) << "Failed to write dex file location length to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001680 return false;
1681 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001682 oat_writer->size_oat_dex_file_location_size_ += sizeof(dex_file_location_size_);
Ian Rogers3d504072014-03-01 09:16:49 -08001683 if (!out->WriteFully(dex_file_location_data_, dex_file_location_size_)) {
1684 PLOG(ERROR) << "Failed to write dex file location data to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001685 return false;
1686 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001687 oat_writer->size_oat_dex_file_location_data_ += dex_file_location_size_;
Ian Rogers3d504072014-03-01 09:16:49 -08001688 if (!out->WriteFully(&dex_file_location_checksum_, sizeof(dex_file_location_checksum_))) {
1689 PLOG(ERROR) << "Failed to write dex file location checksum to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001690 return false;
1691 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001692 oat_writer->size_oat_dex_file_location_checksum_ += sizeof(dex_file_location_checksum_);
Ian Rogers3d504072014-03-01 09:16:49 -08001693 if (!out->WriteFully(&dex_file_offset_, sizeof(dex_file_offset_))) {
1694 PLOG(ERROR) << "Failed to write dex file offset to " << out->GetLocation();
Brian Carlstrom89521892011-12-07 22:05:07 -08001695 return false;
1696 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001697 oat_writer->size_oat_dex_file_offset_ += sizeof(dex_file_offset_);
Ian Rogers3d504072014-03-01 09:16:49 -08001698 if (!out->WriteFully(&methods_offsets_[0],
Brian Carlstromcd60ac72013-01-20 17:09:51 -08001699 sizeof(methods_offsets_[0]) * methods_offsets_.size())) {
Ian Rogers3d504072014-03-01 09:16:49 -08001700 PLOG(ERROR) << "Failed to write methods offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001701 return false;
1702 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001703 oat_writer->size_oat_dex_file_methods_offsets_ +=
1704 sizeof(methods_offsets_[0]) * methods_offsets_.size();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001705 return true;
1706}
1707
Brian Carlstromba150c32013-08-27 17:31:03 -07001708OatWriter::OatClass::OatClass(size_t offset,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001709 const std::vector<CompiledMethod*>& compiled_methods,
Brian Carlstromba150c32013-08-27 17:31:03 -07001710 uint32_t num_non_null_compiled_methods,
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001711 mirror::Class::Status status)
1712 : compiled_methods_(compiled_methods) {
1713 uint32_t num_methods = compiled_methods.size();
Brian Carlstromba150c32013-08-27 17:31:03 -07001714 CHECK_LE(num_non_null_compiled_methods, num_methods);
1715
Brian Carlstrom265091e2013-01-30 14:08:26 -08001716 offset_ = offset;
Brian Carlstromba150c32013-08-27 17:31:03 -07001717 oat_method_offsets_offsets_from_oat_class_.resize(num_methods);
1718
1719 // Since both kOatClassNoneCompiled and kOatClassAllCompiled could
1720 // apply when there are 0 methods, we just arbitrarily say that 0
1721 // methods means kOatClassNoneCompiled and that we won't use
1722 // kOatClassAllCompiled unless there is at least one compiled
1723 // method. This means in an interpretter only system, we can assert
1724 // that all classes are kOatClassNoneCompiled.
1725 if (num_non_null_compiled_methods == 0) {
1726 type_ = kOatClassNoneCompiled;
1727 } else if (num_non_null_compiled_methods == num_methods) {
1728 type_ = kOatClassAllCompiled;
1729 } else {
1730 type_ = kOatClassSomeCompiled;
1731 }
1732
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001733 status_ = status;
Brian Carlstromba150c32013-08-27 17:31:03 -07001734 method_offsets_.resize(num_non_null_compiled_methods);
Vladimir Marko8a630572014-04-09 18:45:35 +01001735 method_headers_.resize(num_non_null_compiled_methods);
Brian Carlstromba150c32013-08-27 17:31:03 -07001736
1737 uint32_t oat_method_offsets_offset_from_oat_class = sizeof(type_) + sizeof(status_);
1738 if (type_ == kOatClassSomeCompiled) {
1739 method_bitmap_ = new BitVector(num_methods, false, Allocator::GetMallocAllocator());
1740 method_bitmap_size_ = method_bitmap_->GetSizeOf();
1741 oat_method_offsets_offset_from_oat_class += sizeof(method_bitmap_size_);
1742 oat_method_offsets_offset_from_oat_class += method_bitmap_size_;
1743 } else {
1744 method_bitmap_ = NULL;
1745 method_bitmap_size_ = 0;
1746 }
1747
1748 for (size_t i = 0; i < num_methods; i++) {
Vladimir Marko96c6ab92014-04-08 14:00:50 +01001749 CompiledMethod* compiled_method = compiled_methods_[i];
Brian Carlstromba150c32013-08-27 17:31:03 -07001750 if (compiled_method == NULL) {
1751 oat_method_offsets_offsets_from_oat_class_[i] = 0;
1752 } else {
1753 oat_method_offsets_offsets_from_oat_class_[i] = oat_method_offsets_offset_from_oat_class;
1754 oat_method_offsets_offset_from_oat_class += sizeof(OatMethodOffsets);
1755 if (type_ == kOatClassSomeCompiled) {
1756 method_bitmap_->SetBit(i);
1757 }
1758 }
1759 }
Brian Carlstrome24fa612011-09-29 00:53:55 -07001760}
1761
Brian Carlstromba150c32013-08-27 17:31:03 -07001762OatWriter::OatClass::~OatClass() {
Mathieu Chartier661974a2014-01-09 11:23:53 -08001763 delete method_bitmap_;
Brian Carlstromba150c32013-08-27 17:31:03 -07001764}
1765
Brian Carlstrom265091e2013-01-30 14:08:26 -08001766size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatHeader(
1767 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07001768 uint32_t method_offset = GetOatMethodOffsetsOffsetFromOatClass(class_def_method_index_);
1769 if (method_offset == 0) {
1770 return 0;
1771 }
1772 return offset_ + method_offset;
Brian Carlstrom265091e2013-01-30 14:08:26 -08001773}
1774
1775size_t OatWriter::OatClass::GetOatMethodOffsetsOffsetFromOatClass(
1776 size_t class_def_method_index_) const {
Brian Carlstromba150c32013-08-27 17:31:03 -07001777 return oat_method_offsets_offsets_from_oat_class_[class_def_method_index_];
Brian Carlstrom265091e2013-01-30 14:08:26 -08001778}
1779
1780size_t OatWriter::OatClass::SizeOf() const {
Brian Carlstromba150c32013-08-27 17:31:03 -07001781 return sizeof(status_)
1782 + sizeof(type_)
1783 + ((method_bitmap_size_ == 0) ? 0 : sizeof(method_bitmap_size_))
1784 + method_bitmap_size_
1785 + (sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001786}
1787
Ian Rogers3d504072014-03-01 09:16:49 -08001788void OatWriter::OatClass::UpdateChecksum(OatHeader* oat_header) const {
1789 oat_header->UpdateChecksum(&status_, sizeof(status_));
1790 oat_header->UpdateChecksum(&type_, sizeof(type_));
Brian Carlstromba150c32013-08-27 17:31:03 -07001791 if (method_bitmap_size_ != 0) {
1792 CHECK_EQ(kOatClassSomeCompiled, type_);
Ian Rogers3d504072014-03-01 09:16:49 -08001793 oat_header->UpdateChecksum(&method_bitmap_size_, sizeof(method_bitmap_size_));
1794 oat_header->UpdateChecksum(method_bitmap_->GetRawStorage(), method_bitmap_size_);
Brian Carlstromba150c32013-08-27 17:31:03 -07001795 }
Ian Rogers3d504072014-03-01 09:16:49 -08001796 oat_header->UpdateChecksum(&method_offsets_[0],
1797 sizeof(method_offsets_[0]) * method_offsets_.size());
Brian Carlstrome24fa612011-09-29 00:53:55 -07001798}
1799
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001800bool OatWriter::OatClass::Write(OatWriter* oat_writer,
Ian Rogers3d504072014-03-01 09:16:49 -08001801 OutputStream* out,
Brian Carlstromc50d8e12013-07-23 22:35:16 -07001802 const size_t file_offset) const {
Brian Carlstrom265091e2013-01-30 14:08:26 -08001803 DCHECK_OFFSET_();
Ian Rogers3d504072014-03-01 09:16:49 -08001804 if (!out->WriteFully(&status_, sizeof(status_))) {
1805 PLOG(ERROR) << "Failed to write class status to " << out->GetLocation();
Brian Carlstrom0755ec52012-01-11 15:19:46 -08001806 return false;
1807 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001808 oat_writer->size_oat_class_status_ += sizeof(status_);
Ian Rogers3d504072014-03-01 09:16:49 -08001809 if (!out->WriteFully(&type_, sizeof(type_))) {
1810 PLOG(ERROR) << "Failed to write oat class type to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07001811 return false;
1812 }
1813 oat_writer->size_oat_class_type_ += sizeof(type_);
1814 if (method_bitmap_size_ != 0) {
1815 CHECK_EQ(kOatClassSomeCompiled, type_);
Ian Rogers3d504072014-03-01 09:16:49 -08001816 if (!out->WriteFully(&method_bitmap_size_, sizeof(method_bitmap_size_))) {
1817 PLOG(ERROR) << "Failed to write method bitmap size to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07001818 return false;
1819 }
1820 oat_writer->size_oat_class_method_bitmaps_ += sizeof(method_bitmap_size_);
Ian Rogers3d504072014-03-01 09:16:49 -08001821 if (!out->WriteFully(method_bitmap_->GetRawStorage(), method_bitmap_size_)) {
1822 PLOG(ERROR) << "Failed to write method bitmap to " << out->GetLocation();
Brian Carlstromba150c32013-08-27 17:31:03 -07001823 return false;
1824 }
1825 oat_writer->size_oat_class_method_bitmaps_ += method_bitmap_size_;
1826 }
Ian Rogers3d504072014-03-01 09:16:49 -08001827 if (!out->WriteFully(&method_offsets_[0],
Brian Carlstromcd60ac72013-01-20 17:09:51 -08001828 sizeof(method_offsets_[0]) * method_offsets_.size())) {
Ian Rogers3d504072014-03-01 09:16:49 -08001829 PLOG(ERROR) << "Failed to write method offsets to " << out->GetLocation();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001830 return false;
1831 }
Jeff Hao0aba0ba2013-06-03 14:49:28 -07001832 oat_writer->size_oat_class_method_offsets_ += sizeof(method_offsets_[0]) * method_offsets_.size();
Brian Carlstrome24fa612011-09-29 00:53:55 -07001833 return true;
1834}
1835
Brian Carlstrome24fa612011-09-29 00:53:55 -07001836} // namespace art