blob: 2b4144c6117ce8f804f90dc788a55bdcfb07706a [file] [log] [blame]
Mathieu Chartierf95a75e2017-11-03 15:25:52 -07001/*
2 * Copyright (C) 2017 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 */
16
17#include "compact_dex_writer.h"
18
Mathieu Chartier05f90d12018-02-07 13:47:17 -080019#include "android-base/stringprintf.h"
Mathieu Chartier8892c6b2018-01-09 15:10:17 -080020#include "base/logging.h"
21#include "base/time_utils.h"
David Sehr9e734c72018-01-04 17:56:19 -080022#include "dex/compact_dex_file.h"
Mathieu Chartier5e3cfa22018-02-20 16:53:37 -080023#include "dex/compact_offset_table.h"
Mathieu Chartier8892c6b2018-01-09 15:10:17 -080024#include "dexlayout.h"
Mathieu Chartierf95a75e2017-11-03 15:25:52 -070025
26namespace art {
27
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -080028CompactDexWriter::CompactDexWriter(DexLayout* dex_layout)
29 : DexWriter(dex_layout, /*compute_offsets*/ true) {
30 CHECK(GetCompactDexLevel() != CompactDexLevel::kCompactDexLevelNone);
Mathieu Chartier66c9df12018-01-16 14:45:20 -080031}
32
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -080033CompactDexLevel CompactDexWriter::GetCompactDexLevel() const {
34 return dex_layout_->GetOptions().compact_dex_level_;
35}
36
37CompactDexWriter::Container::Container(bool dedupe_code_items)
Mathieu Chartierb81ecad2018-01-23 22:08:26 -080038 : code_item_dedupe_(dedupe_code_items, &data_section_),
39 data_item_dedupe_(/*dedupe*/ true, &data_section_) {}
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -080040
41uint32_t CompactDexWriter::WriteDebugInfoOffsetTable(Stream* stream) {
42 const uint32_t start_offset = stream->Tell();
Mathieu Chartier8892c6b2018-01-09 15:10:17 -080043 const dex_ir::Collections& collections = header_->GetCollections();
44 // Debug offsets for method indexes. 0 means no debug info.
45 std::vector<uint32_t> debug_info_offsets(collections.MethodIdsSize(), 0u);
46
47 static constexpr InvokeType invoke_types[] = {
48 kDirect,
49 kVirtual
50 };
51
52 for (InvokeType invoke_type : invoke_types) {
53 for (const std::unique_ptr<dex_ir::ClassDef>& class_def : collections.ClassDefs()) {
54 // Skip classes that are not defined in this dex file.
55 dex_ir::ClassData* class_data = class_def->GetClassData();
56 if (class_data == nullptr) {
57 continue;
58 }
59 for (auto& method : *(invoke_type == InvokeType::kDirect
60 ? class_data->DirectMethods()
61 : class_data->VirtualMethods())) {
62 const dex_ir::MethodId* method_id = method->GetMethodId();
63 dex_ir::CodeItem* code_item = method->GetCodeItem();
64 if (code_item != nullptr && code_item->DebugInfo() != nullptr) {
65 const uint32_t debug_info_offset = code_item->DebugInfo()->GetOffset();
66 const uint32_t method_idx = method_id->GetIndex();
67 if (debug_info_offsets[method_idx] != 0u) {
68 CHECK_EQ(debug_info_offset, debug_info_offsets[method_idx]);
69 }
70 debug_info_offsets[method_idx] = debug_info_offset;
71 }
72 }
73 }
74 }
75
76 std::vector<uint8_t> data;
77 debug_info_base_ = 0u;
78 debug_info_offsets_table_offset_ = 0u;
Mathieu Chartier5e3cfa22018-02-20 16:53:37 -080079 CompactOffsetTable::Build(debug_info_offsets,
80 &data,
81 &debug_info_base_,
82 &debug_info_offsets_table_offset_);
Mathieu Chartier8892c6b2018-01-09 15:10:17 -080083 // Align the table and write it out.
Mathieu Chartier5e3cfa22018-02-20 16:53:37 -080084 stream->AlignTo(CompactOffsetTable::kAlignment);
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -080085 debug_info_offsets_pos_ = stream->Tell();
86 stream->Write(data.data(), data.size());
Mathieu Chartier8892c6b2018-01-09 15:10:17 -080087
88 // Verify that the whole table decodes as expected and measure average performance.
89 const bool kMeasureAndTestOutput = dex_layout_->GetOptions().verify_output_;
90 if (kMeasureAndTestOutput && !debug_info_offsets.empty()) {
91 uint64_t start_time = NanoTime();
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -080092 stream->Begin();
Mathieu Chartier5e3cfa22018-02-20 16:53:37 -080093 CompactOffsetTable::Accessor accessor(stream->Begin() + debug_info_offsets_pos_,
94 debug_info_base_,
95 debug_info_offsets_table_offset_);
Mathieu Chartier8892c6b2018-01-09 15:10:17 -080096
97 for (size_t i = 0; i < debug_info_offsets.size(); ++i) {
Mathieu Chartier5e3cfa22018-02-20 16:53:37 -080098 CHECK_EQ(accessor.GetOffset(i), debug_info_offsets[i]);
Mathieu Chartier8892c6b2018-01-09 15:10:17 -080099 }
100 uint64_t end_time = NanoTime();
101 VLOG(dex) << "Average lookup time (ns) for debug info offsets: "
102 << (end_time - start_time) / debug_info_offsets.size();
103 }
104
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800105 return stream->Tell() - start_offset;
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800106}
107
Mathieu Chartierb81ecad2018-01-23 22:08:26 -0800108CompactDexWriter::ScopedDataSectionItem::ScopedDataSectionItem(Stream* stream,
109 dex_ir::Item* item,
110 size_t alignment,
111 Deduper* deduper)
112 : stream_(stream),
113 item_(item),
114 alignment_(alignment),
115 deduper_(deduper),
116 start_offset_(stream->Tell()) {
117 stream_->AlignTo(alignment_);
118}
119
120CompactDexWriter::ScopedDataSectionItem::~ScopedDataSectionItem() {
121 // After having written, maybe dedupe the whole code item (excluding padding).
122 const uint32_t deduped_offset = deduper_->Dedupe(start_offset_,
123 stream_->Tell(),
124 item_->GetOffset());
Mathieu Chartier807b21b2018-01-29 05:18:24 -0800125 // If we deduped, only use the deduped offset if the alignment matches the required alignment.
126 // Otherwise, return without deduping.
Mathieu Chartierb81ecad2018-01-23 22:08:26 -0800127 if (deduped_offset != Deduper::kDidNotDedupe && IsAlignedParam(deduped_offset, alignment_)) {
Mathieu Chartier807b21b2018-01-29 05:18:24 -0800128 // Update the IR offset to the offset of the deduped item.
Mathieu Chartierb81ecad2018-01-23 22:08:26 -0800129 item_->SetOffset(deduped_offset);
Mathieu Chartier807b21b2018-01-29 05:18:24 -0800130 // Clear the written data for the item so that the stream write doesn't abort in the future.
Mathieu Chartierb81ecad2018-01-23 22:08:26 -0800131 stream_->Clear(start_offset_, stream_->Tell() - start_offset_);
Mathieu Chartier807b21b2018-01-29 05:18:24 -0800132 // Since we deduped, restore the offset to the original position.
Mathieu Chartierb81ecad2018-01-23 22:08:26 -0800133 stream_->Seek(start_offset_);
134 }
135}
136
137size_t CompactDexWriter::ScopedDataSectionItem::Written() const {
138 return stream_->Tell() - start_offset_;
139}
140
141void CompactDexWriter::WriteCodeItem(Stream* stream,
142 dex_ir::CodeItem* code_item,
143 bool reserve_only) {
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800144 DCHECK(code_item != nullptr);
Mathieu Chartier66c9df12018-01-16 14:45:20 -0800145 DCHECK(!reserve_only) << "Not supported because of deduping.";
Mathieu Chartierb81ecad2018-01-23 22:08:26 -0800146 ScopedDataSectionItem data_item(stream,
147 code_item,
148 CompactDexFile::CodeItem::kAlignment,
149 code_item_dedupe_);
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800150
151 CompactDexFile::CodeItem disk_code_item;
Mathieu Chartier8740c662018-01-11 14:50:02 -0800152
153 uint16_t preheader_storage[CompactDexFile::CodeItem::kMaxPreHeaderSize] = {};
154 uint16_t* preheader_end = preheader_storage + CompactDexFile::CodeItem::kMaxPreHeaderSize;
155 const uint16_t* preheader = disk_code_item.Create(
156 code_item->RegistersSize(),
157 code_item->InsSize(),
158 code_item->OutsSize(),
159 code_item->TriesSize(),
160 code_item->InsnsSize(),
161 preheader_end);
162 const size_t preheader_bytes = (preheader_end - preheader) * sizeof(preheader[0]);
163
164 static constexpr size_t kPayloadInstructionRequiredAlignment = 4;
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800165 const uint32_t current_code_item_start = stream->Tell() + preheader_bytes;
Mathieu Chartiera27af082018-02-03 16:12:23 -0800166 if (!IsAlignedParam(current_code_item_start, kPayloadInstructionRequiredAlignment) ||
167 kIsDebugBuild) {
Mathieu Chartier8740c662018-01-11 14:50:02 -0800168 // If the preheader is going to make the code unaligned, consider adding 2 bytes of padding
169 // before if required.
Mathieu Chartiera27af082018-02-03 16:12:23 -0800170 IterationRange<DexInstructionIterator> instructions = code_item->Instructions();
171 SafeDexInstructionIterator it(instructions.begin(), instructions.end());
172 for (; !it.IsErrorState() && it < instructions.end(); ++it) {
173 // In case the instruction goes past the end of the code item, make sure to not process it.
174 if (std::next(it).IsErrorState()) {
175 break;
176 }
177 const Instruction::Code opcode = it->Opcode();
Mathieu Chartier8740c662018-01-11 14:50:02 -0800178 // Payload instructions possibly require special alignment for their data.
179 if (opcode == Instruction::FILL_ARRAY_DATA ||
180 opcode == Instruction::PACKED_SWITCH ||
181 opcode == Instruction::SPARSE_SWITCH) {
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800182 stream->Skip(
183 RoundUp(current_code_item_start, kPayloadInstructionRequiredAlignment) -
184 current_code_item_start);
Mathieu Chartier8740c662018-01-11 14:50:02 -0800185 break;
186 }
187 }
188 }
189
190 // Write preheader first.
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800191 stream->Write(reinterpret_cast<const uint8_t*>(preheader), preheader_bytes);
Mathieu Chartier8740c662018-01-11 14:50:02 -0800192 // Registered offset is after the preheader.
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800193 ProcessOffset(stream, code_item);
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800194 // Avoid using sizeof so that we don't write the fake instruction array at the end of the code
195 // item.
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800196 stream->Write(&disk_code_item, OFFSETOF_MEMBER(CompactDexFile::CodeItem, insns_));
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800197 // Write the instructions.
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800198 stream->Write(code_item->Insns(), code_item->InsnsSize() * sizeof(uint16_t));
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800199 // Write the post instruction data.
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800200 WriteCodeItemPostInstructionData(stream, code_item, reserve_only);
Mathieu Chartierb81ecad2018-01-23 22:08:26 -0800201}
Mathieu Chartier66c9df12018-01-16 14:45:20 -0800202
Mathieu Chartierb81ecad2018-01-23 22:08:26 -0800203void CompactDexWriter::WriteDebugInfoItem(Stream* stream, dex_ir::DebugInfoItem* debug_info) {
204 ScopedDataSectionItem data_item(stream,
205 debug_info,
206 SectionAlignment(DexFile::kDexTypeDebugInfoItem),
207 data_item_dedupe_);
208 ProcessOffset(stream, debug_info);
209 stream->Write(debug_info->GetDebugInfo(), debug_info->GetDebugInfoSize());
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800210}
211
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800212
213CompactDexWriter::Deduper::Deduper(bool enabled, DexContainer::Section* section)
214 : enabled_(enabled),
215 dedupe_map_(/*bucket_count*/ 32,
216 HashedMemoryRange::HashEqual(section),
217 HashedMemoryRange::HashEqual(section)) {}
218
219uint32_t CompactDexWriter::Deduper::Dedupe(uint32_t data_start,
220 uint32_t data_end,
221 uint32_t item_offset) {
222 if (!enabled_) {
223 return kDidNotDedupe;
224 }
Mathieu Chartier66c9df12018-01-16 14:45:20 -0800225 HashedMemoryRange range {data_start, data_end - data_start};
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800226 auto existing = dedupe_map_.emplace(range, item_offset);
Mathieu Chartier66c9df12018-01-16 14:45:20 -0800227 if (!existing.second) {
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800228 // Failed to insert means we deduped, return the existing item offset.
Mathieu Chartier66c9df12018-01-16 14:45:20 -0800229 return existing.first->second;
230 }
231 return kDidNotDedupe;
232}
233
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800234void CompactDexWriter::SortDebugInfosByMethodIndex() {
235 dex_ir::Collections& collections = header_->GetCollections();
236 static constexpr InvokeType invoke_types[] = {
237 kDirect,
238 kVirtual
239 };
240 std::map<const dex_ir::DebugInfoItem*, uint32_t> method_idx_map;
241 for (InvokeType invoke_type : invoke_types) {
242 for (std::unique_ptr<dex_ir::ClassDef>& class_def : collections.ClassDefs()) {
243 // Skip classes that are not defined in this dex file.
244 dex_ir::ClassData* class_data = class_def->GetClassData();
245 if (class_data == nullptr) {
246 continue;
247 }
248 for (auto& method : *(invoke_type == InvokeType::kDirect
249 ? class_data->DirectMethods()
250 : class_data->VirtualMethods())) {
251 const dex_ir::MethodId* method_id = method->GetMethodId();
252 dex_ir::CodeItem* code_item = method->GetCodeItem();
253 if (code_item != nullptr && code_item->DebugInfo() != nullptr) {
254 const dex_ir::DebugInfoItem* debug_item = code_item->DebugInfo();
255 method_idx_map.insert(std::make_pair(debug_item, method_id->GetIndex()));
256 }
257 }
258 }
259 }
260 std::sort(collections.DebugInfoItems().begin(),
261 collections.DebugInfoItems().end(),
262 [&](const std::unique_ptr<dex_ir::DebugInfoItem>& a,
263 const std::unique_ptr<dex_ir::DebugInfoItem>& b) {
264 auto it_a = method_idx_map.find(a.get());
265 auto it_b = method_idx_map.find(b.get());
266 uint32_t idx_a = it_a != method_idx_map.end() ? it_a->second : 0u;
267 uint32_t idx_b = it_b != method_idx_map.end() ? it_b->second : 0u;
268 return idx_a < idx_b;
269 });
270}
271
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800272void CompactDexWriter::WriteHeader(Stream* stream) {
Mathieu Chartierf95a75e2017-11-03 15:25:52 -0700273 CompactDexFile::Header header;
274 CompactDexFile::WriteMagic(&header.magic_[0]);
275 CompactDexFile::WriteCurrentVersion(&header.magic_[0]);
276 header.checksum_ = header_->Checksum();
277 std::copy_n(header_->Signature(), DexFile::kSha1DigestSize, header.signature_);
278 header.file_size_ = header_->FileSize();
Mathieu Chartierf6e31472017-12-28 13:32:08 -0800279 // Since we are not necessarily outputting the same format as the input, avoid using the stored
280 // header size.
281 header.header_size_ = GetHeaderSize();
Mathieu Chartierf95a75e2017-11-03 15:25:52 -0700282 header.endian_tag_ = header_->EndianTag();
283 header.link_size_ = header_->LinkSize();
284 header.link_off_ = header_->LinkOffset();
285 const dex_ir::Collections& collections = header_->GetCollections();
286 header.map_off_ = collections.MapListOffset();
287 header.string_ids_size_ = collections.StringIdsSize();
288 header.string_ids_off_ = collections.StringIdsOffset();
289 header.type_ids_size_ = collections.TypeIdsSize();
290 header.type_ids_off_ = collections.TypeIdsOffset();
291 header.proto_ids_size_ = collections.ProtoIdsSize();
292 header.proto_ids_off_ = collections.ProtoIdsOffset();
293 header.field_ids_size_ = collections.FieldIdsSize();
294 header.field_ids_off_ = collections.FieldIdsOffset();
295 header.method_ids_size_ = collections.MethodIdsSize();
296 header.method_ids_off_ = collections.MethodIdsOffset();
297 header.class_defs_size_ = collections.ClassDefsSize();
298 header.class_defs_off_ = collections.ClassDefsOffset();
299 header.data_size_ = header_->DataSize();
300 header.data_off_ = header_->DataOffset();
Mathieu Chartier6f716502018-03-14 14:00:04 -0700301 header.owned_data_begin_ = owned_data_begin_;
302 header.owned_data_end_ = owned_data_end_;
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800303
304 // Compact dex specific flags.
305 header.debug_info_offsets_pos_ = debug_info_offsets_pos_;
306 header.debug_info_offsets_table_offset_ = debug_info_offsets_table_offset_;
307 header.debug_info_base_ = debug_info_base_;
Mathieu Chartierf6e31472017-12-28 13:32:08 -0800308 header.feature_flags_ = 0u;
309 // In cases where apps are converted to cdex during install, maintain feature flags so that
310 // the verifier correctly verifies apps that aren't targetting default methods.
311 if (header_->SupportDefaultMethods()) {
312 header.feature_flags_ |= static_cast<uint32_t>(CompactDexFile::FeatureFlags::kDefaultMethods);
313 }
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800314 stream->Seek(0);
315 stream->Overwrite(reinterpret_cast<uint8_t*>(&header), sizeof(header));
Mathieu Chartierf95a75e2017-11-03 15:25:52 -0700316}
317
Mathieu Chartierf6e31472017-12-28 13:32:08 -0800318size_t CompactDexWriter::GetHeaderSize() const {
319 return sizeof(CompactDexFile::Header);
320}
321
Mathieu Chartierb81ecad2018-01-23 22:08:26 -0800322void CompactDexWriter::WriteStringData(Stream* stream, dex_ir::StringData* string_data) {
323 ScopedDataSectionItem data_item(stream,
324 string_data,
325 SectionAlignment(DexFile::kDexTypeStringDataItem),
326 data_item_dedupe_);
327 ProcessOffset(stream, string_data);
328 stream->WriteUleb128(CountModifiedUtf8Chars(string_data->Data()));
329 stream->Write(string_data->Data(), strlen(string_data->Data()));
330 // Skip null terminator (already zeroed out, no need to write).
331 stream->Skip(1);
332}
333
Mathieu Chartier05f90d12018-02-07 13:47:17 -0800334bool CompactDexWriter::CanGenerateCompactDex(std::string* error_msg) {
335 dex_ir::Collections& collections = header_->GetCollections();
336 static constexpr InvokeType invoke_types[] = {
337 kDirect,
338 kVirtual
339 };
340 std::vector<bool> saw_method_id(collections.MethodIdsSize(), false);
341 std::vector<dex_ir::CodeItem*> method_id_code_item(collections.MethodIdsSize(), nullptr);
342 std::vector<dex_ir::DebugInfoItem*> method_id_debug_info(collections.MethodIdsSize(), nullptr);
343 for (InvokeType invoke_type : invoke_types) {
344 for (std::unique_ptr<dex_ir::ClassDef>& class_def : collections.ClassDefs()) {
345 // Skip classes that are not defined in this dex file.
346 dex_ir::ClassData* class_data = class_def->GetClassData();
347 if (class_data == nullptr) {
348 continue;
349 }
350 for (auto& method : *(invoke_type == InvokeType::kDirect
351 ? class_data->DirectMethods()
352 : class_data->VirtualMethods())) {
353 const uint32_t idx = method->GetMethodId()->GetIndex();
354 dex_ir::CodeItem* code_item = method->GetCodeItem();
355 dex_ir:: DebugInfoItem* debug_info_item = nullptr;
356 if (code_item != nullptr) {
357 debug_info_item = code_item->DebugInfo();
358 }
359 if (saw_method_id[idx]) {
360 if (method_id_code_item[idx] != code_item) {
361 *error_msg = android::base::StringPrintf("Conflicting code item for method id %u",
362 idx);
363 // Conflicting info, abort generation.
364 return false;
365 }
366 if (method_id_debug_info[idx] != debug_info_item) {
367 *error_msg = android::base::StringPrintf("Conflicting debug info for method id %u",
368 idx);
369 // Conflicting info, abort generation.
370 return false;
371 }
372 }
373 method_id_code_item[idx] = code_item;
374 method_id_debug_info[idx] = debug_info_item;
375 saw_method_id[idx] = true;
376 }
377 }
378 }
379 return true;
380}
381
382bool CompactDexWriter::Write(DexContainer* output, std::string* error_msg) {
383 DCHECK(error_msg != nullptr);
Mathieu Chartier9b302bf2018-01-25 13:08:08 -0800384 CHECK(compute_offsets_);
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800385 CHECK(output->IsCompactDexContainer());
Mathieu Chartier05f90d12018-02-07 13:47:17 -0800386
387 if (!CanGenerateCompactDex(error_msg)) {
388 return false;
389 }
390
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800391 Container* const container = down_cast<Container*>(output);
392 // For now, use the same stream for both data and metadata.
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -0800393 Stream temp_main_stream(output->GetMainSection());
Mathieu Chartierb81ecad2018-01-23 22:08:26 -0800394 CHECK_EQ(output->GetMainSection()->Size(), 0u);
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -0800395 Stream temp_data_stream(output->GetDataSection());
396 Stream* main_stream = &temp_main_stream;
397 Stream* data_stream = &temp_data_stream;
398
399 // We want offset 0 to be reserved for null, seek to the data section alignment or the end of the
400 // section.
401 data_stream->Seek(std::max(
402 static_cast<uint32_t>(output->GetDataSection()->Size()),
403 kDataSectionAlignment));
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800404 code_item_dedupe_ = &container->code_item_dedupe_;
Mathieu Chartierb81ecad2018-01-23 22:08:26 -0800405 data_item_dedupe_ = &container->data_item_dedupe_;
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800406
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800407 // Starting offset is right after the header.
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800408 main_stream->Seek(GetHeaderSize());
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800409
410 dex_ir::Collections& collection = header_->GetCollections();
411
412 // Based on: https://source.android.com/devices/tech/dalvik/dex-format
413 // Since the offsets may not be calculated already, the writing must be done in the correct order.
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800414 const uint32_t string_ids_offset = main_stream->Tell();
415 WriteStringIds(main_stream, /*reserve_only*/ true);
416 WriteTypeIds(main_stream);
417 const uint32_t proto_ids_offset = main_stream->Tell();
418 WriteProtoIds(main_stream, /*reserve_only*/ true);
419 WriteFieldIds(main_stream);
420 WriteMethodIds(main_stream);
421 const uint32_t class_defs_offset = main_stream->Tell();
422 WriteClassDefs(main_stream, /*reserve_only*/ true);
423 const uint32_t call_site_ids_offset = main_stream->Tell();
424 WriteCallSiteIds(main_stream, /*reserve_only*/ true);
425 WriteMethodHandles(main_stream);
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800426
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800427 if (compute_offsets_) {
428 // Data section.
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800429 data_stream->AlignTo(kDataSectionAlignment);
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800430 }
Mathieu Chartier6f716502018-03-14 14:00:04 -0700431 owned_data_begin_ = data_stream->Tell();
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800432
433 // Write code item first to minimize the space required for encoded methods.
434 // For cdex, the code items don't depend on the debug info.
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800435 WriteCodeItems(data_stream, /*reserve_only*/ false);
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800436
437 // Sort the debug infos by method index order, this reduces size by ~0.1% by reducing the size of
438 // the debug info offset table.
439 SortDebugInfosByMethodIndex();
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800440 WriteDebugInfoItems(data_stream);
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800441
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800442 WriteEncodedArrays(data_stream);
443 WriteAnnotations(data_stream);
444 WriteAnnotationSets(data_stream);
445 WriteAnnotationSetRefs(data_stream);
446 WriteAnnotationsDirectories(data_stream);
447 WriteTypeLists(data_stream);
448 WriteClassDatas(data_stream);
449 WriteStringDatas(data_stream);
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800450
451 // Write delayed id sections that depend on data sections.
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800452 {
453 Stream::ScopedSeek seek(main_stream, string_ids_offset);
454 WriteStringIds(main_stream, /*reserve_only*/ false);
455 }
456 {
457 Stream::ScopedSeek seek(main_stream, proto_ids_offset);
458 WriteProtoIds(main_stream, /*reserve_only*/ false);
459 }
460 {
461 Stream::ScopedSeek seek(main_stream, class_defs_offset);
462 WriteClassDefs(main_stream, /*reserve_only*/ false);
463 }
464 {
465 Stream::ScopedSeek seek(main_stream, call_site_ids_offset);
466 WriteCallSiteIds(main_stream, /*reserve_only*/ false);
467 }
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800468
469 // Write the map list.
470 if (compute_offsets_) {
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800471 data_stream->AlignTo(SectionAlignment(DexFile::kDexTypeMapList));
472 collection.SetMapListOffset(data_stream->Tell());
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800473 } else {
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800474 data_stream->Seek(collection.MapListOffset());
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800475 }
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800476
477 // Map items are included in the data section.
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -0800478 GenerateAndWriteMapItems(data_stream);
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800479
480 // Write link data if it exists.
481 const std::vector<uint8_t>& link_data = collection.LinkData();
482 if (link_data.size() > 0) {
483 CHECK_EQ(header_->LinkSize(), static_cast<uint32_t>(link_data.size()));
484 if (compute_offsets_) {
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800485 header_->SetLinkOffset(data_stream->Tell());
486 } else {
487 data_stream->Seek(header_->LinkOffset());
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800488 }
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800489 data_stream->Write(&link_data[0], link_data.size());
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800490 }
491
492 // Write debug info offset table last to make dex file verifier happy.
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800493 WriteDebugInfoOffsetTable(data_stream);
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800494
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -0800495 data_stream->AlignTo(kDataSectionAlignment);
Mathieu Chartier6f716502018-03-14 14:00:04 -0700496 owned_data_end_ = data_stream->Tell();
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -0800497 if (compute_offsets_) {
498 header_->SetDataSize(data_stream->Tell());
499 if (header_->DataSize() != 0) {
500 // Offset must be zero when the size is zero.
501 main_stream->AlignTo(kDataSectionAlignment);
502 // For now, default to saying the data is right after the main stream.
503 header_->SetDataOffset(main_stream->Tell());
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -0800504 } else {
505 header_->SetDataOffset(0u);
506 }
507 }
508
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800509 // Write header last.
510 if (compute_offsets_) {
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800511 header_->SetFileSize(main_stream->Tell());
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800512 }
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800513 WriteHeader(main_stream);
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800514
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -0800515 // Trim sections to make sure they are sized properly.
516 output->GetMainSection()->Resize(header_->FileSize());
517 output->GetDataSection()->Resize(data_stream->Tell());
518
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800519 if (dex_layout_->GetOptions().update_checksum_) {
Mathieu Chartierc3a22aa2018-01-19 18:58:34 -0800520 // Compute the cdex section (also covers the used part of the data section).
521 header_->SetChecksum(CompactDexFile::CalculateChecksum(output->GetMainSection()->Begin(),
522 output->GetMainSection()->Size(),
523 output->GetDataSection()->Begin(),
524 output->GetDataSection()->Size()));
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800525 // Rewrite the header with the calculated checksum.
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800526 WriteHeader(main_stream);
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800527 }
Mathieu Chartier279e3a32018-01-24 18:17:55 -0800528
529 // Clear the dedupe to prevent interdex code item deduping. This does not currently work well with
530 // dex2oat's class unloading. The issue is that verification encounters quickened opcodes after
531 // the first dex gets unloaded.
532 code_item_dedupe_->Clear();
Mathieu Chartier05f90d12018-02-07 13:47:17 -0800533
534 return true;
Mathieu Chartiere6b6ff82018-01-19 18:58:34 -0800535}
536
537std::unique_ptr<DexContainer> CompactDexWriter::CreateDexContainer() const {
538 return std::unique_ptr<DexContainer>(
539 new CompactDexWriter::Container(dex_layout_->GetOptions().dedupe_code_items_));
Mathieu Chartier8892c6b2018-01-09 15:10:17 -0800540}
541
Mathieu Chartierf95a75e2017-11-03 15:25:52 -0700542} // namespace art