blob: c8ddde6caeacbfcbc57394a5787dd31a07adac16 [file] [log] [blame]
Dmitriy Ivanov87a06172015-02-06 10:56:28 -08001// Copyright 2014 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// Implementation notes:
6//
7// We need to remove a piece from the ELF shared library. However, we also
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -08008// want to avoid fixing DWARF cfi data and relative relocation addresses.
9// So after packing we shift offets and starting address of the RX segment
10// while preserving code/data vaddrs location.
11// This requires some fixups for symtab/hash/gnu_hash dynamic section addresses.
Dmitriy Ivanov87a06172015-02-06 10:56:28 -080012
13#include "elf_file.h"
14
15#include <stdlib.h>
16#include <sys/types.h>
17#include <unistd.h>
18#include <algorithm>
19#include <string>
20#include <vector>
21
22#include "debug.h"
23#include "elf_traits.h"
24#include "libelf.h"
25#include "packer.h"
26
27namespace relocation_packer {
28
Dmitriy Ivanov87a06172015-02-06 10:56:28 -080029// Out-of-band dynamic tags used to indicate the offset and size of the
30// android packed relocations section.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -080031static constexpr int32_t DT_ANDROID_REL = DT_LOOS + 2;
32static constexpr int32_t DT_ANDROID_RELSZ = DT_LOOS + 3;
33
34static constexpr int32_t DT_ANDROID_RELA = DT_LOOS + 4;
35static constexpr int32_t DT_ANDROID_RELASZ = DT_LOOS + 5;
36
37static constexpr uint32_t SHT_ANDROID_REL = SHT_LOOS + 1;
38static constexpr uint32_t SHT_ANDROID_RELA = SHT_LOOS + 2;
Dmitriy Ivanov87a06172015-02-06 10:56:28 -080039
40// Alignment to preserve, in bytes. This must be at least as large as the
41// largest d_align and sh_addralign values found in the loaded file.
42// Out of caution for RELRO page alignment, we preserve to a complete target
43// page. See http://www.airs.com/blog/archives/189.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -080044static constexpr size_t kPreserveAlignment = 4096;
Dmitriy Ivanov87a06172015-02-06 10:56:28 -080045
46// Get section data. Checks that the section has exactly one data entry,
47// so that the section size and the data size are the same. True in
48// practice for all sections we resize when packing or unpacking. Done
49// by ensuring that a call to elf_getdata(section, data) returns NULL as
50// the next data entry.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -080051static Elf_Data* GetSectionData(Elf_Scn* section) {
Dmitriy Ivanov87a06172015-02-06 10:56:28 -080052 Elf_Data* data = elf_getdata(section, NULL);
53 CHECK(data && elf_getdata(section, data) == NULL);
54 return data;
55}
56
57// Rewrite section data. Allocates new data and makes it the data element's
58// buffer. Relies on program exit to free allocated data.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -080059static void RewriteSectionData(Elf_Scn* section,
60 const void* section_data,
61 size_t size) {
Dmitriy Ivanov87a06172015-02-06 10:56:28 -080062 Elf_Data* data = GetSectionData(section);
63 CHECK(size == data->d_size);
64 uint8_t* area = new uint8_t[size];
65 memcpy(area, section_data, size);
66 data->d_buf = area;
67}
68
69// Verbose ELF header logging.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -080070template <typename Ehdr>
71static void VerboseLogElfHeader(const Ehdr* elf_header) {
Dmitriy Ivanov87a06172015-02-06 10:56:28 -080072 VLOG(1) << "e_phoff = " << elf_header->e_phoff;
73 VLOG(1) << "e_shoff = " << elf_header->e_shoff;
74 VLOG(1) << "e_ehsize = " << elf_header->e_ehsize;
75 VLOG(1) << "e_phentsize = " << elf_header->e_phentsize;
76 VLOG(1) << "e_phnum = " << elf_header->e_phnum;
77 VLOG(1) << "e_shnum = " << elf_header->e_shnum;
78 VLOG(1) << "e_shstrndx = " << elf_header->e_shstrndx;
79}
80
81// Verbose ELF program header logging.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -080082template <typename Phdr>
83static void VerboseLogProgramHeader(size_t program_header_index,
84 const Phdr* program_header) {
Dmitriy Ivanov87a06172015-02-06 10:56:28 -080085 std::string type;
86 switch (program_header->p_type) {
87 case PT_NULL: type = "NULL"; break;
88 case PT_LOAD: type = "LOAD"; break;
89 case PT_DYNAMIC: type = "DYNAMIC"; break;
90 case PT_INTERP: type = "INTERP"; break;
91 case PT_PHDR: type = "PHDR"; break;
92 case PT_GNU_RELRO: type = "GNU_RELRO"; break;
93 case PT_GNU_STACK: type = "GNU_STACK"; break;
94 case PT_ARM_EXIDX: type = "EXIDX"; break;
95 default: type = "(OTHER)"; break;
96 }
97 VLOG(1) << "phdr[" << program_header_index << "] : " << type;
98 VLOG(1) << " p_offset = " << program_header->p_offset;
99 VLOG(1) << " p_vaddr = " << program_header->p_vaddr;
100 VLOG(1) << " p_paddr = " << program_header->p_paddr;
101 VLOG(1) << " p_filesz = " << program_header->p_filesz;
102 VLOG(1) << " p_memsz = " << program_header->p_memsz;
103 VLOG(1) << " p_flags = " << program_header->p_flags;
104 VLOG(1) << " p_align = " << program_header->p_align;
105}
106
107// Verbose ELF section header logging.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800108template <typename Shdr>
109static void VerboseLogSectionHeader(const std::string& section_name,
110 const Shdr* section_header) {
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800111 VLOG(1) << "section " << section_name;
112 VLOG(1) << " sh_addr = " << section_header->sh_addr;
113 VLOG(1) << " sh_offset = " << section_header->sh_offset;
114 VLOG(1) << " sh_size = " << section_header->sh_size;
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800115 VLOG(1) << " sh_entsize = " << section_header->sh_entsize;
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800116 VLOG(1) << " sh_addralign = " << section_header->sh_addralign;
117}
118
119// Verbose ELF section data logging.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800120static void VerboseLogSectionData(const Elf_Data* data) {
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800121 VLOG(1) << " data";
122 VLOG(1) << " d_buf = " << data->d_buf;
123 VLOG(1) << " d_off = " << data->d_off;
124 VLOG(1) << " d_size = " << data->d_size;
125 VLOG(1) << " d_align = " << data->d_align;
126}
127
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800128// Load the complete ELF file into a memory image in libelf, and identify
129// the .rel.dyn or .rela.dyn, .dynamic, and .android.rel.dyn or
130// .android.rela.dyn sections. No-op if the ELF file has already been loaded.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800131template <typename ELF>
132bool ElfFile<ELF>::Load() {
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800133 if (elf_)
134 return true;
135
136 Elf* elf = elf_begin(fd_, ELF_C_RDWR, NULL);
137 CHECK(elf);
138
139 if (elf_kind(elf) != ELF_K_ELF) {
140 LOG(ERROR) << "File not in ELF format";
141 return false;
142 }
143
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800144 auto elf_header = ELF::getehdr(elf);
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800145 if (!elf_header) {
146 LOG(ERROR) << "Failed to load ELF header: " << elf_errmsg(elf_errno());
147 return false;
148 }
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800149
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800150 if (elf_header->e_type != ET_DYN) {
151 LOG(ERROR) << "ELF file is not a shared object";
152 return false;
153 }
154
155 // Require that our endianness matches that of the target, and that both
156 // are little-endian. Safe for all current build/target combinations.
157 const int endian = elf_header->e_ident[EI_DATA];
158 CHECK(endian == ELFDATA2LSB);
159 CHECK(__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__);
160
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800161 const int file_class = elf_header->e_ident[EI_CLASS];
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800162 VLOG(1) << "endian = " << endian << ", file class = " << file_class;
163 VerboseLogElfHeader(elf_header);
164
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800165 auto elf_program_header = ELF::getphdr(elf);
166 CHECK(elf_program_header != nullptr);
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800167
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800168 const typename ELF::Phdr* dynamic_program_header = NULL;
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800169 for (size_t i = 0; i < elf_header->e_phnum; ++i) {
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800170 auto program_header = &elf_program_header[i];
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800171 VerboseLogProgramHeader(i, program_header);
172
173 if (program_header->p_type == PT_DYNAMIC) {
174 CHECK(dynamic_program_header == NULL);
175 dynamic_program_header = program_header;
176 }
177 }
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800178 CHECK(dynamic_program_header != nullptr);
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800179
180 size_t string_index;
181 elf_getshdrstrndx(elf, &string_index);
182
183 // Notes of the dynamic relocations, packed relocations, and .dynamic
184 // sections. Found while iterating sections, and later stored in class
185 // attributes.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800186 Elf_Scn* found_relocations_section = nullptr;
187 Elf_Scn* found_dynamic_section = nullptr;
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800188
189 // Notes of relocation section types seen. We require one or the other of
190 // these; both is unsupported.
191 bool has_rel_relocations = false;
192 bool has_rela_relocations = false;
Dmitriy Ivanovf15ceeb2015-04-21 15:03:04 -0700193 bool has_android_relocations = false;
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800194
195 Elf_Scn* section = NULL;
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800196 while ((section = elf_nextscn(elf, section)) != nullptr) {
197 auto section_header = ELF::getshdr(section);
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800198 std::string name = elf_strptr(elf, string_index, section_header->sh_name);
199 VerboseLogSectionHeader(name, section_header);
200
201 // Note relocation section types.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800202 if (section_header->sh_type == SHT_REL || section_header->sh_type == SHT_ANDROID_REL) {
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800203 has_rel_relocations = true;
204 }
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800205 if (section_header->sh_type == SHT_RELA || section_header->sh_type == SHT_ANDROID_RELA) {
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800206 has_rela_relocations = true;
207 }
208
209 // Note special sections as we encounter them.
210 if ((name == ".rel.dyn" || name == ".rela.dyn") &&
211 section_header->sh_size > 0) {
212 found_relocations_section = section;
Dmitriy Ivanovf15ceeb2015-04-21 15:03:04 -0700213
214 // Note if relocation section is already packed
215 has_android_relocations =
216 section_header->sh_type == SHT_ANDROID_REL ||
217 section_header->sh_type == SHT_ANDROID_RELA;
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800218 }
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800219
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800220 if (section_header->sh_offset == dynamic_program_header->p_offset) {
221 found_dynamic_section = section;
222 }
223
224 // Ensure we preserve alignment, repeated later for the data block(s).
225 CHECK(section_header->sh_addralign <= kPreserveAlignment);
226
227 Elf_Data* data = NULL;
228 while ((data = elf_getdata(section, data)) != NULL) {
229 CHECK(data->d_align <= kPreserveAlignment);
230 VerboseLogSectionData(data);
231 }
232 }
233
234 // Loading failed if we did not find the required special sections.
235 if (!found_relocations_section) {
236 LOG(ERROR) << "Missing or empty .rel.dyn or .rela.dyn section";
237 return false;
238 }
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800239 if (!found_dynamic_section) {
240 LOG(ERROR) << "Missing .dynamic section";
241 return false;
242 }
243
244 // Loading failed if we could not identify the relocations type.
245 if (!has_rel_relocations && !has_rela_relocations) {
246 LOG(ERROR) << "No relocations sections found";
247 return false;
248 }
249 if (has_rel_relocations && has_rela_relocations) {
250 LOG(ERROR) << "Multiple relocations sections with different types found, "
251 << "not currently supported";
252 return false;
253 }
254
255 elf_ = elf;
256 relocations_section_ = found_relocations_section;
257 dynamic_section_ = found_dynamic_section;
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800258 relocations_type_ = has_rel_relocations ? REL : RELA;
Dmitriy Ivanovf15ceeb2015-04-21 15:03:04 -0700259 has_android_relocations_ = has_android_relocations;
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800260 return true;
261}
262
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800263// Helper for ResizeSection(). Adjust the main ELF header for the hole.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800264template <typename ELF>
265static void AdjustElfHeaderForHole(typename ELF::Ehdr* elf_header,
266 typename ELF::Off hole_start,
267 ssize_t hole_size) {
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800268 if (elf_header->e_phoff > hole_start) {
269 elf_header->e_phoff += hole_size;
270 VLOG(1) << "e_phoff adjusted to " << elf_header->e_phoff;
271 }
272 if (elf_header->e_shoff > hole_start) {
273 elf_header->e_shoff += hole_size;
274 VLOG(1) << "e_shoff adjusted to " << elf_header->e_shoff;
275 }
276}
277
278// Helper for ResizeSection(). Adjust all section headers for the hole.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800279template <typename ELF>
280static void AdjustSectionHeadersForHole(Elf* elf,
281 typename ELF::Off hole_start,
282 ssize_t hole_size) {
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800283 size_t string_index;
284 elf_getshdrstrndx(elf, &string_index);
285
286 Elf_Scn* section = NULL;
287 while ((section = elf_nextscn(elf, section)) != NULL) {
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800288 auto section_header = ELF::getshdr(section);
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800289 std::string name = elf_strptr(elf, string_index, section_header->sh_name);
290
291 if (section_header->sh_offset > hole_start) {
292 section_header->sh_offset += hole_size;
293 VLOG(1) << "section " << name
294 << " sh_offset adjusted to " << section_header->sh_offset;
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800295 } else {
296 section_header->sh_addr -= hole_size;
297 VLOG(1) << "section " << name
298 << " sh_addr adjusted to " << section_header->sh_addr;
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800299 }
300 }
301}
302
303// Helper for ResizeSection(). Adjust the offsets of any program headers
304// that have offsets currently beyond the hole start.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800305template <typename ELF>
306static void AdjustProgramHeaderOffsets(typename ELF::Phdr* program_headers,
307 size_t count,
308 typename ELF::Off hole_start,
309 ssize_t hole_size) {
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800310 for (size_t i = 0; i < count; ++i) {
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800311 typename ELF::Phdr* program_header = &program_headers[i];
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800312
313 if (program_header->p_offset > hole_start) {
314 // The hole start is past this segment, so adjust offset.
315 program_header->p_offset += hole_size;
316 VLOG(1) << "phdr[" << i
317 << "] p_offset adjusted to "<< program_header->p_offset;
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800318 } else {
319 program_header->p_vaddr -= hole_size;
320 program_header->p_paddr -= hole_size;
321 VLOG(1) << "phdr[" << i
322 << "] p_vaddr adjusted to "<< program_header->p_vaddr
323 << "; p_paddr adjusted to "<< program_header->p_paddr;
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800324 }
325 }
326}
327
328// Helper for ResizeSection(). Find the first loadable segment in the
329// file. We expect it to map from file offset zero.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800330template <typename ELF>
331static typename ELF::Phdr* FindLoadSegmentForHole(typename ELF::Phdr* program_headers,
332 size_t count,
333 typename ELF::Off hole_start) {
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800334 for (size_t i = 0; i < count; ++i) {
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800335 typename ELF::Phdr* program_header = &program_headers[i];
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800336
337 if (program_header->p_type == PT_LOAD &&
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800338 program_header->p_offset <= hole_start &&
339 (program_header->p_offset + program_header->p_filesz) >= hole_start ) {
340 return program_header;
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800341 }
342 }
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800343 LOG(FATAL) << "Cannot locate a LOAD segment with hole_start=0x" << std::hex << hole_start;
344 NOTREACHED();
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800345
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800346 return nullptr;
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800347}
348
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800349// Helper for ResizeSection(). Rewrite program headers.
350template <typename ELF>
351static void RewriteProgramHeadersForHole(Elf* elf,
352 typename ELF::Off hole_start,
353 ssize_t hole_size) {
354 const typename ELF::Ehdr* elf_header = ELF::getehdr(elf);
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800355 CHECK(elf_header);
356
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800357 typename ELF::Phdr* elf_program_header = ELF::getphdr(elf);
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800358 CHECK(elf_program_header);
359
360 const size_t program_header_count = elf_header->e_phnum;
361
362 // Locate the segment that we can overwrite to form the new LOAD entry,
363 // and the segment that we are going to split into two parts.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800364 typename ELF::Phdr* target_load_header =
365 FindLoadSegmentForHole<ELF>(elf_program_header, program_header_count, hole_start);
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800366
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800367 VLOG(1) << "phdr[" << target_load_header - elf_program_header << "] adjust";
368 // Adjust PT_LOAD program header memsz and filesz
369 target_load_header->p_filesz += hole_size;
370 target_load_header->p_memsz += hole_size;
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800371
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800372 // Adjust the offsets and p_vaddrs
373 AdjustProgramHeaderOffsets<ELF>(elf_program_header,
374 program_header_count,
375 hole_start,
376 hole_size);
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800377}
378
379// Helper for ResizeSection(). Locate and return the dynamic section.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800380template <typename ELF>
381static Elf_Scn* GetDynamicSection(Elf* elf) {
382 const typename ELF::Ehdr* elf_header = ELF::getehdr(elf);
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800383 CHECK(elf_header);
384
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800385 const typename ELF::Phdr* elf_program_header = ELF::getphdr(elf);
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800386 CHECK(elf_program_header);
387
388 // Find the program header that describes the dynamic section.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800389 const typename ELF::Phdr* dynamic_program_header = NULL;
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800390 for (size_t i = 0; i < elf_header->e_phnum; ++i) {
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800391 const typename ELF::Phdr* program_header = &elf_program_header[i];
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800392
393 if (program_header->p_type == PT_DYNAMIC) {
394 dynamic_program_header = program_header;
395 }
396 }
397 CHECK(dynamic_program_header);
398
399 // Now find the section with the same offset as this program header.
400 Elf_Scn* dynamic_section = NULL;
401 Elf_Scn* section = NULL;
402 while ((section = elf_nextscn(elf, section)) != NULL) {
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800403 typename ELF::Shdr* section_header = ELF::getshdr(section);
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800404
405 if (section_header->sh_offset == dynamic_program_header->p_offset) {
406 dynamic_section = section;
407 }
408 }
409 CHECK(dynamic_section != NULL);
410
411 return dynamic_section;
412}
413
414// Helper for ResizeSection(). Adjust the .dynamic section for the hole.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800415template <typename ELF>
416void ElfFile<ELF>::AdjustDynamicSectionForHole(Elf_Scn* dynamic_section,
417 typename ELF::Off hole_start,
418 ssize_t hole_size,
419 relocations_type_t relocations_type) {
420 CHECK(relocations_type != NONE);
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800421 Elf_Data* data = GetSectionData(dynamic_section);
422
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800423 auto dynamic_base = reinterpret_cast<typename ELF::Dyn*>(data->d_buf);
424 std::vector<typename ELF::Dyn> dynamics(
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800425 dynamic_base,
426 dynamic_base + data->d_size / sizeof(dynamics[0]));
427
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800428 if (hole_size > 0) { // expanding
429 hole_start += hole_size;
430 }
431
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800432 for (size_t i = 0; i < dynamics.size(); ++i) {
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800433 typename ELF::Dyn* dynamic = &dynamics[i];
434 const typename ELF::Sword tag = dynamic->d_tag;
435
436 // Any tags that hold offsets are adjustment candidates.
437 const bool is_adjustable = (tag == DT_PLTGOT ||
438 tag == DT_HASH ||
439 tag == DT_GNU_HASH ||
440 tag == DT_STRTAB ||
441 tag == DT_SYMTAB ||
442 tag == DT_RELA ||
443 tag == DT_INIT ||
444 tag == DT_FINI ||
445 tag == DT_REL ||
446 tag == DT_JMPREL ||
447 tag == DT_INIT_ARRAY ||
448 tag == DT_FINI_ARRAY ||
Dmitriy Ivanovbb25bbe2015-04-20 17:41:28 -0700449 tag == DT_VERSYM ||
450 tag == DT_VERNEED ||
451 tag == DT_VERDEF ||
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800452 tag == DT_ANDROID_REL||
453 tag == DT_ANDROID_RELA);
454
455 if (is_adjustable && dynamic->d_un.d_ptr <= hole_start) {
456 dynamic->d_un.d_ptr -= hole_size;
457 VLOG(1) << "dynamic[" << i << "] " << dynamic->d_tag
458 << " d_ptr adjusted to " << dynamic->d_un.d_ptr;
459 }
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800460
461 // DT_RELSZ or DT_RELASZ indicate the overall size of relocations.
462 // Only one will be present. Adjust by hole size.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800463 if (tag == DT_RELSZ || tag == DT_RELASZ || tag == DT_ANDROID_RELSZ || tag == DT_ANDROID_RELASZ) {
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800464 dynamic->d_un.d_val += hole_size;
465 VLOG(1) << "dynamic[" << i << "] " << dynamic->d_tag
466 << " d_val adjusted to " << dynamic->d_un.d_val;
467 }
468
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800469 // Ignore DT_RELCOUNT and DT_RELACOUNT: (1) nobody uses them and
470 // technically (2) the relative relocation count is not changed.
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800471
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800472 // DT_RELENT and DT_RELAENT don't change, ignore them as well.
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800473 }
474
475 void* section_data = &dynamics[0];
476 size_t bytes = dynamics.size() * sizeof(dynamics[0]);
477 RewriteSectionData(dynamic_section, section_data, bytes);
478}
479
480// Resize a section. If the new size is larger than the current size, open
481// up a hole by increasing file offsets that come after the hole. If smaller
482// than the current size, remove the hole by decreasing those offsets.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800483template <typename ELF>
484void ElfFile<ELF>::ResizeSection(Elf* elf, Elf_Scn* section, size_t new_size,
485 typename ELF::Word new_sh_type,
486 relocations_type_t relocations_type) {
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800487
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800488 size_t string_index;
489 elf_getshdrstrndx(elf, &string_index);
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800490 auto section_header = ELF::getshdr(section);
491 std::string name = elf_strptr(elf, string_index, section_header->sh_name);
492
493 if (section_header->sh_size == new_size) {
494 return;
495 }
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800496
497 // Require that the section size and the data size are the same. True
498 // in practice for all sections we resize when packing or unpacking.
499 Elf_Data* data = GetSectionData(section);
500 CHECK(data->d_off == 0 && data->d_size == section_header->sh_size);
501
502 // Require that the section is not zero-length (that is, has allocated
503 // data that we can validly expand).
504 CHECK(data->d_size && data->d_buf);
505
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800506 const auto hole_start = section_header->sh_offset;
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800507 const ssize_t hole_size = new_size - data->d_size;
508
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800509 VLOG_IF(1, (hole_size > 0)) << "expand section (" << name << ") size: " <<
510 data->d_size << " -> " << (data->d_size + hole_size);
511 VLOG_IF(1, (hole_size < 0)) << "shrink section (" << name << ") size: " <<
512 data->d_size << " -> " << (data->d_size + hole_size);
513
514 // libelf overrides sh_entsize for known sh_types, so it does not matter what we set
515 // for SHT_REL/SHT_RELA.
516 typename ELF::Xword new_entsize =
517 (new_sh_type == SHT_ANDROID_REL || new_sh_type == SHT_ANDROID_RELA) ? 1 : 0;
518
519 VLOG(1) << "Update section (" << name << ") entry size: " <<
520 section_header->sh_entsize << " -> " << new_entsize;
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800521
522 // Resize the data and the section header.
523 data->d_size += hole_size;
524 section_header->sh_size += hole_size;
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800525 section_header->sh_entsize = new_entsize;
526 section_header->sh_type = new_sh_type;
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800527
528 // Add the hole size to all offsets in the ELF file that are after the
529 // start of the hole. If the hole size is positive we are expanding the
530 // section to create a new hole; if negative, we are closing up a hole.
531
532 // Start with the main ELF header.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800533 typename ELF::Ehdr* elf_header = ELF::getehdr(elf);
534 AdjustElfHeaderForHole<ELF>(elf_header, hole_start, hole_size);
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800535
536 // Adjust all section headers.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800537 AdjustSectionHeadersForHole<ELF>(elf, hole_start, hole_size);
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800538
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800539 // Rewrite the program headers to either split or coalesce segments,
540 // and adjust dynamic entries to match.
541 RewriteProgramHeadersForHole<ELF>(elf, hole_start, hole_size);
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800542
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800543 Elf_Scn* dynamic_section = GetDynamicSection<ELF>(elf);
544 AdjustDynamicSectionForHole(dynamic_section, hole_start, hole_size, relocations_type);
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800545}
546
547// Find the first slot in a dynamics array with the given tag. The array
548// always ends with a free (unused) element, and which we exclude from the
549// search. Returns dynamics->size() if not found.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800550template <typename ELF>
551static size_t FindDynamicEntry(typename ELF::Sword tag,
552 std::vector<typename ELF::Dyn>* dynamics) {
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800553 // Loop until the penultimate entry. We exclude the end sentinel.
554 for (size_t i = 0; i < dynamics->size() - 1; ++i) {
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800555 if (dynamics->at(i).d_tag == tag) {
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800556 return i;
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800557 }
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800558 }
559
560 // The tag was not found.
561 return dynamics->size();
562}
563
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800564// Replace dynamic entry.
565template <typename ELF>
566static void ReplaceDynamicEntry(typename ELF::Sword tag,
567 const typename ELF::Dyn& dyn,
568 std::vector<typename ELF::Dyn>* dynamics) {
569 const size_t slot = FindDynamicEntry<ELF>(tag, dynamics);
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800570 if (slot == dynamics->size()) {
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800571 LOG(FATAL) << "Dynamic slot is not found for tag=" << tag;
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800572 }
573
574 // Replace this entry with the one supplied.
575 dynamics->at(slot) = dyn;
576 VLOG(1) << "dynamic[" << slot << "] overwritten with " << dyn.d_tag;
577}
578
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800579// Remove relative entries from dynamic relocations and write as packed
580// data into android packed relocations.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800581template <typename ELF>
582bool ElfFile<ELF>::PackRelocations() {
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800583 // Load the ELF file into libelf.
584 if (!Load()) {
585 LOG(ERROR) << "Failed to load as ELF";
586 return false;
587 }
588
589 // Retrieve the current dynamic relocations section data.
590 Elf_Data* data = GetSectionData(relocations_section_);
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800591 // we always pack rela, because packed format is pretty much the same
592 std::vector<typename ELF::Rela> relocations;
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800593
594 if (relocations_type_ == REL) {
595 // Convert data to a vector of relocations.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800596 const typename ELF::Rel* relocations_base = reinterpret_cast<typename ELF::Rel*>(data->d_buf);
597 ConvertRelArrayToRelaVector(relocations_base,
598 data->d_size / sizeof(typename ELF::Rel), &relocations);
Dmitriy Ivanovbb25bbe2015-04-20 17:41:28 -0700599 VLOG(1) << "Relocations : REL";
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800600 } else if (relocations_type_ == RELA) {
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800601 // Convert data to a vector of relocations with addends.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800602 const typename ELF::Rela* relocations_base = reinterpret_cast<typename ELF::Rela*>(data->d_buf);
603 relocations = std::vector<typename ELF::Rela>(
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800604 relocations_base,
605 relocations_base + data->d_size / sizeof(relocations[0]));
606
Dmitriy Ivanovbb25bbe2015-04-20 17:41:28 -0700607 VLOG(1) << "Relocations : RELA";
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800608 } else {
609 NOTREACHED();
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800610 }
611
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800612 return PackTypedRelocations(&relocations);
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800613}
614
615// Helper for PackRelocations(). Rel type is one of ELF::Rel or ELF::Rela.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800616template <typename ELF>
617bool ElfFile<ELF>::PackTypedRelocations(std::vector<typename ELF::Rela>* relocations) {
618 typedef typename ELF::Rela Rela;
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800619
Dmitriy Ivanovf15ceeb2015-04-21 15:03:04 -0700620 if (has_android_relocations_) {
Dmitriy Ivanovb0b93382015-04-24 12:39:14 -0700621 LOG(INFO) << "Relocation table is already packed";
622 return true;
Dmitriy Ivanovf15ceeb2015-04-21 15:03:04 -0700623 }
624
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800625 // If no relocations then we have nothing packable. Perhaps
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800626 // the shared object has already been packed?
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800627 if (relocations->empty()) {
Dmitriy Ivanovf15ceeb2015-04-21 15:03:04 -0700628 LOG(ERROR) << "No relocations found";
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800629 return false;
630 }
631
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800632 const size_t rel_size =
633 relocations_type_ == RELA ? sizeof(typename ELF::Rela) : sizeof(typename ELF::Rel);
634 const size_t initial_bytes = relocations->size() * rel_size;
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800635
Dmitriy Ivanovbb25bbe2015-04-20 17:41:28 -0700636 VLOG(1) << "Unpacked : " << initial_bytes << " bytes";
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800637 std::vector<uint8_t> packed;
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800638 RelocationPacker<ELF> packer;
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800639
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800640 // Pack relocations: dry run to estimate memory savings.
641 packer.PackRelocations(*relocations, &packed);
642 const size_t packed_bytes_estimate = packed.size() * sizeof(packed[0]);
Dmitriy Ivanovbb25bbe2015-04-20 17:41:28 -0700643 VLOG(1) << "Packed (no padding): " << packed_bytes_estimate << " bytes";
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800644
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800645 if (packed.empty()) {
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800646 LOG(INFO) << "Too few relocations to pack";
Dmitriy Ivanovbb25bbe2015-04-20 17:41:28 -0700647 return true;
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800648 }
649
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800650 // Pre-calculate the size of the hole we will close up when we rewrite
651 // dynamic relocations. We have to adjust relocation addresses to
652 // account for this.
653 typename ELF::Shdr* section_header = ELF::getshdr(relocations_section_);
654 ssize_t hole_size = initial_bytes - packed_bytes_estimate;
655
656 // hole_size needs to be page_aligned.
657 hole_size -= hole_size % kPreserveAlignment;
658
659 LOG(INFO) << "Compaction : " << hole_size << " bytes";
660
661 // Adjusting for alignment may have removed any packing benefit.
662 if (hole_size == 0) {
663 LOG(INFO) << "Too few relocations to pack after alignment";
Dmitriy Ivanovbb25bbe2015-04-20 17:41:28 -0700664 return true;
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800665 }
666
667 if (hole_size <= 0) {
668 LOG(INFO) << "Packing relocations saves no space";
Dmitriy Ivanovadfcb972015-04-23 13:47:39 -0700669 return true;
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800670 }
671
672 size_t data_padding_bytes = is_padding_relocations_ ?
673 initial_bytes - packed_bytes_estimate :
674 initial_bytes - hole_size - packed_bytes_estimate;
675
676 // pad data
677 std::vector<uint8_t> padding(data_padding_bytes, 0);
678 packed.insert(packed.end(), padding.begin(), padding.end());
679
680 const void* packed_data = &packed[0];
681
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800682 // Run a loopback self-test as a check that packing is lossless.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800683 std::vector<Rela> unpacked;
684 packer.UnpackRelocations(packed, &unpacked);
685 CHECK(unpacked.size() == relocations->size());
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800686 CHECK(!memcmp(&unpacked[0],
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800687 &relocations->at(0),
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800688 unpacked.size() * sizeof(unpacked[0])));
689
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800690 // Rewrite the current dynamic relocations section with packed one then shrink it to size.
691 const size_t bytes = packed.size() * sizeof(packed[0]);
692 ResizeSection(elf_, relocations_section_, bytes,
693 relocations_type_ == REL ? SHT_ANDROID_REL : SHT_ANDROID_RELA, relocations_type_);
694 RewriteSectionData(relocations_section_, packed_data, bytes);
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800695
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800696 // TODO (dimitry): fix string table and replace .rel.dyn/plt with .android.rel.dyn/plt
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800697
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800698 // Rewrite .dynamic and rename relocation tags describing the packed android
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800699 // relocations.
700 Elf_Data* data = GetSectionData(dynamic_section_);
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800701 const typename ELF::Dyn* dynamic_base = reinterpret_cast<typename ELF::Dyn*>(data->d_buf);
702 std::vector<typename ELF::Dyn> dynamics(
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800703 dynamic_base,
704 dynamic_base + data->d_size / sizeof(dynamics[0]));
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800705 section_header = ELF::getshdr(relocations_section_);
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800706 {
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800707 typename ELF::Dyn dyn;
708 dyn.d_tag = relocations_type_ == REL ? DT_ANDROID_REL : DT_ANDROID_RELA;
709 dyn.d_un.d_ptr = section_header->sh_addr;
710 ReplaceDynamicEntry<ELF>(relocations_type_ == REL ? DT_REL : DT_RELA, dyn, &dynamics);
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800711 }
712 {
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800713 typename ELF::Dyn dyn;
714 dyn.d_tag = relocations_type_ == REL ? DT_ANDROID_RELSZ : DT_ANDROID_RELASZ;
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800715 dyn.d_un.d_val = section_header->sh_size;
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800716 ReplaceDynamicEntry<ELF>(relocations_type_ == REL ? DT_RELSZ : DT_RELASZ, dyn, &dynamics);
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800717 }
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800718
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800719 const void* dynamics_data = &dynamics[0];
720 const size_t dynamics_bytes = dynamics.size() * sizeof(dynamics[0]);
721 RewriteSectionData(dynamic_section_, dynamics_data, dynamics_bytes);
722
723 Flush();
724 return true;
725}
726
727// Find packed relative relocations in the packed android relocations
728// section, unpack them, and rewrite the dynamic relocations section to
729// contain unpacked data.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800730template <typename ELF>
731bool ElfFile<ELF>::UnpackRelocations() {
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800732 // Load the ELF file into libelf.
733 if (!Load()) {
734 LOG(ERROR) << "Failed to load as ELF";
735 return false;
736 }
737
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800738 typename ELF::Shdr* section_header = ELF::getshdr(relocations_section_);
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800739 // Retrieve the current packed android relocations section data.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800740 Elf_Data* data = GetSectionData(relocations_section_);
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800741
742 // Convert data to a vector of bytes.
743 const uint8_t* packed_base = reinterpret_cast<uint8_t*>(data->d_buf);
744 std::vector<uint8_t> packed(
745 packed_base,
746 packed_base + data->d_size / sizeof(packed[0]));
747
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800748 if ((section_header->sh_type == SHT_ANDROID_RELA || section_header->sh_type == SHT_ANDROID_REL) &&
749 packed.size() > 3 &&
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800750 packed[0] == 'A' &&
751 packed[1] == 'P' &&
Dmitriy Ivanovf15ceeb2015-04-21 15:03:04 -0700752 packed[2] == 'S' &&
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800753 packed[3] == '2') {
754 LOG(INFO) << "Relocations : " << (relocations_type_ == REL ? "REL" : "RELA");
755 } else {
756 LOG(ERROR) << "Packed relocations not found (not packed?)";
757 return false;
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800758 }
759
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800760 return UnpackTypedRelocations(packed);
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800761}
762
763// Helper for UnpackRelocations(). Rel type is one of ELF::Rel or ELF::Rela.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800764template <typename ELF>
765bool ElfFile<ELF>::UnpackTypedRelocations(const std::vector<uint8_t>& packed) {
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800766 // Unpack the data to re-materialize the relative relocations.
767 const size_t packed_bytes = packed.size() * sizeof(packed[0]);
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800768 LOG(INFO) << "Packed : " << packed_bytes << " bytes";
769 std::vector<typename ELF::Rela> unpacked_relocations;
770 RelocationPacker<ELF> packer;
771 packer.UnpackRelocations(packed, &unpacked_relocations);
772
773 const size_t relocation_entry_size =
774 relocations_type_ == REL ? sizeof(typename ELF::Rel) : sizeof(typename ELF::Rela);
775 const size_t unpacked_bytes = unpacked_relocations.size() * relocation_entry_size;
776 LOG(INFO) << "Unpacked : " << unpacked_bytes << " bytes";
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800777
778 // Retrieve the current dynamic relocations section data.
779 Elf_Data* data = GetSectionData(relocations_section_);
780
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800781 LOG(INFO) << "Relocations : " << unpacked_relocations.size() << " entries";
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800782
783 // If we found the same number of null relocation entries in the dynamic
784 // relocations section as we hold as unpacked relative relocations, then
785 // this is a padded file.
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800786
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800787 const bool is_padded = packed_bytes == unpacked_bytes;
788
789 // Unless padded, pre-apply relative relocations to account for the
790 // hole, and pre-adjust all relocation offsets accordingly.
791 typename ELF::Shdr* section_header = ELF::getshdr(relocations_section_);
792
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800793 if (!is_padded) {
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800794 LOG(INFO) << "Expansion : " << unpacked_bytes - packed_bytes << " bytes";
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800795 }
796
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800797 // Rewrite the current dynamic relocations section with unpacked version of
798 // relocations.
799 const void* section_data = nullptr;
800 std::vector<typename ELF::Rel> unpacked_rel_relocations;
801 if (relocations_type_ == RELA) {
802 section_data = &unpacked_relocations[0];
803 } else if (relocations_type_ == REL) {
804 ConvertRelaVectorToRelVector(unpacked_relocations, &unpacked_rel_relocations);
805 section_data = &unpacked_rel_relocations[0];
806 } else {
807 NOTREACHED();
808 }
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800809
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800810 ResizeSection(elf_, relocations_section_, unpacked_bytes,
811 relocations_type_ == REL ? SHT_REL : SHT_RELA, relocations_type_);
812 RewriteSectionData(relocations_section_, section_data, unpacked_bytes);
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800813
814 // Rewrite .dynamic to remove two tags describing packed android relocations.
815 data = GetSectionData(dynamic_section_);
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800816 const typename ELF::Dyn* dynamic_base = reinterpret_cast<typename ELF::Dyn*>(data->d_buf);
817 std::vector<typename ELF::Dyn> dynamics(
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800818 dynamic_base,
819 dynamic_base + data->d_size / sizeof(dynamics[0]));
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800820 {
821 typename ELF::Dyn dyn;
822 dyn.d_tag = relocations_type_ == REL ? DT_REL : DT_RELA;
823 dyn.d_un.d_ptr = section_header->sh_addr;
824 ReplaceDynamicEntry<ELF>(relocations_type_ == REL ? DT_ANDROID_REL : DT_ANDROID_RELA,
825 dyn, &dynamics);
826 }
827
828 {
829 typename ELF::Dyn dyn;
830 dyn.d_tag = relocations_type_ == REL ? DT_RELSZ : DT_RELASZ;
831 dyn.d_un.d_val = section_header->sh_size;
832 ReplaceDynamicEntry<ELF>(relocations_type_ == REL ? DT_ANDROID_RELSZ : DT_ANDROID_RELASZ,
833 dyn, &dynamics);
834 }
835
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800836 const void* dynamics_data = &dynamics[0];
837 const size_t dynamics_bytes = dynamics.size() * sizeof(dynamics[0]);
838 RewriteSectionData(dynamic_section_, dynamics_data, dynamics_bytes);
839
840 Flush();
841 return true;
842}
843
844// Flush rewritten shared object file data.
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800845template <typename ELF>
846void ElfFile<ELF>::Flush() {
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800847 // Flag all ELF data held in memory as needing to be written back to the
848 // file, and tell libelf that we have controlled the file layout.
849 elf_flagelf(elf_, ELF_C_SET, ELF_F_DIRTY);
850 elf_flagelf(elf_, ELF_C_SET, ELF_F_LAYOUT);
851
852 // Write ELF data back to disk.
853 const off_t file_bytes = elf_update(elf_, ELF_C_WRITE);
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800854 if (file_bytes == -1) {
855 LOG(ERROR) << "elf_update failed: " << elf_errmsg(elf_errno());
856 }
857
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800858 CHECK(file_bytes > 0);
859 VLOG(1) << "elf_update returned: " << file_bytes;
860
861 // Clean up libelf, and truncate the output file to the number of bytes
862 // written by elf_update().
863 elf_end(elf_);
864 elf_ = NULL;
865 const int truncate = ftruncate(fd_, file_bytes);
866 CHECK(truncate == 0);
867}
868
Dmitriy Ivanovf8ff6b12015-01-27 19:32:56 -0800869template <typename ELF>
870void ElfFile<ELF>::ConvertRelArrayToRelaVector(const typename ELF::Rel* rel_array,
871 size_t rel_array_size,
872 std::vector<typename ELF::Rela>* rela_vector) {
873 for (size_t i = 0; i<rel_array_size; ++i) {
874 typename ELF::Rela rela;
875 rela.r_offset = rel_array[i].r_offset;
876 rela.r_info = rel_array[i].r_info;
877 rela.r_addend = 0;
878 rela_vector->push_back(rela);
879 }
880}
881
882template <typename ELF>
883void ElfFile<ELF>::ConvertRelaVectorToRelVector(const std::vector<typename ELF::Rela>& rela_vector,
884 std::vector<typename ELF::Rel>* rel_vector) {
885 for (auto rela : rela_vector) {
886 typename ELF::Rel rel;
887 rel.r_offset = rela.r_offset;
888 rel.r_info = rela.r_info;
889 CHECK(rela.r_addend == 0);
890 rel_vector->push_back(rel);
891 }
892}
893
894template class ElfFile<ELF32_traits>;
895template class ElfFile<ELF64_traits>;
896
Dmitriy Ivanov87a06172015-02-06 10:56:28 -0800897} // namespace relocation_packer