blob: 71f02d3b5d4fb486c85db6f63ea15300e2964a86 [file] [log] [blame]
Brian Carlstrom7940e442013-07-12 13:46:57 -07001/*
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 "base/logging.h"
20#include "base/unix_file/fd_file.h"
Brian Carlstromc6dfdac2013-08-26 18:57:31 -070021#include "buffered_output_stream.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070022#include "driver/compiler_driver.h"
Alex Light3470ab42014-06-18 10:35:45 -070023#include "dwarf.h"
Nicolas Geoffray50cfe742014-02-19 13:27:42 +000024#include "elf_utils.h"
Brian Carlstromc50d8e12013-07-23 22:35:16 -070025#include "file_output_stream.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070026#include "globals.h"
Andreas Gampe79273802014-08-05 20:21:05 -070027#include "leb128.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070028#include "oat.h"
Brian Carlstromc50d8e12013-07-23 22:35:16 -070029#include "oat_writer.h"
Brian Carlstrom7940e442013-07-12 13:46:57 -070030#include "utils.h"
31
32namespace art {
33
Brian Carlstromb12f3472014-06-11 14:54:46 -070034static constexpr Elf32_Word NextOffset(const Elf32_Shdr& cur, const Elf32_Shdr& prev) {
35 return RoundUp(prev.sh_size + prev.sh_offset, cur.sh_addralign);
Brian Carlstrom7940e442013-07-12 13:46:57 -070036}
37
Brian Carlstromb12f3472014-06-11 14:54:46 -070038static uint8_t MakeStInfo(uint8_t binding, uint8_t type) {
39 return ((binding) << 4) + ((type) & 0xf);
40}
41
Andreas Gampe79273802014-08-05 20:21:05 -070042static void UpdateWord(std::vector<uint8_t>* buf, int offset, int data) {
43 (*buf)[offset+0] = data;
44 (*buf)[offset+1] = data >> 8;
45 (*buf)[offset+2] = data >> 16;
46 (*buf)[offset+3] = data >> 24;
47}
48
49static void PushWord(std::vector<uint8_t>* buf, int data) {
50 buf->push_back(data & 0xff);
51 buf->push_back((data >> 8) & 0xff);
52 buf->push_back((data >> 16) & 0xff);
53 buf->push_back((data >> 24) & 0xff);
54}
55
56static void PushHalf(std::vector<uint8_t>* buf, int data) {
57 buf->push_back(data & 0xff);
58 buf->push_back((data >> 8) & 0xff);
59}
60
Brian Carlstromb12f3472014-06-11 14:54:46 -070061bool ElfWriterQuick::ElfBuilder::Write() {
62 // The basic layout of the elf file. Order may be different in final output.
Brian Carlstrom7940e442013-07-12 13:46:57 -070063 // +-------------------------+
64 // | Elf32_Ehdr |
65 // +-------------------------+
66 // | Elf32_Phdr PHDR |
67 // | Elf32_Phdr LOAD R | .dynsym .dynstr .hash .rodata
68 // | Elf32_Phdr LOAD R X | .text
69 // | Elf32_Phdr LOAD RW | .dynamic
70 // | Elf32_Phdr DYNAMIC | .dynamic
71 // +-------------------------+
72 // | .dynsym |
73 // | Elf32_Sym STN_UNDEF |
74 // | Elf32_Sym oatdata |
75 // | Elf32_Sym oatexec |
76 // | Elf32_Sym oatlastword |
77 // +-------------------------+
78 // | .dynstr |
79 // | \0 |
80 // | oatdata\0 |
81 // | oatexec\0 |
82 // | oatlastword\0 |
83 // | boot.oat\0 |
84 // +-------------------------+
85 // | .hash |
Brian Carlstromb12f3472014-06-11 14:54:46 -070086 // | Elf32_Word nbucket = b |
87 // | Elf32_Word nchain = c |
88 // | Elf32_Word bucket[0] |
89 // | ... |
90 // | Elf32_Word bucket[b - 1]|
91 // | Elf32_Word chain[0] |
92 // | ... |
93 // | Elf32_Word chain[c - 1] |
Brian Carlstrom7940e442013-07-12 13:46:57 -070094 // +-------------------------+
95 // | .rodata |
96 // | oatdata..oatexec-4 |
97 // +-------------------------+
98 // | .text |
99 // | oatexec..oatlastword |
100 // +-------------------------+
101 // | .dynamic |
102 // | Elf32_Dyn DT_SONAME |
103 // | Elf32_Dyn DT_HASH |
104 // | Elf32_Dyn DT_SYMTAB |
105 // | Elf32_Dyn DT_SYMENT |
106 // | Elf32_Dyn DT_STRTAB |
107 // | Elf32_Dyn DT_STRSZ |
108 // | Elf32_Dyn DT_NULL |
Brian Carlstromb12f3472014-06-11 14:54:46 -0700109 // +-------------------------+ (Optional)
110 // | .strtab | (Optional)
111 // | program symbol names | (Optional)
112 // +-------------------------+ (Optional)
113 // | .symtab | (Optional)
114 // | program symbols | (Optional)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700115 // +-------------------------+
116 // | .shstrtab |
117 // | \0 |
118 // | .dynamic\0 |
119 // | .dynsym\0 |
120 // | .dynstr\0 |
121 // | .hash\0 |
122 // | .rodata\0 |
123 // | .text\0 |
124 // | .shstrtab\0 |
Brian Carlstromb12f3472014-06-11 14:54:46 -0700125 // | .symtab\0 | (Optional)
126 // | .strtab\0 | (Optional)
127 // | .debug_str\0 | (Optional)
128 // | .debug_info\0 | (Optional)
Tong Shen35e1e6a2014-07-30 09:31:22 -0700129 // | .eh_frame\0 | (Optional)
Brian Carlstromb12f3472014-06-11 14:54:46 -0700130 // | .debug_abbrev\0 | (Optional)
131 // +-------------------------+ (Optional)
132 // | .debug_str | (Optional)
133 // +-------------------------+ (Optional)
134 // | .debug_info | (Optional)
135 // +-------------------------+ (Optional)
Tong Shen35e1e6a2014-07-30 09:31:22 -0700136 // | .eh_frame | (Optional)
Brian Carlstromb12f3472014-06-11 14:54:46 -0700137 // +-------------------------+ (Optional)
138 // | .debug_abbrev | (Optional)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700139 // +-------------------------+
140 // | Elf32_Shdr NULL |
141 // | Elf32_Shdr .dynsym |
142 // | Elf32_Shdr .dynstr |
143 // | Elf32_Shdr .hash |
144 // | Elf32_Shdr .text |
145 // | Elf32_Shdr .rodata |
146 // | Elf32_Shdr .dynamic |
147 // | Elf32_Shdr .shstrtab |
Brian Carlstromb12f3472014-06-11 14:54:46 -0700148 // | Elf32_Shdr .debug_str | (Optional)
Mark Mendellae9fd932014-02-10 16:14:35 -0800149 // | Elf32_Shdr .debug_info | (Optional)
Tong Shen35e1e6a2014-07-30 09:31:22 -0700150 // | Elf32_Shdr .eh_frame | (Optional)
Brian Carlstromb12f3472014-06-11 14:54:46 -0700151 // | Elf32_Shdr .debug_abbrev| (Optional)
Brian Carlstrom7940e442013-07-12 13:46:57 -0700152 // +-------------------------+
153
Brian Carlstrom7940e442013-07-12 13:46:57 -0700154
Brian Carlstromb12f3472014-06-11 14:54:46 -0700155 if (fatal_error_) {
156 return false;
157 }
158 // Step 1. Figure out all the offsets.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700159
Brian Carlstromb12f3472014-06-11 14:54:46 -0700160 // What phdr is.
161 uint32_t phdr_offset = sizeof(Elf32_Ehdr);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700162 const uint8_t PH_PHDR = 0;
163 const uint8_t PH_LOAD_R__ = 1;
164 const uint8_t PH_LOAD_R_X = 2;
165 const uint8_t PH_LOAD_RW_ = 3;
166 const uint8_t PH_DYNAMIC = 4;
167 const uint8_t PH_NUM = 5;
Nicolas Geoffray50cfe742014-02-19 13:27:42 +0000168 uint32_t phdr_size = sizeof(Elf32_Phdr) * PH_NUM;
Brian Carlstromb12f3472014-06-11 14:54:46 -0700169 if (debug_logging_) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700170 LOG(INFO) << "phdr_offset=" << phdr_offset << std::hex << " " << phdr_offset;
171 LOG(INFO) << "phdr_size=" << phdr_size << std::hex << " " << phdr_size;
172 }
Brian Carlstromb12f3472014-06-11 14:54:46 -0700173 Elf32_Phdr program_headers[PH_NUM];
174 memset(&program_headers, 0, sizeof(program_headers));
175 program_headers[PH_PHDR].p_type = PT_PHDR;
176 program_headers[PH_PHDR].p_offset = phdr_offset;
177 program_headers[PH_PHDR].p_vaddr = phdr_offset;
178 program_headers[PH_PHDR].p_paddr = phdr_offset;
179 program_headers[PH_PHDR].p_filesz = sizeof(program_headers);
180 program_headers[PH_PHDR].p_memsz = sizeof(program_headers);
181 program_headers[PH_PHDR].p_flags = PF_R;
182 program_headers[PH_PHDR].p_align = sizeof(Elf32_Word);
Brian Carlstrom7940e442013-07-12 13:46:57 -0700183
Brian Carlstromb12f3472014-06-11 14:54:46 -0700184 program_headers[PH_LOAD_R__].p_type = PT_LOAD;
185 program_headers[PH_LOAD_R__].p_offset = 0;
186 program_headers[PH_LOAD_R__].p_vaddr = 0;
187 program_headers[PH_LOAD_R__].p_paddr = 0;
188 program_headers[PH_LOAD_R__].p_flags = PF_R;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700189
Brian Carlstromb12f3472014-06-11 14:54:46 -0700190 program_headers[PH_LOAD_R_X].p_type = PT_LOAD;
191 program_headers[PH_LOAD_R_X].p_flags = PF_R | PF_X;
192
193 program_headers[PH_LOAD_RW_].p_type = PT_LOAD;
194 program_headers[PH_LOAD_RW_].p_flags = PF_R | PF_W;
195
196 program_headers[PH_DYNAMIC].p_type = PT_DYNAMIC;
197 program_headers[PH_DYNAMIC].p_flags = PF_R | PF_W;
198
199 // Get the dynstr string.
200 std::string dynstr(dynsym_builder_.GenerateStrtab());
201
202 // Add the SONAME to the dynstr.
Brian Carlstrom7940e442013-07-12 13:46:57 -0700203 uint32_t dynstr_soname_offset = dynstr.size();
204 std::string file_name(elf_file_->GetPath());
205 size_t directory_separator_pos = file_name.rfind('/');
206 if (directory_separator_pos != std::string::npos) {
207 file_name = file_name.substr(directory_separator_pos + 1);
208 }
209 dynstr += file_name;
210 dynstr += '\0';
Brian Carlstromb12f3472014-06-11 14:54:46 -0700211 if (debug_logging_) {
212 LOG(INFO) << "dynstr size (bytes) =" << dynstr.size()
213 << std::hex << " " << dynstr.size();
Brian Carlstrom8758c642014-06-11 14:22:02 -0700214 LOG(INFO) << "dynsym size (elements)=" << dynsym_builder_.GetSize()
215 << std::hex << " " << dynsym_builder_.GetSize();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700216 }
217
Brian Carlstromb12f3472014-06-11 14:54:46 -0700218 // get the strtab
219 std::string strtab;
220 if (IncludingDebugSymbols()) {
221 strtab = symtab_builder_.GenerateStrtab();
222 if (debug_logging_) {
223 LOG(INFO) << "strtab size (bytes) =" << strtab.size()
224 << std::hex << " " << strtab.size();
Brian Carlstrom8758c642014-06-11 14:22:02 -0700225 LOG(INFO) << "symtab size (elements) =" << symtab_builder_.GetSize()
226 << std::hex << " " << symtab_builder_.GetSize();
Brian Carlstromb12f3472014-06-11 14:54:46 -0700227 }
Brian Carlstrom7940e442013-07-12 13:46:57 -0700228 }
229
Brian Carlstromb12f3472014-06-11 14:54:46 -0700230 // Get the section header string table.
231 std::vector<Elf32_Shdr*> section_ptrs;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700232 std::string shstrtab;
233 shstrtab += '\0';
Brian Carlstromb12f3472014-06-11 14:54:46 -0700234
235 // Setup sym_undef
236 Elf32_Shdr null_hdr;
237 memset(&null_hdr, 0, sizeof(null_hdr));
238 null_hdr.sh_type = SHT_NULL;
239 null_hdr.sh_link = SHN_UNDEF;
240 section_ptrs.push_back(&null_hdr);
241
242 uint32_t section_index = 1;
243
244 // setup .dynsym
245 section_ptrs.push_back(&dynsym_builder_.section_);
246 AssignSectionStr(&dynsym_builder_, &shstrtab);
247 dynsym_builder_.section_index_ = section_index++;
248
249 // Setup .dynstr
250 section_ptrs.push_back(&dynsym_builder_.strtab_.section_);
251 AssignSectionStr(&dynsym_builder_.strtab_, &shstrtab);
252 dynsym_builder_.strtab_.section_index_ = section_index++;
253
254 // Setup .hash
255 section_ptrs.push_back(&hash_builder_.section_);
256 AssignSectionStr(&hash_builder_, &shstrtab);
257 hash_builder_.section_index_ = section_index++;
258
259 // Setup .rodata
260 section_ptrs.push_back(&rodata_builder_.section_);
261 AssignSectionStr(&rodata_builder_, &shstrtab);
262 rodata_builder_.section_index_ = section_index++;
263
264 // Setup .text
265 section_ptrs.push_back(&text_builder_.section_);
266 AssignSectionStr(&text_builder_, &shstrtab);
267 text_builder_.section_index_ = section_index++;
268
269 // Setup .dynamic
270 section_ptrs.push_back(&dynamic_builder_.section_);
271 AssignSectionStr(&dynamic_builder_, &shstrtab);
272 dynamic_builder_.section_index_ = section_index++;
273
274 if (IncludingDebugSymbols()) {
275 // Setup .symtab
276 section_ptrs.push_back(&symtab_builder_.section_);
277 AssignSectionStr(&symtab_builder_, &shstrtab);
278 symtab_builder_.section_index_ = section_index++;
279
280 // Setup .strtab
281 section_ptrs.push_back(&symtab_builder_.strtab_.section_);
282 AssignSectionStr(&symtab_builder_.strtab_, &shstrtab);
283 symtab_builder_.strtab_.section_index_ = section_index++;
284 }
285 ElfRawSectionBuilder* it = other_builders_.data();
286 for (uint32_t cnt = 0; cnt < other_builders_.size(); ++it, ++cnt) {
287 // Setup all the other sections.
288 section_ptrs.push_back(&it->section_);
289 AssignSectionStr(it, &shstrtab);
290 it->section_index_ = section_index++;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700291 }
292
Brian Carlstromb12f3472014-06-11 14:54:46 -0700293 // Setup shstrtab
294 section_ptrs.push_back(&shstrtab_builder_.section_);
295 AssignSectionStr(&shstrtab_builder_, &shstrtab);
296 shstrtab_builder_.section_index_ = section_index++;
297
298 if (debug_logging_) {
299 LOG(INFO) << ".shstrtab size (bytes) =" << shstrtab.size()
300 << std::hex << " " << shstrtab.size();
301 LOG(INFO) << "section list size (elements)=" << section_ptrs.size()
302 << std::hex << " " << section_ptrs.size();
Mark Mendellae9fd932014-02-10 16:14:35 -0800303 }
304
Brian Carlstromb12f3472014-06-11 14:54:46 -0700305 // Fill in the hash section.
306 std::vector<Elf32_Word> hash = dynsym_builder_.GenerateHashContents();
307
308 if (debug_logging_) {
309 LOG(INFO) << ".hash size (bytes)=" << hash.size() * sizeof(Elf32_Word)
310 << std::hex << " " << hash.size() * sizeof(Elf32_Word);
Mark Mendellae9fd932014-02-10 16:14:35 -0800311 }
312
Brian Carlstromb12f3472014-06-11 14:54:46 -0700313 Elf32_Word base_offset = sizeof(Elf32_Ehdr) + sizeof(program_headers);
314 std::vector<ElfFilePiece> pieces;
315
316 // Get the layout in the sections.
317 //
318 // Get the layout of the dynsym section.
319 dynsym_builder_.section_.sh_offset = RoundUp(base_offset, dynsym_builder_.section_.sh_addralign);
320 dynsym_builder_.section_.sh_addr = dynsym_builder_.section_.sh_offset;
Brian Carlstrom8758c642014-06-11 14:22:02 -0700321 dynsym_builder_.section_.sh_size = dynsym_builder_.GetSize() * sizeof(Elf32_Sym);
Brian Carlstromb12f3472014-06-11 14:54:46 -0700322 dynsym_builder_.section_.sh_link = dynsym_builder_.GetLink();
323
324 // Get the layout of the dynstr section.
325 dynsym_builder_.strtab_.section_.sh_offset = NextOffset(dynsym_builder_.strtab_.section_,
326 dynsym_builder_.section_);
327 dynsym_builder_.strtab_.section_.sh_addr = dynsym_builder_.strtab_.section_.sh_offset;
328 dynsym_builder_.strtab_.section_.sh_size = dynstr.size();
329 dynsym_builder_.strtab_.section_.sh_link = dynsym_builder_.strtab_.GetLink();
330
331 // Get the layout of the hash section
332 hash_builder_.section_.sh_offset = NextOffset(hash_builder_.section_,
333 dynsym_builder_.strtab_.section_);
334 hash_builder_.section_.sh_addr = hash_builder_.section_.sh_offset;
335 hash_builder_.section_.sh_size = hash.size() * sizeof(Elf32_Word);
336 hash_builder_.section_.sh_link = hash_builder_.GetLink();
337
338 // Get the layout of the rodata section.
339 rodata_builder_.section_.sh_offset = NextOffset(rodata_builder_.section_,
340 hash_builder_.section_);
341 rodata_builder_.section_.sh_addr = rodata_builder_.section_.sh_offset;
342 rodata_builder_.section_.sh_size = rodata_builder_.size_;
343 rodata_builder_.section_.sh_link = rodata_builder_.GetLink();
344
345 // Get the layout of the text section.
346 text_builder_.section_.sh_offset = NextOffset(text_builder_.section_, rodata_builder_.section_);
347 text_builder_.section_.sh_addr = text_builder_.section_.sh_offset;
348 text_builder_.section_.sh_size = text_builder_.size_;
349 text_builder_.section_.sh_link = text_builder_.GetLink();
350 CHECK_ALIGNED(rodata_builder_.section_.sh_offset + rodata_builder_.section_.sh_size, kPageSize);
351
352 // Get the layout of the dynamic section.
353 dynamic_builder_.section_.sh_offset = NextOffset(dynamic_builder_.section_,
354 text_builder_.section_);
355 dynamic_builder_.section_.sh_addr = dynamic_builder_.section_.sh_offset;
Brian Carlstrom8758c642014-06-11 14:22:02 -0700356 dynamic_builder_.section_.sh_size = dynamic_builder_.GetSize() * sizeof(Elf32_Dyn);
Brian Carlstromb12f3472014-06-11 14:54:46 -0700357 dynamic_builder_.section_.sh_link = dynamic_builder_.GetLink();
358
359 Elf32_Shdr prev = dynamic_builder_.section_;
360 if (IncludingDebugSymbols()) {
361 // Get the layout of the symtab section.
362 symtab_builder_.section_.sh_offset = NextOffset(symtab_builder_.section_,
363 dynamic_builder_.section_);
364 symtab_builder_.section_.sh_addr = 0;
365 // Add to leave space for the null symbol.
Brian Carlstrom8758c642014-06-11 14:22:02 -0700366 symtab_builder_.section_.sh_size = symtab_builder_.GetSize() * sizeof(Elf32_Sym);
Brian Carlstromb12f3472014-06-11 14:54:46 -0700367 symtab_builder_.section_.sh_link = symtab_builder_.GetLink();
368
369 // Get the layout of the dynstr section.
370 symtab_builder_.strtab_.section_.sh_offset = NextOffset(symtab_builder_.strtab_.section_,
371 symtab_builder_.section_);
372 symtab_builder_.strtab_.section_.sh_addr = 0;
373 symtab_builder_.strtab_.section_.sh_size = strtab.size();
374 symtab_builder_.strtab_.section_.sh_link = symtab_builder_.strtab_.GetLink();
375
376 prev = symtab_builder_.strtab_.section_;
Mark Mendellae9fd932014-02-10 16:14:35 -0800377 }
Brian Carlstromb12f3472014-06-11 14:54:46 -0700378 if (debug_logging_) {
379 LOG(INFO) << "dynsym off=" << dynsym_builder_.section_.sh_offset
380 << " dynsym size=" << dynsym_builder_.section_.sh_size;
381 LOG(INFO) << "dynstr off=" << dynsym_builder_.strtab_.section_.sh_offset
382 << " dynstr size=" << dynsym_builder_.strtab_.section_.sh_size;
383 LOG(INFO) << "hash off=" << hash_builder_.section_.sh_offset
384 << " hash size=" << hash_builder_.section_.sh_size;
385 LOG(INFO) << "rodata off=" << rodata_builder_.section_.sh_offset
386 << " rodata size=" << rodata_builder_.section_.sh_size;
387 LOG(INFO) << "text off=" << text_builder_.section_.sh_offset
388 << " text size=" << text_builder_.section_.sh_size;
389 LOG(INFO) << "dynamic off=" << dynamic_builder_.section_.sh_offset
390 << " dynamic size=" << dynamic_builder_.section_.sh_size;
391 if (IncludingDebugSymbols()) {
392 LOG(INFO) << "symtab off=" << symtab_builder_.section_.sh_offset
393 << " symtab size=" << symtab_builder_.section_.sh_size;
394 LOG(INFO) << "strtab off=" << symtab_builder_.strtab_.section_.sh_offset
395 << " strtab size=" << symtab_builder_.strtab_.section_.sh_size;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700396 }
397 }
Brian Carlstromb12f3472014-06-11 14:54:46 -0700398 // Get the layout of the extra sections. (This will deal with the debug
399 // sections if they are there)
400 for (auto it = other_builders_.begin(); it != other_builders_.end(); ++it) {
401 it->section_.sh_offset = NextOffset(it->section_, prev);
402 it->section_.sh_addr = 0;
403 it->section_.sh_size = it->GetBuffer()->size();
404 it->section_.sh_link = it->GetLink();
405 pieces.push_back(ElfFilePiece(it->name_, it->section_.sh_offset,
406 it->GetBuffer()->data(), it->GetBuffer()->size()));
407 prev = it->section_;
408 if (debug_logging_) {
409 LOG(INFO) << it->name_ << " off=" << it->section_.sh_offset
410 << " " << it->name_ << " size=" << it->section_.sh_size;
411 }
412 }
413 // Get the layout of the shstrtab section
414 shstrtab_builder_.section_.sh_offset = NextOffset(shstrtab_builder_.section_, prev);
415 shstrtab_builder_.section_.sh_addr = 0;
416 shstrtab_builder_.section_.sh_size = shstrtab.size();
417 shstrtab_builder_.section_.sh_link = shstrtab_builder_.GetLink();
418 if (debug_logging_) {
419 LOG(INFO) << "shstrtab off=" << shstrtab_builder_.section_.sh_offset
420 << " shstrtab size=" << shstrtab_builder_.section_.sh_size;
Mark Mendellae9fd932014-02-10 16:14:35 -0800421 }
422
Brian Carlstromb12f3472014-06-11 14:54:46 -0700423 // The section list comes after come after.
424 Elf32_Word sections_offset = RoundUp(
425 shstrtab_builder_.section_.sh_offset + shstrtab_builder_.section_.sh_size,
426 sizeof(Elf32_Word));
Brian Carlstrom7940e442013-07-12 13:46:57 -0700427
Brian Carlstromb12f3472014-06-11 14:54:46 -0700428 // Setup the actual symbol arrays.
429 std::vector<Elf32_Sym> dynsym = dynsym_builder_.GenerateSymtab();
Brian Carlstrom8758c642014-06-11 14:22:02 -0700430 CHECK_EQ(dynsym.size() * sizeof(Elf32_Sym), dynsym_builder_.section_.sh_size);
Brian Carlstromb12f3472014-06-11 14:54:46 -0700431 std::vector<Elf32_Sym> symtab;
432 if (IncludingDebugSymbols()) {
433 symtab = symtab_builder_.GenerateSymtab();
Brian Carlstrom8758c642014-06-11 14:22:02 -0700434 CHECK_EQ(symtab.size() * sizeof(Elf32_Sym), symtab_builder_.section_.sh_size);
Brian Carlstromb12f3472014-06-11 14:54:46 -0700435 }
436
437 // Setup the dynamic section.
438 // This will add the 2 values we cannot know until now time, namely the size
439 // and the soname_offset.
440 std::vector<Elf32_Dyn> dynamic = dynamic_builder_.GetDynamics(dynstr.size(),
441 dynstr_soname_offset);
Brian Carlstrom8758c642014-06-11 14:22:02 -0700442 CHECK_EQ(dynamic.size() * sizeof(Elf32_Dyn), dynamic_builder_.section_.sh_size);
Brian Carlstromb12f3472014-06-11 14:54:46 -0700443
444 // Finish setup of the program headers now that we know the layout of the
445 // whole file.
446 Elf32_Word load_r_size = rodata_builder_.section_.sh_offset + rodata_builder_.section_.sh_size;
447 program_headers[PH_LOAD_R__].p_filesz = load_r_size;
448 program_headers[PH_LOAD_R__].p_memsz = load_r_size;
449 program_headers[PH_LOAD_R__].p_align = rodata_builder_.section_.sh_addralign;
450
451 Elf32_Word load_rx_size = text_builder_.section_.sh_size;
452 program_headers[PH_LOAD_R_X].p_offset = text_builder_.section_.sh_offset;
453 program_headers[PH_LOAD_R_X].p_vaddr = text_builder_.section_.sh_offset;
454 program_headers[PH_LOAD_R_X].p_paddr = text_builder_.section_.sh_offset;
455 program_headers[PH_LOAD_R_X].p_filesz = load_rx_size;
456 program_headers[PH_LOAD_R_X].p_memsz = load_rx_size;
457 program_headers[PH_LOAD_R_X].p_align = text_builder_.section_.sh_addralign;
458
459 program_headers[PH_LOAD_RW_].p_offset = dynamic_builder_.section_.sh_offset;
460 program_headers[PH_LOAD_RW_].p_vaddr = dynamic_builder_.section_.sh_offset;
461 program_headers[PH_LOAD_RW_].p_paddr = dynamic_builder_.section_.sh_offset;
462 program_headers[PH_LOAD_RW_].p_filesz = dynamic_builder_.section_.sh_size;
463 program_headers[PH_LOAD_RW_].p_memsz = dynamic_builder_.section_.sh_size;
464 program_headers[PH_LOAD_RW_].p_align = dynamic_builder_.section_.sh_addralign;
465
466 program_headers[PH_DYNAMIC].p_offset = dynamic_builder_.section_.sh_offset;
467 program_headers[PH_DYNAMIC].p_vaddr = dynamic_builder_.section_.sh_offset;
468 program_headers[PH_DYNAMIC].p_paddr = dynamic_builder_.section_.sh_offset;
469 program_headers[PH_DYNAMIC].p_filesz = dynamic_builder_.section_.sh_size;
470 program_headers[PH_DYNAMIC].p_memsz = dynamic_builder_.section_.sh_size;
471 program_headers[PH_DYNAMIC].p_align = dynamic_builder_.section_.sh_addralign;
472
473 // Finish setup of the Ehdr values.
474 elf_header_.e_phoff = phdr_offset;
475 elf_header_.e_shoff = sections_offset;
476 elf_header_.e_phnum = PH_NUM;
477 elf_header_.e_shnum = section_ptrs.size();
478 elf_header_.e_shstrndx = shstrtab_builder_.section_index_;
479
480 // Add the rest of the pieces to the list.
481 pieces.push_back(ElfFilePiece("Elf Header", 0, &elf_header_, sizeof(elf_header_)));
482 pieces.push_back(ElfFilePiece("Program headers", phdr_offset,
483 &program_headers, sizeof(program_headers)));
484 pieces.push_back(ElfFilePiece(".dynamic", dynamic_builder_.section_.sh_offset,
485 dynamic.data(), dynamic_builder_.section_.sh_size));
486 pieces.push_back(ElfFilePiece(".dynsym", dynsym_builder_.section_.sh_offset,
Brian Carlstrom8758c642014-06-11 14:22:02 -0700487 dynsym.data(), dynsym.size() * sizeof(Elf32_Sym)));
Brian Carlstromb12f3472014-06-11 14:54:46 -0700488 pieces.push_back(ElfFilePiece(".dynstr", dynsym_builder_.strtab_.section_.sh_offset,
489 dynstr.c_str(), dynstr.size()));
490 pieces.push_back(ElfFilePiece(".hash", hash_builder_.section_.sh_offset,
491 hash.data(), hash.size() * sizeof(Elf32_Word)));
492 pieces.push_back(ElfFilePiece(".rodata", rodata_builder_.section_.sh_offset,
Alex Light3470ab42014-06-18 10:35:45 -0700493 nullptr, rodata_builder_.section_.sh_size));
Brian Carlstromb12f3472014-06-11 14:54:46 -0700494 pieces.push_back(ElfFilePiece(".text", text_builder_.section_.sh_offset,
Alex Light3470ab42014-06-18 10:35:45 -0700495 nullptr, text_builder_.section_.sh_size));
Brian Carlstromb12f3472014-06-11 14:54:46 -0700496 if (IncludingDebugSymbols()) {
497 pieces.push_back(ElfFilePiece(".symtab", symtab_builder_.section_.sh_offset,
498 symtab.data(), symtab.size() * sizeof(Elf32_Sym)));
499 pieces.push_back(ElfFilePiece(".strtab", symtab_builder_.strtab_.section_.sh_offset,
500 strtab.c_str(), strtab.size()));
501 }
502 pieces.push_back(ElfFilePiece(".shstrtab", shstrtab_builder_.section_.sh_offset,
503 &shstrtab[0], shstrtab.size()));
504 for (uint32_t i = 0; i < section_ptrs.size(); ++i) {
505 // Just add all the sections in induvidually since they are all over the
506 // place on the heap/stack.
507 Elf32_Word cur_off = sections_offset + i * sizeof(Elf32_Shdr);
508 pieces.push_back(ElfFilePiece("section table piece", cur_off,
509 section_ptrs[i], sizeof(Elf32_Shdr)));
510 }
511
512 if (!WriteOutFile(pieces)) {
513 LOG(ERROR) << "Unable to write to file " << elf_file_->GetPath();
Brian Carlstrom7940e442013-07-12 13:46:57 -0700514 return false;
515 }
Brian Carlstromb12f3472014-06-11 14:54:46 -0700516 // write out the actual oat file data.
517 Elf32_Word oat_data_offset = rodata_builder_.section_.sh_offset;
Brian Carlstrom7940e442013-07-12 13:46:57 -0700518 if (static_cast<off_t>(oat_data_offset) != lseek(elf_file_->Fd(), oat_data_offset, SEEK_SET)) {
519 PLOG(ERROR) << "Failed to seek to .rodata offset " << oat_data_offset
520 << " for " << elf_file_->GetPath();
521 return false;
522 }
Brian Carlstromb12f3472014-06-11 14:54:46 -0700523 std::unique_ptr<BufferedOutputStream> output_stream(
524 new BufferedOutputStream(new FileOutputStream(elf_file_)));
525 if (!oat_writer_->Write(output_stream.get())) {
Brian Carlstrom7940e442013-07-12 13:46:57 -0700526 PLOG(ERROR) << "Failed to write .rodata and .text for " << elf_file_->GetPath();
527 return false;
528 }
529
Brian Carlstrom35f72252014-06-11 21:24:53 +0000530 return true;
Brian Carlstromb12f3472014-06-11 14:54:46 -0700531}
532
533bool ElfWriterQuick::ElfBuilder::WriteOutFile(const std::vector<ElfFilePiece>& pieces) {
534 // TODO It would be nice if this checked for overlap.
535 for (auto it = pieces.begin(); it != pieces.end(); ++it) {
536 if (it->data_) {
537 if (static_cast<off_t>(it->offset_) != lseek(elf_file_->Fd(), it->offset_, SEEK_SET)) {
538 PLOG(ERROR) << "Failed to seek to " << it->dbg_name_ << " offset location "
539 << it->offset_ << " for " << elf_file_->GetPath();
540 return false;
541 }
542 if (!elf_file_->WriteFully(it->data_, it->size_)) {
543 PLOG(ERROR) << "Failed to write " << it->dbg_name_ << " for " << elf_file_->GetPath();
544 return false;
545 }
546 }
547 }
548 return true;
549}
550
551void ElfWriterQuick::ElfBuilder::SetupDynamic() {
552 dynamic_builder_.AddDynamicTag(DT_HASH, 0, &hash_builder_);
553 dynamic_builder_.AddDynamicTag(DT_STRTAB, 0, &dynsym_builder_.strtab_);
554 dynamic_builder_.AddDynamicTag(DT_SYMTAB, 0, &dynsym_builder_);
555 dynamic_builder_.AddDynamicTag(DT_SYMENT, sizeof(Elf32_Sym));
556}
557
558void ElfWriterQuick::ElfBuilder::SetupRequiredSymbols() {
559 dynsym_builder_.AddSymbol("oatdata", &rodata_builder_, 0, true,
560 rodata_builder_.size_, STB_GLOBAL, STT_OBJECT);
561 dynsym_builder_.AddSymbol("oatexec", &text_builder_, 0, true,
562 text_builder_.size_, STB_GLOBAL, STT_OBJECT);
563 dynsym_builder_.AddSymbol("oatlastword", &text_builder_, text_builder_.size_ - 4,
564 true, 4, STB_GLOBAL, STT_OBJECT);
565}
566
Brian Carlstrom8758c642014-06-11 14:22:02 -0700567void ElfWriterQuick::ElfDynamicBuilder::AddDynamicTag(Elf32_Sword tag, Elf32_Word d_un) {
Brian Carlstromb12f3472014-06-11 14:54:46 -0700568 if (tag == DT_NULL) {
569 return;
570 }
Alex Light3470ab42014-06-18 10:35:45 -0700571 dynamics_.push_back({nullptr, tag, d_un});
Brian Carlstromb12f3472014-06-11 14:54:46 -0700572}
573
Brian Carlstrom8758c642014-06-11 14:22:02 -0700574void ElfWriterQuick::ElfDynamicBuilder::AddDynamicTag(Elf32_Sword tag, Elf32_Word d_un,
Brian Carlstromb12f3472014-06-11 14:54:46 -0700575 ElfSectionBuilder* section) {
576 if (tag == DT_NULL) {
577 return;
578 }
579 dynamics_.push_back({section, tag, d_un});
580}
581
Brian Carlstrom8758c642014-06-11 14:22:02 -0700582std::vector<Elf32_Dyn> ElfWriterQuick::ElfDynamicBuilder::GetDynamics(Elf32_Word strsz,
583 Elf32_Word soname) {
Brian Carlstromb12f3472014-06-11 14:54:46 -0700584 std::vector<Elf32_Dyn> ret;
585 for (auto it = dynamics_.cbegin(); it != dynamics_.cend(); ++it) {
586 if (it->section_) {
587 // We are adding an address relative to a section.
588 ret.push_back(
Brian Carlstrom8758c642014-06-11 14:22:02 -0700589 {it->tag_, {it->off_ + it->section_->section_.sh_addr}});
Brian Carlstromb12f3472014-06-11 14:54:46 -0700590 } else {
591 ret.push_back({it->tag_, {it->off_}});
592 }
593 }
594 ret.push_back({DT_STRSZ, {strsz}});
595 ret.push_back({DT_SONAME, {soname}});
596 ret.push_back({DT_NULL, {0}});
597 return ret;
598}
599
600std::vector<Elf32_Sym> ElfWriterQuick::ElfSymtabBuilder::GenerateSymtab() {
601 std::vector<Elf32_Sym> ret;
602 Elf32_Sym undef_sym;
603 memset(&undef_sym, 0, sizeof(undef_sym));
604 undef_sym.st_shndx = SHN_UNDEF;
605 ret.push_back(undef_sym);
606
607 for (auto it = symbols_.cbegin(); it != symbols_.cend(); ++it) {
608 Elf32_Sym sym;
609 memset(&sym, 0, sizeof(sym));
610 sym.st_name = it->name_idx_;
611 if (it->is_relative_) {
612 sym.st_value = it->addr_ + it->section_->section_.sh_offset;
613 } else {
614 sym.st_value = it->addr_;
615 }
616 sym.st_size = it->size_;
617 sym.st_other = it->other_;
618 sym.st_shndx = it->section_->section_index_;
619 sym.st_info = it->info_;
620
621 ret.push_back(sym);
622 }
623 return ret;
624}
625
626std::string ElfWriterQuick::ElfSymtabBuilder::GenerateStrtab() {
627 std::string tab;
628 tab += '\0';
629 for (auto it = symbols_.begin(); it != symbols_.end(); ++it) {
630 it->name_idx_ = tab.size();
631 tab += it->name_;
632 tab += '\0';
633 }
634 strtab_.section_.sh_size = tab.size();
635 return tab;
636}
637
638void ElfWriterQuick::ElfBuilder::AssignSectionStr(
639 ElfSectionBuilder* builder, std::string* strtab) {
640 builder->section_.sh_name = strtab->size();
641 *strtab += builder->name_;
642 *strtab += '\0';
643 if (debug_logging_) {
644 LOG(INFO) << "adding section name \"" << builder->name_ << "\" "
645 << "to shstrtab at offset " << builder->section_.sh_name;
646 }
647}
648
649// from bionic
650static unsigned elfhash(const char *_name) {
651 const unsigned char *name = (const unsigned char *) _name;
652 unsigned h = 0, g;
653
654 while (*name) {
655 h = (h << 4) + *name++;
656 g = h & 0xf0000000;
657 h ^= g;
658 h ^= g >> 24;
659 }
660 return h;
661}
662
663
664std::vector<Elf32_Word> ElfWriterQuick::ElfSymtabBuilder::GenerateHashContents() {
665 // Here is how The ELF hash table works.
666 // There are 3 arrays to worry about.
667 // * The symbol table where the symbol information is.
668 // * The bucket array which is an array of indexes into the symtab and chain.
669 // * The chain array which is also an array of indexes into the symtab and chain.
670 //
671 // Lets say the state is something like this.
672 // +--------+ +--------+ +-----------+
673 // | symtab | | bucket | | chain |
Alex Light3470ab42014-06-18 10:35:45 -0700674 // | nullptr | | 1 | | STN_UNDEF |
Brian Carlstromb12f3472014-06-11 14:54:46 -0700675 // | <sym1> | | 4 | | 2 |
676 // | <sym2> | | | | 5 |
677 // | <sym3> | | | | STN_UNDEF |
678 // | <sym4> | | | | 3 |
679 // | <sym5> | | | | STN_UNDEF |
680 // +--------+ +--------+ +-----------+
681 //
682 // The lookup process (in python psudocode) is
683 //
684 // def GetSym(name):
685 // # NB STN_UNDEF == 0
686 // indx = bucket[elfhash(name) % num_buckets]
687 // while indx != STN_UNDEF:
688 // if GetSymbolName(symtab[indx]) == name:
689 // return symtab[indx]
690 // indx = chain[indx]
691 // return SYMBOL_NOT_FOUND
692 //
693 // Between bucket and chain arrays every symtab index must be present exactly
694 // once (except for STN_UNDEF, which must be present 1 + num_bucket times).
695
696 // Select number of buckets.
697 // This is essentially arbitrary.
698 Elf32_Word nbuckets;
Brian Carlstrom8758c642014-06-11 14:22:02 -0700699 Elf32_Word chain_size = GetSize();
Brian Carlstromb12f3472014-06-11 14:54:46 -0700700 if (symbols_.size() < 8) {
701 nbuckets = 2;
702 } else if (symbols_.size() < 32) {
703 nbuckets = 4;
704 } else if (symbols_.size() < 256) {
705 nbuckets = 16;
706 } else {
707 // Have about 32 ids per bucket.
708 nbuckets = RoundUp(symbols_.size()/32, 2);
709 }
710 std::vector<Elf32_Word> hash;
711 hash.push_back(nbuckets);
712 hash.push_back(chain_size);
713 uint32_t bucket_offset = hash.size();
714 uint32_t chain_offset = bucket_offset + nbuckets;
715 hash.resize(hash.size() + nbuckets + chain_size, 0);
716
717 Elf32_Word* buckets = hash.data() + bucket_offset;
718 Elf32_Word* chain = hash.data() + chain_offset;
719
720 // Set up the actual hash table.
721 for (Elf32_Word i = 0; i < symbols_.size(); i++) {
722 // Add 1 since we need to have the null symbol that is not in the symbols
723 // list.
724 Elf32_Word index = i + 1;
725 Elf32_Word hash_val = static_cast<Elf32_Word>(elfhash(symbols_[i].name_.c_str())) % nbuckets;
726 if (buckets[hash_val] == 0) {
727 buckets[hash_val] = index;
728 } else {
729 hash_val = buckets[hash_val];
730 CHECK_LT(hash_val, chain_size);
731 while (chain[hash_val] != 0) {
732 hash_val = chain[hash_val];
733 CHECK_LT(hash_val, chain_size);
734 }
735 chain[hash_val] = index;
736 // Check for loops. Works because if this is non-empty then there must be
737 // another cell which already contains the same symbol index as this one,
738 // which means some symbol has more then one name, which isn't allowed.
739 CHECK_EQ(chain[index], static_cast<Elf32_Word>(0));
740 }
741 }
742
743 return hash;
744}
745
746void ElfWriterQuick::ElfBuilder::SetupEhdr() {
747 memset(&elf_header_, 0, sizeof(elf_header_));
748 elf_header_.e_ident[EI_MAG0] = ELFMAG0;
749 elf_header_.e_ident[EI_MAG1] = ELFMAG1;
750 elf_header_.e_ident[EI_MAG2] = ELFMAG2;
751 elf_header_.e_ident[EI_MAG3] = ELFMAG3;
752 elf_header_.e_ident[EI_CLASS] = ELFCLASS32;
753 elf_header_.e_ident[EI_DATA] = ELFDATA2LSB;
754 elf_header_.e_ident[EI_VERSION] = EV_CURRENT;
755 elf_header_.e_ident[EI_OSABI] = ELFOSABI_LINUX;
756 elf_header_.e_ident[EI_ABIVERSION] = 0;
757 elf_header_.e_type = ET_DYN;
758 elf_header_.e_version = 1;
759 elf_header_.e_entry = 0;
760 elf_header_.e_ehsize = sizeof(Elf32_Ehdr);
761 elf_header_.e_phentsize = sizeof(Elf32_Phdr);
762 elf_header_.e_shentsize = sizeof(Elf32_Shdr);
763 elf_header_.e_phoff = sizeof(Elf32_Ehdr);
764}
765
766void ElfWriterQuick::ElfBuilder::SetISA(InstructionSet isa) {
767 switch (isa) {
768 case kArm:
769 // Fall through.
770 case kThumb2: {
771 elf_header_.e_machine = EM_ARM;
772 elf_header_.e_flags = EF_ARM_EABI_VER5;
773 break;
774 }
775 case kArm64: {
776 elf_header_.e_machine = EM_AARCH64;
777 elf_header_.e_flags = 0;
778 break;
779 }
780 case kX86: {
781 elf_header_.e_machine = EM_386;
782 elf_header_.e_flags = 0;
783 break;
784 }
785 case kX86_64: {
786 elf_header_.e_machine = EM_X86_64;
787 elf_header_.e_flags = 0;
788 break;
789 }
790 case kMips: {
791 elf_header_.e_machine = EM_MIPS;
792 elf_header_.e_flags = (EF_MIPS_NOREORDER |
793 EF_MIPS_PIC |
794 EF_MIPS_CPIC |
795 EF_MIPS_ABI_O32 |
796 EF_MIPS_ARCH_32R2);
797 break;
798 }
799 default: {
800 fatal_error_ = true;
801 LOG(FATAL) << "Unknown instruction set: " << isa;
802 break;
803 }
804 }
805}
806
807void ElfWriterQuick::ElfSymtabBuilder::AddSymbol(
808 const std::string& name, const ElfSectionBuilder* section, Elf32_Addr addr,
809 bool is_relative, Elf32_Word size, uint8_t binding, uint8_t type, uint8_t other) {
810 CHECK(section);
811 ElfSymtabBuilder::ElfSymbolState state {name, section, addr, size, is_relative,
812 MakeStInfo(binding, type), other, 0};
813 symbols_.push_back(state);
814}
815
816bool ElfWriterQuick::Create(File* elf_file,
817 OatWriter* oat_writer,
818 const std::vector<const DexFile*>& dex_files,
819 const std::string& android_root,
820 bool is_host,
821 const CompilerDriver& driver) {
822 ElfWriterQuick elf_writer(driver, elf_file);
823 return elf_writer.Write(oat_writer, dex_files, android_root, is_host);
824}
825
Alex Light53cb16b2014-06-12 11:26:29 -0700826// Add patch information to this section. Each patch is a Elf32_Word that
827// identifies an offset from the start of the text section
828void ElfWriterQuick::ReservePatchSpace(std::vector<uint8_t>* buffer, bool debug) {
829 size_t size =
830 compiler_driver_->GetCodeToPatch().size() +
831 compiler_driver_->GetMethodsToPatch().size() +
832 compiler_driver_->GetClassesToPatch().size();
833 if (size == 0) {
834 if (debug) {
835 LOG(INFO) << "No patches to record";
836 }
837 return;
838 }
839 buffer->resize(size * sizeof(uintptr_t));
840 if (debug) {
841 LOG(INFO) << "Patches reserved for " << size;
842 }
843}
844
Andreas Gampe79273802014-08-05 20:21:05 -0700845static void EncodeUnsignedLeb128(uint32_t data, std::vector<uint8_t>* dst) {
846 size_t encoded_size = UnsignedLeb128Size(data);
847 size_t cur_index = dst->size();
848 dst->resize(dst->size() + encoded_size);
849 uint8_t* write_pos = &((*dst)[cur_index]);
850 uint8_t* write_pos_after = EncodeUnsignedLeb128(write_pos, data);
851 DCHECK_EQ(static_cast<size_t>(write_pos_after - write_pos), encoded_size);
852}
853
854static void EncodeSignedLeb128(int32_t data, std::vector<uint8_t>* dst) {
855 size_t encoded_size = SignedLeb128Size(data);
856 size_t cur_index = dst->size();
857 dst->resize(dst->size() + encoded_size);
858 uint8_t* write_pos = &((*dst)[cur_index]);
859 uint8_t* write_pos_after = EncodeSignedLeb128(write_pos, data);
860 DCHECK_EQ(static_cast<size_t>(write_pos_after - write_pos), encoded_size);
861}
862
863std::vector<uint8_t>* ConstructCIEFrameX86(bool is_x86_64) {
864 std::vector<uint8_t>*cfi_info = new std::vector<uint8_t>;
865
866 // Length (will be filled in later in this routine).
867 PushWord(cfi_info, 0);
868
869 // CIE id: always 0.
870 PushWord(cfi_info, 0);
871
872 // Version: always 1.
873 cfi_info->push_back(0x01);
874
875 // Augmentation: 'zR\0'
876 cfi_info->push_back(0x7a);
877 cfi_info->push_back(0x52);
878 cfi_info->push_back(0x0);
879
880 // Code alignment: 1.
881 EncodeUnsignedLeb128(1, cfi_info);
882
883 // Data alignment.
884 if (is_x86_64) {
885 EncodeSignedLeb128(-8, cfi_info);
886 } else {
887 EncodeSignedLeb128(-4, cfi_info);
888 }
889
890 // Return address register.
891 if (is_x86_64) {
892 // R16(RIP)
893 cfi_info->push_back(0x10);
894 } else {
895 // R8(EIP)
896 cfi_info->push_back(0x08);
897 }
898
899 // Augmentation length: 1.
900 cfi_info->push_back(1);
901
902 // Augmentation data: 0x03 ((DW_EH_PE_absptr << 4) | DW_EH_PE_udata4).
903 cfi_info->push_back(0x03);
904
905 // Initial instructions.
906 if (is_x86_64) {
907 // DW_CFA_def_cfa R7(RSP) 8.
908 cfi_info->push_back(0x0c);
909 cfi_info->push_back(0x07);
910 cfi_info->push_back(0x08);
911
912 // DW_CFA_offset R16(RIP) 1 (* -8).
913 cfi_info->push_back(0x90);
914 cfi_info->push_back(0x01);
915 } else {
916 // DW_CFA_def_cfa R4(ESP) 4.
917 cfi_info->push_back(0x0c);
918 cfi_info->push_back(0x04);
919 cfi_info->push_back(0x04);
920
921 // DW_CFA_offset R8(EIP) 1 (* -4).
922 cfi_info->push_back(0x88);
923 cfi_info->push_back(0x01);
924 }
925
926 // Padding to a multiple of 4
927 while ((cfi_info->size() & 3) != 0) {
928 // DW_CFA_nop is encoded as 0.
929 cfi_info->push_back(0);
930 }
931
932 // Set the length of the CIE inside the generated bytes.
933 uint32_t length = cfi_info->size() - 4;
934 (*cfi_info)[0] = length;
935 (*cfi_info)[1] = length >> 8;
936 (*cfi_info)[2] = length >> 16;
937 (*cfi_info)[3] = length >> 24;
938 return cfi_info;
939}
940
941std::vector<uint8_t>* ConstructCIEFrame(InstructionSet isa) {
942 switch (isa) {
943 case kX86:
944 return ConstructCIEFrameX86(false);
945 case kX86_64:
946 return ConstructCIEFrameX86(true);
947
948 default:
949 // Not implemented.
950 return nullptr;
951 }
952}
953
Brian Carlstromb12f3472014-06-11 14:54:46 -0700954bool ElfWriterQuick::Write(OatWriter* oat_writer,
955 const std::vector<const DexFile*>& dex_files_unused,
956 const std::string& android_root_unused,
957 bool is_host_unused) {
Andreas Gampe79273802014-08-05 20:21:05 -0700958 constexpr bool debug = false;
Brian Carlstromb12f3472014-06-11 14:54:46 -0700959 const OatHeader& oat_header = oat_writer->GetOatHeader();
960 Elf32_Word oat_data_size = oat_header.GetExecutableOffset();
961 uint32_t oat_exec_size = oat_writer->GetSize() - oat_data_size;
962
963 ElfBuilder builder(oat_writer, elf_file_, compiler_driver_->GetInstructionSet(), 0,
Andreas Gampe79273802014-08-05 20:21:05 -0700964 oat_data_size, oat_data_size, oat_exec_size,
965 compiler_driver_->GetCompilerOptions().GetIncludeDebugSymbols(),
966 debug);
Alex Light78382fa2014-06-06 15:45:32 -0700967
Andreas Gampe79273802014-08-05 20:21:05 -0700968 if (compiler_driver_->GetCompilerOptions().GetIncludeDebugSymbols()) {
969 WriteDebugSymbols(builder, oat_writer);
Brian Carlstromb12f3472014-06-11 14:54:46 -0700970 }
971
Alex Light53cb16b2014-06-12 11:26:29 -0700972 if (compiler_driver_->GetCompilerOptions().GetIncludePatchInformation()) {
973 ElfRawSectionBuilder oat_patches(".oat_patches", SHT_OAT_PATCH, 0, NULL, 0,
974 sizeof(size_t), sizeof(size_t));
975 ReservePatchSpace(oat_patches.GetBuffer(), debug);
976 builder.RegisterRawSection(oat_patches);
977 }
978
Brian Carlstromb12f3472014-06-11 14:54:46 -0700979 return builder.Write();
980}
Mark Mendellae9fd932014-02-10 16:14:35 -0800981
Andreas Gampe79273802014-08-05 20:21:05 -0700982void ElfWriterQuick::WriteDebugSymbols(ElfBuilder& builder, OatWriter* oat_writer) {
983 std::unique_ptr<std::vector<uint8_t>> cfi_info(
984 ConstructCIEFrame(compiler_driver_->GetInstructionSet()));
985
986 // Iterate over the compiled methods.
Alex Light78382fa2014-06-06 15:45:32 -0700987 const std::vector<OatWriter::DebugInfo>& method_info = oat_writer->GetCFIMethodInfo();
988 ElfSymtabBuilder* symtab = &builder.symtab_builder_;
989 for (auto it = method_info.begin(); it != method_info.end(); ++it) {
990 symtab->AddSymbol(it->method_name_, &builder.text_builder_, it->low_pc_, true,
991 it->high_pc_ - it->low_pc_, STB_GLOBAL, STT_FUNC);
Andreas Gampe79273802014-08-05 20:21:05 -0700992
993 // Include CFI for compiled method, if possible.
994 if (cfi_info.get() != nullptr) {
995 DCHECK(it->compiled_method_ != nullptr);
996
997 // Copy in the FDE, if present
998 const std::vector<uint8_t>* fde = it->compiled_method_->GetCFIInfo();
999 if (fde != nullptr) {
1000 // Copy the information into cfi_info and then fix the address in the new copy.
1001 int cur_offset = cfi_info->size();
1002 cfi_info->insert(cfi_info->end(), fde->begin(), fde->end());
1003
1004 // Set the 'CIE_pointer' field to cur_offset+4.
1005 uint32_t CIE_pointer = cur_offset + 4;
1006 uint32_t offset_to_update = cur_offset + sizeof(uint32_t);
1007 (*cfi_info)[offset_to_update+0] = CIE_pointer;
1008 (*cfi_info)[offset_to_update+1] = CIE_pointer >> 8;
1009 (*cfi_info)[offset_to_update+2] = CIE_pointer >> 16;
1010 (*cfi_info)[offset_to_update+3] = CIE_pointer >> 24;
1011
1012 // Set the 'initial_location' field to address the start of the method.
1013 offset_to_update = cur_offset + 2*sizeof(uint32_t);
1014 const uint32_t quick_code_start = it->low_pc_;
1015 (*cfi_info)[offset_to_update+0] = quick_code_start;
1016 (*cfi_info)[offset_to_update+1] = quick_code_start >> 8;
1017 (*cfi_info)[offset_to_update+2] = quick_code_start >> 16;
1018 (*cfi_info)[offset_to_update+3] = quick_code_start >> 24;
1019 }
1020 }
Alex Light78382fa2014-06-06 15:45:32 -07001021 }
Alex Light78382fa2014-06-06 15:45:32 -07001022
Andreas Gampe79273802014-08-05 20:21:05 -07001023 if (cfi_info.get() != nullptr) {
1024 // Now lay down the Elf sections.
1025 ElfRawSectionBuilder debug_info(".debug_info", SHT_PROGBITS, 0, nullptr, 0, 1, 0);
1026 ElfRawSectionBuilder debug_abbrev(".debug_abbrev", SHT_PROGBITS, 0, nullptr, 0, 1, 0);
1027 ElfRawSectionBuilder debug_str(".debug_str", SHT_PROGBITS, 0, nullptr, 0, 1, 0);
1028 ElfRawSectionBuilder eh_frame(".eh_frame", SHT_PROGBITS, SHF_ALLOC, nullptr, 0, 4, 0);
1029 eh_frame.SetBuffer(std::move(*cfi_info.get()));
Mark Mendellae9fd932014-02-10 16:14:35 -08001030
Andreas Gampe79273802014-08-05 20:21:05 -07001031 FillInCFIInformation(oat_writer, debug_info.GetBuffer(), debug_abbrev.GetBuffer(),
1032 debug_str.GetBuffer());
1033 builder.RegisterRawSection(debug_info);
1034 builder.RegisterRawSection(debug_abbrev);
1035 builder.RegisterRawSection(eh_frame);
1036 builder.RegisterRawSection(debug_str);
1037 }
Mark Mendellae9fd932014-02-10 16:14:35 -08001038}
1039
Mark Mendellae9fd932014-02-10 16:14:35 -08001040void ElfWriterQuick::FillInCFIInformation(OatWriter* oat_writer,
1041 std::vector<uint8_t>* dbg_info,
1042 std::vector<uint8_t>* dbg_abbrev,
1043 std::vector<uint8_t>* dbg_str) {
1044 // Create the debug_abbrev section with boilerplate information.
1045 // We only care about low_pc and high_pc right now for the compilation
1046 // unit and methods.
1047
1048 // Tag 1: Compilation unit: DW_TAG_compile_unit.
1049 dbg_abbrev->push_back(1);
1050 dbg_abbrev->push_back(DW_TAG_compile_unit);
1051
1052 // There are children (the methods).
1053 dbg_abbrev->push_back(DW_CHILDREN_yes);
1054
1055 // DW_LANG_Java DW_FORM_data1.
1056 dbg_abbrev->push_back(DW_AT_language);
1057 dbg_abbrev->push_back(DW_FORM_data1);
1058
1059 // DW_AT_low_pc DW_FORM_addr.
1060 dbg_abbrev->push_back(DW_AT_low_pc);
1061 dbg_abbrev->push_back(DW_FORM_addr);
1062
1063 // DW_AT_high_pc DW_FORM_addr.
1064 dbg_abbrev->push_back(DW_AT_high_pc);
1065 dbg_abbrev->push_back(DW_FORM_addr);
1066
1067 // End of DW_TAG_compile_unit.
1068 PushHalf(dbg_abbrev, 0);
1069
1070 // Tag 2: Compilation unit: DW_TAG_subprogram.
1071 dbg_abbrev->push_back(2);
1072 dbg_abbrev->push_back(DW_TAG_subprogram);
1073
1074 // There are no children.
1075 dbg_abbrev->push_back(DW_CHILDREN_no);
1076
1077 // Name of the method.
1078 dbg_abbrev->push_back(DW_AT_name);
1079 dbg_abbrev->push_back(DW_FORM_strp);
1080
1081 // DW_AT_low_pc DW_FORM_addr.
1082 dbg_abbrev->push_back(DW_AT_low_pc);
1083 dbg_abbrev->push_back(DW_FORM_addr);
1084
1085 // DW_AT_high_pc DW_FORM_addr.
1086 dbg_abbrev->push_back(DW_AT_high_pc);
1087 dbg_abbrev->push_back(DW_FORM_addr);
1088
1089 // End of DW_TAG_subprogram.
1090 PushHalf(dbg_abbrev, 0);
1091
1092 // Start the debug_info section with the header information
1093 // 'unit_length' will be filled in later.
1094 PushWord(dbg_info, 0);
1095
1096 // 'version' - 3.
1097 PushHalf(dbg_info, 3);
1098
1099 // Offset into .debug_abbrev section (always 0).
1100 PushWord(dbg_info, 0);
1101
1102 // Address size: 4.
1103 dbg_info->push_back(4);
1104
1105 // Start the description for the compilation unit.
1106 // This uses tag 1.
1107 dbg_info->push_back(1);
1108
1109 // The language is Java.
1110 dbg_info->push_back(DW_LANG_Java);
1111
1112 // Leave space for low_pc and high_pc.
1113 int low_pc_offset = dbg_info->size();
1114 PushWord(dbg_info, 0);
1115 PushWord(dbg_info, 0);
1116
1117 // Walk through the information in the method table, and enter into dbg_info.
1118 const std::vector<OatWriter::DebugInfo>& dbg = oat_writer->GetCFIMethodInfo();
1119 uint32_t low_pc = 0xFFFFFFFFU;
1120 uint32_t high_pc = 0;
1121
1122 for (uint32_t i = 0; i < dbg.size(); i++) {
1123 const OatWriter::DebugInfo& info = dbg[i];
1124 if (info.low_pc_ < low_pc) {
1125 low_pc = info.low_pc_;
1126 }
1127 if (info.high_pc_ > high_pc) {
1128 high_pc = info.high_pc_;
1129 }
1130
1131 // Start a new TAG: subroutine (2).
1132 dbg_info->push_back(2);
1133
1134 // Enter the name into the string table (and NUL terminate).
1135 uint32_t str_offset = dbg_str->size();
1136 dbg_str->insert(dbg_str->end(), info.method_name_.begin(), info.method_name_.end());
1137 dbg_str->push_back('\0');
1138
1139 // Enter name, low_pc, high_pc.
1140 PushWord(dbg_info, str_offset);
1141 PushWord(dbg_info, info.low_pc_);
1142 PushWord(dbg_info, info.high_pc_);
1143 }
1144
1145 // One byte terminator
1146 dbg_info->push_back(0);
1147
1148 // We have now walked all the methods. Fill in lengths and low/high PCs.
1149 UpdateWord(dbg_info, 0, dbg_info->size() - 4);
1150 UpdateWord(dbg_info, low_pc_offset, low_pc);
1151 UpdateWord(dbg_info, low_pc_offset + 4, high_pc);
Brian Carlstrom7940e442013-07-12 13:46:57 -07001152}
1153
1154} // namespace art