elf_writer_quick.cc revision bc90fd09e09a845ae6ea0d84ad67560575a94142
1/*
2 * Copyright (C) 2012 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 "elf_writer_quick.h"
18
19#include <unordered_map>
20#include <unordered_set>
21
22#include "base/logging.h"
23#include "base/unix_file/fd_file.h"
24#include "compiled_method.h"
25#include "dex_file-inl.h"
26#include "driver/compiler_driver.h"
27#include "driver/compiler_options.h"
28#include "elf_builder.h"
29#include "elf_file.h"
30#include "elf_utils.h"
31#include "elf_writer_debug.h"
32#include "globals.h"
33#include "leb128.h"
34#include "oat.h"
35#include "oat_writer.h"
36#include "utils.h"
37
38namespace art {
39
40template <typename ElfTypes>
41bool ElfWriterQuick<ElfTypes>::Create(File* elf_file,
42                                      OatWriter* oat_writer,
43                                      const std::vector<const DexFile*>& dex_files,
44                                      const std::string& android_root,
45                                      bool is_host,
46                                      const CompilerDriver& driver) {
47  ElfWriterQuick elf_writer(driver, elf_file);
48  return elf_writer.Write(oat_writer, dex_files, android_root, is_host);
49}
50
51template <typename ElfTypes>
52static void WriteDebugSymbols(ElfBuilder<ElfTypes>* builder, OatWriter* oat_writer);
53
54// Encode patch locations in .oat_patches format.
55template <typename ElfTypes>
56void ElfWriterQuick<ElfTypes>::EncodeOatPatches(
57    const OatWriter::PatchLocationsMap& sections,
58    std::vector<uint8_t>* buffer) {
59  for (const auto& section : sections) {
60    const std::string& name = section.first;
61    std::vector<uintptr_t>* locations = section.second.get();
62    DCHECK(!name.empty());
63    std::sort(locations->begin(), locations->end());
64    // Reserve buffer space - guess 2 bytes per ULEB128.
65    buffer->reserve(buffer->size() + name.size() + locations->size() * 2);
66    // Write null-terminated section name.
67    const uint8_t* name_data = reinterpret_cast<const uint8_t*>(name.c_str());
68    buffer->insert(buffer->end(), name_data, name_data + name.size() + 1);
69    // Write placeholder for data length.
70    size_t length_pos = buffer->size();
71    EncodeUnsignedLeb128(buffer, UINT32_MAX);
72    // Write LEB128 encoded list of advances (deltas between consequtive addresses).
73    size_t data_pos = buffer->size();
74    uintptr_t address = 0;  // relative to start of section.
75    for (uintptr_t location : *locations) {
76      DCHECK_LT(location - address, UINT32_MAX) << "Large gap between patch locations";
77      EncodeUnsignedLeb128(buffer, location - address);
78      address = location;
79    }
80    // Update length.
81    UpdateUnsignedLeb128(buffer->data() + length_pos, buffer->size() - data_pos);
82  }
83  buffer->push_back(0);  // End of sections.
84}
85
86class RodataWriter FINAL : public CodeOutput {
87 public:
88  explicit RodataWriter(OatWriter* oat_writer) : oat_writer_(oat_writer) {}
89
90  bool Write(OutputStream* out) OVERRIDE {
91    return oat_writer_->WriteRodata(out);
92  }
93
94 private:
95  OatWriter* oat_writer_;
96};
97
98class TextWriter FINAL : public CodeOutput {
99 public:
100  explicit TextWriter(OatWriter* oat_writer) : oat_writer_(oat_writer) {}
101
102  bool Write(OutputStream* out) OVERRIDE {
103    return oat_writer_->WriteCode(out);
104  }
105
106 private:
107  OatWriter* oat_writer_;
108};
109
110template <typename ElfTypes>
111bool ElfWriterQuick<ElfTypes>::Write(
112    OatWriter* oat_writer,
113    const std::vector<const DexFile*>& dex_files_unused ATTRIBUTE_UNUSED,
114    const std::string& android_root_unused ATTRIBUTE_UNUSED,
115    bool is_host_unused ATTRIBUTE_UNUSED) {
116  const InstructionSet isa = compiler_driver_->GetInstructionSet();
117
118  // Setup the builder with the main OAT sections (.rodata .text .bss).
119  const size_t rodata_size = oat_writer->GetOatHeader().GetExecutableOffset();
120  const size_t text_size = oat_writer->GetSize() - rodata_size;
121  const size_t bss_size = oat_writer->GetBssSize();
122  RodataWriter rodata_writer(oat_writer);
123  TextWriter text_writer(oat_writer);
124  std::unique_ptr<ElfBuilder<ElfTypes>> builder(new ElfBuilder<ElfTypes>(
125      isa, rodata_size, &rodata_writer, text_size, &text_writer, bss_size));
126
127  // Add debug sections.
128  // They are stack allocated here (in the same scope as the builder),
129  // but they are registred with the builder only if they are used.
130  using RawSection = typename ElfBuilder<ElfTypes>::RawSection;
131  const int pointer_size = GetInstructionSetPointerSize(isa);
132  const auto* text = builder->GetText();
133  constexpr bool absolute = false;  // patch to make absolute addresses.
134  constexpr bool relative = true;  // patch to make relative addresses.
135  const bool is64bit = Is64BitInstructionSet(isa);
136  RawSection eh_frame(".eh_frame", SHT_PROGBITS, SHF_ALLOC,
137                      nullptr, 0, pointer_size, 0, text, relative, is64bit);
138  RawSection eh_frame_hdr(".eh_frame_hdr", SHT_PROGBITS, SHF_ALLOC,
139                          nullptr, 0, 4, 0);
140  RawSection debug_info(".debug_info", SHT_PROGBITS, 0,
141                        nullptr, 0, 1, 0, text, absolute, false /* 32bit */);
142  RawSection debug_abbrev(".debug_abbrev", SHT_PROGBITS, 0,
143                          nullptr, 0, 1, 0);
144  RawSection debug_str(".debug_str", SHT_PROGBITS, 0,
145                       nullptr, 0, 1, 0);
146  RawSection debug_line(".debug_line", SHT_PROGBITS, 0,
147                        nullptr, 0, 1, 0, text, absolute, false /* 32bit */);
148  if (!oat_writer->GetMethodDebugInfo().empty()) {
149    if (compiler_driver_->GetCompilerOptions().GetIncludeCFI()) {
150      dwarf::WriteEhFrame(
151          compiler_driver_, oat_writer, dwarf::DW_EH_PE_pcrel,
152          eh_frame.GetBuffer(), eh_frame.GetPatchLocations(),
153          eh_frame_hdr.GetBuffer());
154      builder->RegisterSection(&eh_frame);
155      builder->RegisterSection(&eh_frame_hdr);
156    }
157    if (compiler_driver_->GetCompilerOptions().GetIncludeDebugSymbols()) {
158      // Add methods to .symtab.
159      WriteDebugSymbols(builder.get(), oat_writer);
160      // Generate DWARF .debug_* sections.
161      dwarf::WriteDebugSections(
162          compiler_driver_, oat_writer,
163          debug_info.GetBuffer(), debug_info.GetPatchLocations(),
164          debug_abbrev.GetBuffer(),
165          debug_str.GetBuffer(),
166          debug_line.GetBuffer(), debug_line.GetPatchLocations());
167      builder->RegisterSection(&debug_info);
168      builder->RegisterSection(&debug_abbrev);
169      builder->RegisterSection(&debug_str);
170      builder->RegisterSection(&debug_line);
171      *oat_writer->GetAbsolutePatchLocationsFor(".debug_info") =
172          *debug_info.GetPatchLocations();
173      *oat_writer->GetAbsolutePatchLocationsFor(".debug_line") =
174          *debug_line.GetPatchLocations();
175    }
176  }
177
178  // Add relocation section.
179  RawSection oat_patches(".oat_patches", SHT_OAT_PATCH, 0, nullptr, 0, 1, 0);
180  if (compiler_driver_->GetCompilerOptions().GetIncludePatchInformation() ||
181      // ElfWriter::Fixup will be called regardless and it needs to be able
182      // to patch debug sections so we have to include patches for them.
183      compiler_driver_->GetCompilerOptions().GetIncludeDebugSymbols()) {
184    EncodeOatPatches(oat_writer->GetAbsolutePatchLocations(), oat_patches.GetBuffer());
185    builder->RegisterSection(&oat_patches);
186  }
187
188  return builder->Write(elf_file_);
189}
190
191template <typename ElfTypes>
192static void WriteDebugSymbols(ElfBuilder<ElfTypes>* builder, OatWriter* oat_writer) {
193  const std::vector<OatWriter::DebugInfo>& method_info = oat_writer->GetMethodDebugInfo();
194
195  // Find all addresses (low_pc) which contain deduped methods.
196  // The first instance of method is not marked deduped_, but the rest is.
197  std::unordered_set<uint32_t> deduped_addresses;
198  for (auto it = method_info.begin(); it != method_info.end(); ++it) {
199    if (it->deduped_) {
200      deduped_addresses.insert(it->low_pc_);
201    }
202  }
203
204  auto* symtab = builder->GetSymtab();
205  for (auto it = method_info.begin(); it != method_info.end(); ++it) {
206    std::string name = PrettyMethod(it->dex_method_index_, *it->dex_file_, true);
207    if (deduped_addresses.find(it->low_pc_) != deduped_addresses.end()) {
208      name += " [DEDUPED]";
209    }
210
211    uint32_t low_pc = it->low_pc_;
212    // Add in code delta, e.g., thumb bit 0 for Thumb2 code.
213    low_pc += it->compiled_method_->CodeDelta();
214    symtab->AddSymbol(name, builder->GetText(), low_pc,
215                      true, it->high_pc_ - it->low_pc_, STB_GLOBAL, STT_FUNC);
216
217    // Conforming to aaelf, add $t mapping symbol to indicate start of a sequence of thumb2
218    // instructions, so that disassembler tools can correctly disassemble.
219    if (it->compiled_method_->GetInstructionSet() == kThumb2) {
220      symtab->AddSymbol("$t", builder->GetText(), it->low_pc_ & ~1, true,
221                        0, STB_LOCAL, STT_NOTYPE);
222    }
223  }
224}
225
226// Explicit instantiations
227template class ElfWriterQuick<ElfTypes32>;
228template class ElfWriterQuick<ElfTypes64>;
229
230}  // namespace art
231