blob: 3fdb8e44bac3bbf947e2fd23dbcc0c9e15186f6a [file] [log] [blame]
Brian Carlstrom700c8d32012-11-05 10:42:02 -08001/*
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.h"
18
19#include "base/unix_file/fd_file.h"
Ian Rogers1212a022013-03-04 10:48:41 -080020#include "compiler/driver/compiler_driver.h"
Brian Carlstrom700c8d32012-11-05 10:42:02 -080021#include "elf_file.h"
22#include "oat.h"
23#include "oat_file.h"
24
25#include <llvm/Support/TargetSelect.h>
26
27#include <mcld/Environment.h>
28#include <mcld/IRBuilder.h>
29#include <mcld/Linker.h>
30#include <mcld/LinkerConfig.h>
Brian Carlstrom818d98e2013-02-10 21:38:12 -080031#include <mcld/MC/ZOption.h>
Brian Carlstrom700c8d32012-11-05 10:42:02 -080032#include <mcld/Module.h>
33#include <mcld/Support/Path.h>
34#include <mcld/Support/TargetSelect.h>
35
36namespace art {
37
Ian Rogers1212a022013-03-04 10:48:41 -080038bool ElfWriter::Create(File* file, std::vector<uint8_t>& oat_contents, const CompilerDriver& compiler) {
39 ElfWriter elf_writer(&compiler);
Brian Carlstrom700c8d32012-11-05 10:42:02 -080040 return elf_writer.Write(oat_contents, file);
41}
42
Ian Rogers1212a022013-03-04 10:48:41 -080043ElfWriter::ElfWriter(const CompilerDriver* driver) : compiler_driver_(driver) {}
Brian Carlstrom700c8d32012-11-05 10:42:02 -080044
45ElfWriter::~ElfWriter() {}
46
47static void InitializeLLVM() {
48 // TODO: this is lifted from art's compiler_llvm.cc, should be factored out
49#if defined(ART_TARGET)
50 llvm::InitializeNativeTarget();
51 // TODO: odd that there is no InitializeNativeTargetMC?
52#else
53 llvm::InitializeAllTargets();
54 llvm::InitializeAllTargetMCs();
55#endif
56}
57
58bool ElfWriter::Write(std::vector<uint8_t>& oat_contents, File* elf_file) {
59
60 std::string target_triple;
61 std::string target_cpu;
62 std::string target_attr;
Ian Rogers1212a022013-03-04 10:48:41 -080063 CompilerDriver::InstructionSetToLLVMTarget(compiler_driver_->GetInstructionSet(),
Brian Carlstrom700c8d32012-11-05 10:42:02 -080064 target_triple,
65 target_cpu,
66 target_attr);
67
68 {
69 // Based on mclinker's llvm-mcld.cpp main() and LinkerTest
70 //
71 // TODO: LinkerTest uses mcld::Initialize(), but it does an
72 // llvm::InitializeAllTargets, which we don't want. Basically we
73 // want mcld::InitializeNative, but it doesn't exist yet, so we
74 // inline the minimal we need here.
75 InitializeLLVM();
76 mcld::InitializeAllTargets();
77 mcld::InitializeAllLinkers();
78 mcld::InitializeAllEmulations();
79 mcld::InitializeAllDiagnostics();
80
81 UniquePtr<mcld::LinkerConfig> linker_config(new mcld::LinkerConfig(target_triple));
82 CHECK(linker_config.get() != NULL);
83 linker_config->setCodeGenType(mcld::LinkerConfig::DynObj);
Ian Rogers1212a022013-03-04 10:48:41 -080084 if (compiler_driver_->GetInstructionSet() == kMips) {
Brian Carlstrom818d98e2013-02-10 21:38:12 -080085 // MCLinker defaults MIPS section alignment to 0x10000, not 0x1000
86 mcld::ZOption z_option;
87 z_option.setKind(mcld::ZOption::MaxPageSize);
88 z_option.setPageSize(kPageSize);
89 linker_config->options().addZOption(z_option);
90 }
Brian Carlstrom700c8d32012-11-05 10:42:02 -080091 linker_config->options().setSOName(elf_file->GetPath());
92 // TODO: Wire up mcld DiagnosticEngine to LOG?
93 if (false) {
94 // enables some tracing of input file processing
95 linker_config->options().setTrace(true);
96 }
97
98 // Based on alone::Linker::config
99 UniquePtr<mcld::Module> module(new mcld::Module(linker_config->options().soname()));
100 CHECK(module.get() != NULL);
101 UniquePtr<mcld::IRBuilder> ir_builder(new mcld::IRBuilder(*module.get(), *linker_config.get()));
102 CHECK(ir_builder.get() != NULL);
103 UniquePtr<mcld::Linker> linker(new mcld::Linker());
104 CHECK(linker.get() != NULL);
105 linker->config(*linker_config.get());
106
107
108 // Add an artificial memory input. Based on LinkerTest.
109 UniquePtr<OatFile> oat_file(OatFile::Open(oat_contents, elf_file->GetPath()));
110 CHECK(oat_file.get() != NULL) << elf_file->GetPath();
111
112 const char* oat_data_start = reinterpret_cast<const char*>(&oat_file->GetOatHeader());
113 const size_t oat_data_length = oat_file->GetOatHeader().GetExecutableOffset();
114 const char* oat_code_start = oat_data_start + oat_data_length;
115 const size_t oat_code_length = oat_file->Size() - oat_data_length;
116
117 // TODO: ownership of input?
118 mcld::Input* input = ir_builder->CreateInput("oat contents",
119 mcld::sys::fs::Path("oat contents path"),
120 mcld::Input::Object);
121 CHECK(input != NULL);
122
123 // TODO: ownership of null_section?
124 mcld::LDSection* null_section = ir_builder->CreateELFHeader(*input,
125 "",
126 mcld::LDFileFormat::Null,
127 llvm::ELF::SHT_NULL,
128 0);
129 CHECK(null_section != NULL);
130
131 // TODO: we should split readonly data from readonly executable
132 // code like .oat does. We need to control section layout with
133 // linker script like functionality to guarantee references
134 // between sections maintain relative position which isn't
135 // possible right now with the mclinker APIs.
136 CHECK(oat_code_start);
137
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800138 // we need to ensure that oatdata is page aligned so when we
139 // fixup the segment load addresses, they remain page aligned.
Brian Carlstrom818d98e2013-02-10 21:38:12 -0800140 uint32_t alignment = kPageSize;
141
142 // TODO: ownership of text_section?
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800143 mcld::LDSection* text_section = ir_builder->CreateELFHeader(*input,
144 ".text",
145 llvm::ELF::SHT_PROGBITS,
146 llvm::ELF::SHF_EXECINSTR
147 | llvm::ELF::SHF_ALLOC,
Brian Carlstrom818d98e2013-02-10 21:38:12 -0800148 alignment);
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800149 CHECK(text_section != NULL);
150
151 mcld::SectionData* text_section_data = ir_builder->CreateSectionData(*text_section);
152 CHECK(text_section_data != NULL);
153
154 // TODO: why does IRBuilder::CreateRegion take a non-const pointer?
155 mcld::Fragment* text_fragment = ir_builder->CreateRegion(const_cast<char*>(oat_data_start),
156 oat_file->Size());
157 CHECK(text_fragment != NULL);
158 ir_builder->AppendFragment(*text_fragment, *text_section_data);
159
160 ir_builder->AddSymbol(*input,
161 "oatdata",
162 mcld::ResolveInfo::Object,
163 mcld::ResolveInfo::Define,
164 mcld::ResolveInfo::Global,
165 oat_data_length, // size
166 0, // offset
167 text_section);
168
169 ir_builder->AddSymbol(*input,
170 "oatexec",
Ian Rogerse9de2dd2013-01-31 11:11:16 -0800171 mcld::ResolveInfo::Function,
Brian Carlstrom700c8d32012-11-05 10:42:02 -0800172 mcld::ResolveInfo::Define,
173 mcld::ResolveInfo::Global,
174 oat_code_length, // size
175 oat_data_length, // offset
176 text_section);
177
178 ir_builder->AddSymbol(*input,
179 "oatlastword",
180 mcld::ResolveInfo::Object,
181 mcld::ResolveInfo::Define,
182 mcld::ResolveInfo::Global,
183 0, // size
184 // subtract a word so symbol is within section
185 (oat_data_length + oat_code_length) - sizeof(uint32_t), // offset
186 text_section);
187
188 // link inputs
189 if (!linker->link(*module.get(), *ir_builder.get())) {
190 LOG(ERROR) << "problem linking " << elf_file->GetPath();
191 return false;
192 }
193
194 // emited linked output
195 if (!linker->emit(elf_file->Fd())) {
196 LOG(ERROR) << "problem emitting " << elf_file->GetPath();
197 return false;
198 }
199 // TODO: mcld::Linker::emit closed the file descriptor. It probably shouldn't.
200 // For now, close our File to match.
201 elf_file->Close();
202 mcld::Finalize();
203 }
204 LOG(INFO) << "ELF file written successfully: " << elf_file->GetPath();
205 return true;
206}
207
208bool ElfWriter::Fixup(File* file, uintptr_t oat_data_begin) {
209 UniquePtr<ElfFile> elf_file(ElfFile::Open(file, true, false));
210 CHECK(elf_file.get() != NULL);
211
212 // Lookup "oatdata" symbol address.
213 llvm::ELF::Elf32_Addr oatdata_address = elf_file->FindSymbolAddress(llvm::ELF::SHT_DYNSYM,
214 "oatdata");
215 CHECK_NE(0U, oatdata_address);
216 llvm::ELF::Elf32_Off base_address = oat_data_begin - oatdata_address;
217
218 if (!FixupDynamic(*elf_file.get(), base_address)) {
219 LOG(WARNING) << "Failed fo fixup .dynamic in " << file->GetPath();
220 return false;
221 }
222 if (!FixupSectionHeaders(*elf_file.get(), base_address)) {
223 LOG(WARNING) << "Failed fo fixup section headers in " << file->GetPath();
224 return false;
225 }
226 if (!FixupProgramHeaders(*elf_file.get(), base_address)) {
227 LOG(WARNING) << "Failed fo fixup program headers in " << file->GetPath();
228 return false;
229 }
230 if (!FixupSymbols(*elf_file.get(), base_address, true)) {
231 LOG(WARNING) << "Failed fo fixup .dynsym in " << file->GetPath();
232 return false;
233 }
234 if (!FixupSymbols(*elf_file.get(), base_address, false)) {
235 LOG(WARNING) << "Failed fo fixup .symtab in " << file->GetPath();
236 return false;
237 }
238 return true;
239}
240
241bool ElfWriter::FixupDynamic(ElfFile& elf_file, uintptr_t base_address) {
242 // TODO: C++0x auto.
243 for (llvm::ELF::Elf32_Word i = 0; i < elf_file.GetDynamicNum(); i++) {
244 llvm::ELF::Elf32_Dyn& elf_dyn = elf_file.GetDynamic(i);
245 bool elf_dyn_needs_fixup = false;
246 // case 1: if Elf32_Dyn.d_tag implies Elf32_Dyn.d_un contains an address in d_ptr
247 switch (elf_dyn.d_tag) {
248 case llvm::ELF::DT_PLTGOT:
249 case llvm::ELF::DT_HASH:
250 case llvm::ELF::DT_STRTAB:
251 case llvm::ELF::DT_SYMTAB:
252 case llvm::ELF::DT_RELA:
253 case llvm::ELF::DT_INIT:
254 case llvm::ELF::DT_FINI:
255 case llvm::ELF::DT_REL:
256 case llvm::ELF::DT_DEBUG:
257 case llvm::ELF::DT_JMPREL: {
258 elf_dyn_needs_fixup = true;
259 break;
260 }
261 default: {
262 // case 2: if d_tag is even and greater than > DT_ENCODING
263 if ((elf_dyn.d_tag > llvm::ELF::DT_ENCODING) && ((elf_dyn.d_tag % 2) == 0)) {
264 elf_dyn_needs_fixup = true;
265 }
266 break;
267 }
268 }
269 if (elf_dyn_needs_fixup) {
270 uint32_t d_ptr = elf_dyn.d_un.d_ptr;
271 d_ptr += base_address;
272 elf_dyn.d_un.d_ptr = d_ptr;
273 }
274 }
275 return true;
276}
277
278bool ElfWriter::FixupSectionHeaders(ElfFile& elf_file, uintptr_t base_address) {
279 for (llvm::ELF::Elf32_Word i = 0; i < elf_file.GetSectionHeaderNum(); i++) {
280 llvm::ELF::Elf32_Shdr& sh = elf_file.GetSectionHeader(i);
281 // 0 implies that the section will not exist in the memory of the process
282 if (sh.sh_addr == 0) {
283 continue;
284 }
285 sh.sh_addr += base_address;
286 }
287 return true;
288}
289
290bool ElfWriter::FixupProgramHeaders(ElfFile& elf_file, uintptr_t base_address) {
291 // TODO: ELFObjectFile doesn't have give to Elf32_Phdr, so we do that ourselves for now.
292 for (llvm::ELF::Elf32_Word i = 0; i < elf_file.GetProgramHeaderNum(); i++) {
293 llvm::ELF::Elf32_Phdr& ph = elf_file.GetProgramHeader(i);
294 CHECK_EQ(ph.p_vaddr, ph.p_paddr) << elf_file.GetFile().GetPath() << " i=" << i;
295 CHECK((ph.p_align == 0) || (0 == ((ph.p_vaddr - ph.p_offset) & (ph.p_align - 1))));
296 ph.p_vaddr += base_address;
297 ph.p_paddr += base_address;
298 CHECK((ph.p_align == 0) || (0 == ((ph.p_vaddr - ph.p_offset) & (ph.p_align - 1))));
299 }
300 return true;
301}
302
303bool ElfWriter::FixupSymbols(ElfFile& elf_file, uintptr_t base_address, bool dynamic) {
304 llvm::ELF::Elf32_Word section_type = dynamic ? llvm::ELF::SHT_DYNSYM : llvm::ELF::SHT_SYMTAB;
305 // TODO: Unfortunate ELFObjectFile has protected symbol access, so use ElfFile
306 llvm::ELF::Elf32_Shdr* symbol_section = elf_file.FindSectionByType(section_type);
307 CHECK(symbol_section != NULL) << elf_file.GetFile().GetPath();
308 for (uint32_t i = 0; i < elf_file.GetSymbolNum(*symbol_section); i++) {
309 llvm::ELF::Elf32_Sym& symbol = elf_file.GetSymbol(section_type, i);
310 if (symbol.st_value != 0) {
311 symbol.st_value += base_address;
312 }
313 }
314 return true;
315}
316
317void ElfWriter::GetOatElfInformation(File* file,
318 size_t& oat_loaded_size,
319 size_t& oat_data_offset) {
320 UniquePtr<ElfFile> elf_file(ElfFile::Open(file, false, false));
321 CHECK(elf_file.get() != NULL);
322
323 oat_loaded_size = elf_file->GetLoadedSize();
324 CHECK_NE(0U, oat_loaded_size);
325 oat_data_offset = elf_file->FindSymbolAddress(llvm::ELF::SHT_DYNSYM, "oatdata");
326 CHECK_NE(0U, oat_data_offset);
327}
328
329} // namespace art