OLD | NEW |
(Empty) | |
| 1 // 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 |
| 8 // 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. |
| 12 |
| 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 |
| 27 namespace relocation_packer { |
| 28 |
| 29 // Out-of-band dynamic tags used to indicate the offset and size of the |
| 30 // android packed relocations section. |
| 31 static constexpr int32_t DT_ANDROID_REL = DT_LOOS + 2; |
| 32 static constexpr int32_t DT_ANDROID_RELSZ = DT_LOOS + 3; |
| 33 |
| 34 static constexpr int32_t DT_ANDROID_RELA = DT_LOOS + 4; |
| 35 static constexpr int32_t DT_ANDROID_RELASZ = DT_LOOS + 5; |
| 36 |
| 37 static constexpr uint32_t SHT_ANDROID_REL = SHT_LOOS + 1; |
| 38 static constexpr uint32_t SHT_ANDROID_RELA = SHT_LOOS + 2; |
| 39 |
| 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. |
| 44 static constexpr size_t kPreserveAlignment = 4096; |
| 45 |
| 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. |
| 51 static Elf_Data* GetSectionData(Elf_Scn* section) { |
| 52 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. |
| 59 static void RewriteSectionData(Elf_Scn* section, |
| 60 const void* section_data, |
| 61 size_t size) { |
| 62 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. |
| 70 template <typename Ehdr> |
| 71 static void VerboseLogElfHeader(const Ehdr* elf_header) { |
| 72 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. |
| 82 template <typename Phdr> |
| 83 static void VerboseLogProgramHeader(size_t program_header_index, |
| 84 const Phdr* program_header) { |
| 85 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. |
| 108 template <typename Shdr> |
| 109 static void VerboseLogSectionHeader(const std::string& section_name, |
| 110 const Shdr* section_header) { |
| 111 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; |
| 115 VLOG(1) << " sh_entsize = " << section_header->sh_entsize; |
| 116 VLOG(1) << " sh_addralign = " << section_header->sh_addralign; |
| 117 } |
| 118 |
| 119 // Verbose ELF section data logging. |
| 120 static void VerboseLogSectionData(const Elf_Data* data) { |
| 121 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 |
| 128 // 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. |
| 131 template <typename ELF> |
| 132 bool ElfFile<ELF>::Load() { |
| 133 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 |
| 144 auto elf_header = ELF::getehdr(elf); |
| 145 if (!elf_header) { |
| 146 LOG(ERROR) << "Failed to load ELF header: " << elf_errmsg(elf_errno()); |
| 147 return false; |
| 148 } |
| 149 |
| 150 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 |
| 161 const int file_class = elf_header->e_ident[EI_CLASS]; |
| 162 VLOG(1) << "endian = " << endian << ", file class = " << file_class; |
| 163 VerboseLogElfHeader(elf_header); |
| 164 |
| 165 auto elf_program_header = ELF::getphdr(elf); |
| 166 CHECK(elf_program_header != nullptr); |
| 167 |
| 168 const typename ELF::Phdr* dynamic_program_header = NULL; |
| 169 for (size_t i = 0; i < elf_header->e_phnum; ++i) { |
| 170 auto program_header = &elf_program_header[i]; |
| 171 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 } |
| 178 CHECK(dynamic_program_header != nullptr); |
| 179 |
| 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. |
| 186 Elf_Scn* found_relocations_section = nullptr; |
| 187 Elf_Scn* found_dynamic_section = nullptr; |
| 188 |
| 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; |
| 193 |
| 194 Elf_Scn* section = NULL; |
| 195 while ((section = elf_nextscn(elf, section)) != nullptr) { |
| 196 auto section_header = ELF::getshdr(section); |
| 197 std::string name = elf_strptr(elf, string_index, section_header->sh_name); |
| 198 VerboseLogSectionHeader(name, section_header); |
| 199 |
| 200 // Note relocation section types. |
| 201 if (section_header->sh_type == SHT_REL || section_header->sh_type == SHT_AND
ROID_REL) { |
| 202 has_rel_relocations = true; |
| 203 } |
| 204 if (section_header->sh_type == SHT_RELA || section_header->sh_type == SHT_AN
DROID_RELA) { |
| 205 has_rela_relocations = true; |
| 206 } |
| 207 |
| 208 // Note special sections as we encounter them. |
| 209 if ((name == ".rel.dyn" || name == ".rela.dyn") && |
| 210 section_header->sh_size > 0) { |
| 211 found_relocations_section = section; |
| 212 } |
| 213 |
| 214 if (section_header->sh_offset == dynamic_program_header->p_offset) { |
| 215 found_dynamic_section = section; |
| 216 } |
| 217 |
| 218 // Ensure we preserve alignment, repeated later for the data block(s). |
| 219 CHECK(section_header->sh_addralign <= kPreserveAlignment); |
| 220 |
| 221 Elf_Data* data = NULL; |
| 222 while ((data = elf_getdata(section, data)) != NULL) { |
| 223 CHECK(data->d_align <= kPreserveAlignment); |
| 224 VerboseLogSectionData(data); |
| 225 } |
| 226 } |
| 227 |
| 228 // Loading failed if we did not find the required special sections. |
| 229 if (!found_relocations_section) { |
| 230 LOG(ERROR) << "Missing or empty .rel.dyn or .rela.dyn section"; |
| 231 return false; |
| 232 } |
| 233 if (!found_dynamic_section) { |
| 234 LOG(ERROR) << "Missing .dynamic section"; |
| 235 return false; |
| 236 } |
| 237 |
| 238 // Loading failed if we could not identify the relocations type. |
| 239 if (!has_rel_relocations && !has_rela_relocations) { |
| 240 LOG(ERROR) << "No relocations sections found"; |
| 241 return false; |
| 242 } |
| 243 if (has_rel_relocations && has_rela_relocations) { |
| 244 LOG(ERROR) << "Multiple relocations sections with different types found, " |
| 245 << "not currently supported"; |
| 246 return false; |
| 247 } |
| 248 |
| 249 elf_ = elf; |
| 250 relocations_section_ = found_relocations_section; |
| 251 dynamic_section_ = found_dynamic_section; |
| 252 relocations_type_ = has_rel_relocations ? REL : RELA; |
| 253 return true; |
| 254 } |
| 255 |
| 256 // Helper for ResizeSection(). Adjust the main ELF header for the hole. |
| 257 template <typename ELF> |
| 258 static void AdjustElfHeaderForHole(typename ELF::Ehdr* elf_header, |
| 259 typename ELF::Off hole_start, |
| 260 ssize_t hole_size) { |
| 261 if (elf_header->e_phoff > hole_start) { |
| 262 elf_header->e_phoff += hole_size; |
| 263 VLOG(1) << "e_phoff adjusted to " << elf_header->e_phoff; |
| 264 } |
| 265 if (elf_header->e_shoff > hole_start) { |
| 266 elf_header->e_shoff += hole_size; |
| 267 VLOG(1) << "e_shoff adjusted to " << elf_header->e_shoff; |
| 268 } |
| 269 } |
| 270 |
| 271 // Helper for ResizeSection(). Adjust all section headers for the hole. |
| 272 template <typename ELF> |
| 273 static void AdjustSectionHeadersForHole(Elf* elf, |
| 274 typename ELF::Off hole_start, |
| 275 ssize_t hole_size) { |
| 276 size_t string_index; |
| 277 elf_getshdrstrndx(elf, &string_index); |
| 278 |
| 279 Elf_Scn* section = NULL; |
| 280 while ((section = elf_nextscn(elf, section)) != NULL) { |
| 281 auto section_header = ELF::getshdr(section); |
| 282 std::string name = elf_strptr(elf, string_index, section_header->sh_name); |
| 283 |
| 284 if (section_header->sh_offset > hole_start) { |
| 285 section_header->sh_offset += hole_size; |
| 286 VLOG(1) << "section " << name |
| 287 << " sh_offset adjusted to " << section_header->sh_offset; |
| 288 } else { |
| 289 section_header->sh_addr -= hole_size; |
| 290 VLOG(1) << "section " << name |
| 291 << " sh_addr adjusted to " << section_header->sh_addr; |
| 292 } |
| 293 } |
| 294 } |
| 295 |
| 296 // Helper for ResizeSection(). Adjust the offsets of any program headers |
| 297 // that have offsets currently beyond the hole start. |
| 298 template <typename ELF> |
| 299 static void AdjustProgramHeaderOffsets(typename ELF::Phdr* program_headers, |
| 300 size_t count, |
| 301 typename ELF::Off hole_start, |
| 302 ssize_t hole_size) { |
| 303 for (size_t i = 0; i < count; ++i) { |
| 304 typename ELF::Phdr* program_header = &program_headers[i]; |
| 305 |
| 306 if (program_header->p_offset > hole_start) { |
| 307 // The hole start is past this segment, so adjust offset. |
| 308 program_header->p_offset += hole_size; |
| 309 VLOG(1) << "phdr[" << i |
| 310 << "] p_offset adjusted to "<< program_header->p_offset; |
| 311 } else { |
| 312 program_header->p_vaddr -= hole_size; |
| 313 program_header->p_paddr -= hole_size; |
| 314 VLOG(1) << "phdr[" << i |
| 315 << "] p_vaddr adjusted to "<< program_header->p_vaddr |
| 316 << "; p_paddr adjusted to "<< program_header->p_paddr; |
| 317 } |
| 318 } |
| 319 } |
| 320 |
| 321 // Helper for ResizeSection(). Find the first loadable segment in the |
| 322 // file. We expect it to map from file offset zero. |
| 323 template <typename ELF> |
| 324 static typename ELF::Phdr* FindLoadSegmentForHole(typename ELF::Phdr* program_he
aders, |
| 325 size_t count, |
| 326 typename ELF::Off hole_start)
{ |
| 327 for (size_t i = 0; i < count; ++i) { |
| 328 typename ELF::Phdr* program_header = &program_headers[i]; |
| 329 |
| 330 if (program_header->p_type == PT_LOAD && |
| 331 program_header->p_offset <= hole_start && |
| 332 (program_header->p_offset + program_header->p_filesz) >= hole_start ) { |
| 333 return program_header; |
| 334 } |
| 335 } |
| 336 LOG(FATAL) << "Cannot locate a LOAD segment with hole_start=0x" << std::hex <<
hole_start; |
| 337 NOTREACHED(); |
| 338 |
| 339 return nullptr; |
| 340 } |
| 341 |
| 342 // Helper for ResizeSection(). Rewrite program headers. |
| 343 template <typename ELF> |
| 344 static void RewriteProgramHeadersForHole(Elf* elf, |
| 345 typename ELF::Off hole_start, |
| 346 ssize_t hole_size) { |
| 347 const typename ELF::Ehdr* elf_header = ELF::getehdr(elf); |
| 348 CHECK(elf_header); |
| 349 |
| 350 typename ELF::Phdr* elf_program_header = ELF::getphdr(elf); |
| 351 CHECK(elf_program_header); |
| 352 |
| 353 const size_t program_header_count = elf_header->e_phnum; |
| 354 |
| 355 // Locate the segment that we can overwrite to form the new LOAD entry, |
| 356 // and the segment that we are going to split into two parts. |
| 357 typename ELF::Phdr* target_load_header = |
| 358 FindLoadSegmentForHole<ELF>(elf_program_header, program_header_count, hole
_start); |
| 359 |
| 360 VLOG(1) << "phdr[" << target_load_header - elf_program_header << "] adjust"; |
| 361 // Adjust PT_LOAD program header memsz and filesz |
| 362 target_load_header->p_filesz += hole_size; |
| 363 target_load_header->p_memsz += hole_size; |
| 364 |
| 365 // Adjust the offsets and p_vaddrs |
| 366 AdjustProgramHeaderOffsets<ELF>(elf_program_header, |
| 367 program_header_count, |
| 368 hole_start, |
| 369 hole_size); |
| 370 } |
| 371 |
| 372 // Helper for ResizeSection(). Locate and return the dynamic section. |
| 373 template <typename ELF> |
| 374 static Elf_Scn* GetDynamicSection(Elf* elf) { |
| 375 const typename ELF::Ehdr* elf_header = ELF::getehdr(elf); |
| 376 CHECK(elf_header); |
| 377 |
| 378 const typename ELF::Phdr* elf_program_header = ELF::getphdr(elf); |
| 379 CHECK(elf_program_header); |
| 380 |
| 381 // Find the program header that describes the dynamic section. |
| 382 const typename ELF::Phdr* dynamic_program_header = NULL; |
| 383 for (size_t i = 0; i < elf_header->e_phnum; ++i) { |
| 384 const typename ELF::Phdr* program_header = &elf_program_header[i]; |
| 385 |
| 386 if (program_header->p_type == PT_DYNAMIC) { |
| 387 dynamic_program_header = program_header; |
| 388 } |
| 389 } |
| 390 CHECK(dynamic_program_header); |
| 391 |
| 392 // Now find the section with the same offset as this program header. |
| 393 Elf_Scn* dynamic_section = NULL; |
| 394 Elf_Scn* section = NULL; |
| 395 while ((section = elf_nextscn(elf, section)) != NULL) { |
| 396 typename ELF::Shdr* section_header = ELF::getshdr(section); |
| 397 |
| 398 if (section_header->sh_offset == dynamic_program_header->p_offset) { |
| 399 dynamic_section = section; |
| 400 } |
| 401 } |
| 402 CHECK(dynamic_section != NULL); |
| 403 |
| 404 return dynamic_section; |
| 405 } |
| 406 |
| 407 // Helper for ResizeSection(). Adjust the .dynamic section for the hole. |
| 408 template <typename ELF> |
| 409 void ElfFile<ELF>::AdjustDynamicSectionForHole(Elf_Scn* dynamic_section, |
| 410 typename ELF::Off hole_start, |
| 411 ssize_t hole_size, |
| 412 relocations_type_t relocations_ty
pe) { |
| 413 CHECK(relocations_type != NONE); |
| 414 Elf_Data* data = GetSectionData(dynamic_section); |
| 415 |
| 416 auto dynamic_base = reinterpret_cast<typename ELF::Dyn*>(data->d_buf); |
| 417 std::vector<typename ELF::Dyn> dynamics( |
| 418 dynamic_base, |
| 419 dynamic_base + data->d_size / sizeof(dynamics[0])); |
| 420 |
| 421 if (hole_size > 0) { // expanding |
| 422 hole_start += hole_size; |
| 423 } |
| 424 |
| 425 for (size_t i = 0; i < dynamics.size(); ++i) { |
| 426 typename ELF::Dyn* dynamic = &dynamics[i]; |
| 427 const typename ELF::Sword tag = dynamic->d_tag; |
| 428 |
| 429 // Any tags that hold offsets are adjustment candidates. |
| 430 const bool is_adjustable = (tag == DT_PLTGOT || |
| 431 tag == DT_HASH || |
| 432 tag == DT_GNU_HASH || |
| 433 tag == DT_STRTAB || |
| 434 tag == DT_SYMTAB || |
| 435 tag == DT_RELA || |
| 436 tag == DT_INIT || |
| 437 tag == DT_FINI || |
| 438 tag == DT_REL || |
| 439 tag == DT_JMPREL || |
| 440 tag == DT_INIT_ARRAY || |
| 441 tag == DT_FINI_ARRAY || |
| 442 tag == DT_ANDROID_REL|| |
| 443 tag == DT_ANDROID_RELA); |
| 444 |
| 445 if (is_adjustable && dynamic->d_un.d_ptr <= hole_start) { |
| 446 dynamic->d_un.d_ptr -= hole_size; |
| 447 VLOG(1) << "dynamic[" << i << "] " << dynamic->d_tag |
| 448 << " d_ptr adjusted to " << dynamic->d_un.d_ptr; |
| 449 } |
| 450 |
| 451 // DT_RELSZ or DT_RELASZ indicate the overall size of relocations. |
| 452 // Only one will be present. Adjust by hole size. |
| 453 if (tag == DT_RELSZ || tag == DT_RELASZ || tag == DT_ANDROID_RELSZ || tag ==
DT_ANDROID_RELASZ) { |
| 454 dynamic->d_un.d_val += hole_size; |
| 455 VLOG(1) << "dynamic[" << i << "] " << dynamic->d_tag |
| 456 << " d_val adjusted to " << dynamic->d_un.d_val; |
| 457 } |
| 458 |
| 459 // Ignore DT_RELCOUNT and DT_RELACOUNT: (1) nobody uses them and |
| 460 // technically (2) the relative relocation count is not changed. |
| 461 |
| 462 // DT_RELENT and DT_RELAENT don't change, ignore them as well. |
| 463 } |
| 464 |
| 465 void* section_data = &dynamics[0]; |
| 466 size_t bytes = dynamics.size() * sizeof(dynamics[0]); |
| 467 RewriteSectionData(dynamic_section, section_data, bytes); |
| 468 } |
| 469 |
| 470 // Resize a section. If the new size is larger than the current size, open |
| 471 // up a hole by increasing file offsets that come after the hole. If smaller |
| 472 // than the current size, remove the hole by decreasing those offsets. |
| 473 template <typename ELF> |
| 474 void ElfFile<ELF>::ResizeSection(Elf* elf, Elf_Scn* section, size_t new_size, |
| 475 typename ELF::Word new_sh_type, |
| 476 relocations_type_t relocations_type) { |
| 477 |
| 478 size_t string_index; |
| 479 elf_getshdrstrndx(elf, &string_index); |
| 480 auto section_header = ELF::getshdr(section); |
| 481 std::string name = elf_strptr(elf, string_index, section_header->sh_name); |
| 482 |
| 483 if (section_header->sh_size == new_size) { |
| 484 return; |
| 485 } |
| 486 |
| 487 // Require that the section size and the data size are the same. True |
| 488 // in practice for all sections we resize when packing or unpacking. |
| 489 Elf_Data* data = GetSectionData(section); |
| 490 CHECK(data->d_off == 0 && data->d_size == section_header->sh_size); |
| 491 |
| 492 // Require that the section is not zero-length (that is, has allocated |
| 493 // data that we can validly expand). |
| 494 CHECK(data->d_size && data->d_buf); |
| 495 |
| 496 const auto hole_start = section_header->sh_offset; |
| 497 const ssize_t hole_size = new_size - data->d_size; |
| 498 |
| 499 VLOG_IF(1, (hole_size > 0)) << "expand section (" << name << ") size: " << |
| 500 data->d_size << " -> " << (data->d_size + hole_size); |
| 501 VLOG_IF(1, (hole_size < 0)) << "shrink section (" << name << ") size: " << |
| 502 data->d_size << " -> " << (data->d_size + hole_size); |
| 503 |
| 504 // libelf overrides sh_entsize for known sh_types, so it does not matter what
we set |
| 505 // for SHT_REL/SHT_RELA. |
| 506 typename ELF::Xword new_entsize = |
| 507 (new_sh_type == SHT_ANDROID_REL || new_sh_type == SHT_ANDROID_RELA) ? 1 :
0; |
| 508 |
| 509 VLOG(1) << "Update section (" << name << ") entry size: " << |
| 510 section_header->sh_entsize << " -> " << new_entsize; |
| 511 |
| 512 // Resize the data and the section header. |
| 513 data->d_size += hole_size; |
| 514 section_header->sh_size += hole_size; |
| 515 section_header->sh_entsize = new_entsize; |
| 516 section_header->sh_type = new_sh_type; |
| 517 |
| 518 // Add the hole size to all offsets in the ELF file that are after the |
| 519 // start of the hole. If the hole size is positive we are expanding the |
| 520 // section to create a new hole; if negative, we are closing up a hole. |
| 521 |
| 522 // Start with the main ELF header. |
| 523 typename ELF::Ehdr* elf_header = ELF::getehdr(elf); |
| 524 AdjustElfHeaderForHole<ELF>(elf_header, hole_start, hole_size); |
| 525 |
| 526 // Adjust all section headers. |
| 527 AdjustSectionHeadersForHole<ELF>(elf, hole_start, hole_size); |
| 528 |
| 529 // Rewrite the program headers to either split or coalesce segments, |
| 530 // and adjust dynamic entries to match. |
| 531 RewriteProgramHeadersForHole<ELF>(elf, hole_start, hole_size); |
| 532 |
| 533 Elf_Scn* dynamic_section = GetDynamicSection<ELF>(elf); |
| 534 AdjustDynamicSectionForHole(dynamic_section, hole_start, hole_size, relocation
s_type); |
| 535 } |
| 536 |
| 537 // Find the first slot in a dynamics array with the given tag. The array |
| 538 // always ends with a free (unused) element, and which we exclude from the |
| 539 // search. Returns dynamics->size() if not found. |
| 540 template <typename ELF> |
| 541 static size_t FindDynamicEntry(typename ELF::Sword tag, |
| 542 std::vector<typename ELF::Dyn>* dynamics) { |
| 543 // Loop until the penultimate entry. We exclude the end sentinel. |
| 544 for (size_t i = 0; i < dynamics->size() - 1; ++i) { |
| 545 if (dynamics->at(i).d_tag == tag) { |
| 546 return i; |
| 547 } |
| 548 } |
| 549 |
| 550 // The tag was not found. |
| 551 return dynamics->size(); |
| 552 } |
| 553 |
| 554 // Replace dynamic entry. |
| 555 template <typename ELF> |
| 556 static void ReplaceDynamicEntry(typename ELF::Sword tag, |
| 557 const typename ELF::Dyn& dyn, |
| 558 std::vector<typename ELF::Dyn>* dynamics) { |
| 559 const size_t slot = FindDynamicEntry<ELF>(tag, dynamics); |
| 560 if (slot == dynamics->size()) { |
| 561 LOG(FATAL) << "Dynamic slot is not found for tag=" << tag; |
| 562 } |
| 563 |
| 564 // Replace this entry with the one supplied. |
| 565 dynamics->at(slot) = dyn; |
| 566 VLOG(1) << "dynamic[" << slot << "] overwritten with " << dyn.d_tag; |
| 567 } |
| 568 |
| 569 // Remove relative entries from dynamic relocations and write as packed |
| 570 // data into android packed relocations. |
| 571 template <typename ELF> |
| 572 bool ElfFile<ELF>::PackRelocations() { |
| 573 // Load the ELF file into libelf. |
| 574 if (!Load()) { |
| 575 LOG(ERROR) << "Failed to load as ELF"; |
| 576 return false; |
| 577 } |
| 578 |
| 579 // Retrieve the current dynamic relocations section data. |
| 580 Elf_Data* data = GetSectionData(relocations_section_); |
| 581 // we always pack rela, because packed format is pretty much the same |
| 582 std::vector<typename ELF::Rela> relocations; |
| 583 |
| 584 if (relocations_type_ == REL) { |
| 585 // Convert data to a vector of relocations. |
| 586 const typename ELF::Rel* relocations_base = reinterpret_cast<typename ELF::R
el*>(data->d_buf); |
| 587 ConvertRelArrayToRelaVector(relocations_base, |
| 588 data->d_size / sizeof(typename ELF::Rel), &relocations); |
| 589 LOG(INFO) << "Relocations : REL"; |
| 590 } else if (relocations_type_ == RELA) { |
| 591 // Convert data to a vector of relocations with addends. |
| 592 const typename ELF::Rela* relocations_base = reinterpret_cast<typename ELF::
Rela*>(data->d_buf); |
| 593 relocations = std::vector<typename ELF::Rela>( |
| 594 relocations_base, |
| 595 relocations_base + data->d_size / sizeof(relocations[0])); |
| 596 |
| 597 LOG(INFO) << "Relocations : RELA"; |
| 598 } else { |
| 599 NOTREACHED(); |
| 600 } |
| 601 |
| 602 return PackTypedRelocations(&relocations); |
| 603 } |
| 604 |
| 605 // Helper for PackRelocations(). Rel type is one of ELF::Rel or ELF::Rela. |
| 606 template <typename ELF> |
| 607 bool ElfFile<ELF>::PackTypedRelocations(std::vector<typename ELF::Rela>* relocat
ions) { |
| 608 typedef typename ELF::Rela Rela; |
| 609 |
| 610 // If no relocations then we have nothing packable. Perhaps |
| 611 // the shared object has already been packed? |
| 612 if (relocations->empty()) { |
| 613 LOG(ERROR) << "No relocations found (already packed?)"; |
| 614 return false; |
| 615 } |
| 616 |
| 617 const size_t rel_size = |
| 618 relocations_type_ == RELA ? sizeof(typename ELF::Rela) : sizeof(typename E
LF::Rel); |
| 619 const size_t initial_bytes = relocations->size() * rel_size; |
| 620 |
| 621 LOG(INFO) << "Unpacked : " << initial_bytes << " bytes"; |
| 622 std::vector<uint8_t> packed; |
| 623 RelocationPacker<ELF> packer; |
| 624 |
| 625 // Pack relocations: dry run to estimate memory savings. |
| 626 packer.PackRelocations(*relocations, &packed); |
| 627 const size_t packed_bytes_estimate = packed.size() * sizeof(packed[0]); |
| 628 LOG(INFO) << "Packed (no padding): " << packed_bytes_estimate << " byt
es"; |
| 629 |
| 630 if (packed.empty()) { |
| 631 LOG(INFO) << "Too few relocations to pack"; |
| 632 return false; |
| 633 } |
| 634 |
| 635 // Pre-calculate the size of the hole we will close up when we rewrite |
| 636 // dynamic relocations. We have to adjust relocation addresses to |
| 637 // account for this. |
| 638 typename ELF::Shdr* section_header = ELF::getshdr(relocations_section_); |
| 639 ssize_t hole_size = initial_bytes - packed_bytes_estimate; |
| 640 |
| 641 // hole_size needs to be page_aligned. |
| 642 hole_size -= hole_size % kPreserveAlignment; |
| 643 |
| 644 LOG(INFO) << "Compaction : " << hole_size << " bytes"; |
| 645 |
| 646 // Adjusting for alignment may have removed any packing benefit. |
| 647 if (hole_size == 0) { |
| 648 LOG(INFO) << "Too few relocations to pack after alignment"; |
| 649 return false; |
| 650 } |
| 651 |
| 652 if (hole_size <= 0) { |
| 653 LOG(INFO) << "Packing relocations saves no space"; |
| 654 return false; |
| 655 } |
| 656 |
| 657 size_t data_padding_bytes = is_padding_relocations_ ? |
| 658 initial_bytes - packed_bytes_estimate : |
| 659 initial_bytes - hole_size - packed_bytes_estimate; |
| 660 |
| 661 // pad data |
| 662 std::vector<uint8_t> padding(data_padding_bytes, 0); |
| 663 packed.insert(packed.end(), padding.begin(), padding.end()); |
| 664 |
| 665 const void* packed_data = &packed[0]; |
| 666 |
| 667 // Run a loopback self-test as a check that packing is lossless. |
| 668 std::vector<Rela> unpacked; |
| 669 packer.UnpackRelocations(packed, &unpacked); |
| 670 CHECK(unpacked.size() == relocations->size()); |
| 671 CHECK(!memcmp(&unpacked[0], |
| 672 &relocations->at(0), |
| 673 unpacked.size() * sizeof(unpacked[0]))); |
| 674 |
| 675 // Rewrite the current dynamic relocations section with packed one then shrink
it to size. |
| 676 const size_t bytes = packed.size() * sizeof(packed[0]); |
| 677 ResizeSection(elf_, relocations_section_, bytes, |
| 678 relocations_type_ == REL ? SHT_ANDROID_REL : SHT_ANDROID_RELA, relocations
_type_); |
| 679 RewriteSectionData(relocations_section_, packed_data, bytes); |
| 680 |
| 681 // TODO (dimitry): fix string table and replace .rel.dyn/plt with .android.rel
.dyn/plt |
| 682 |
| 683 // Rewrite .dynamic and rename relocation tags describing the packed android |
| 684 // relocations. |
| 685 Elf_Data* data = GetSectionData(dynamic_section_); |
| 686 const typename ELF::Dyn* dynamic_base = reinterpret_cast<typename ELF::Dyn*>(d
ata->d_buf); |
| 687 std::vector<typename ELF::Dyn> dynamics( |
| 688 dynamic_base, |
| 689 dynamic_base + data->d_size / sizeof(dynamics[0])); |
| 690 section_header = ELF::getshdr(relocations_section_); |
| 691 { |
| 692 typename ELF::Dyn dyn; |
| 693 dyn.d_tag = relocations_type_ == REL ? DT_ANDROID_REL : DT_ANDROID_RELA; |
| 694 dyn.d_un.d_ptr = section_header->sh_addr; |
| 695 ReplaceDynamicEntry<ELF>(relocations_type_ == REL ? DT_REL : DT_RELA, dyn, &
dynamics); |
| 696 } |
| 697 { |
| 698 typename ELF::Dyn dyn; |
| 699 dyn.d_tag = relocations_type_ == REL ? DT_ANDROID_RELSZ : DT_ANDROID_RELASZ; |
| 700 dyn.d_un.d_val = section_header->sh_size; |
| 701 ReplaceDynamicEntry<ELF>(relocations_type_ == REL ? DT_RELSZ : DT_RELASZ, dy
n, &dynamics); |
| 702 } |
| 703 |
| 704 const void* dynamics_data = &dynamics[0]; |
| 705 const size_t dynamics_bytes = dynamics.size() * sizeof(dynamics[0]); |
| 706 RewriteSectionData(dynamic_section_, dynamics_data, dynamics_bytes); |
| 707 |
| 708 Flush(); |
| 709 return true; |
| 710 } |
| 711 |
| 712 // Find packed relative relocations in the packed android relocations |
| 713 // section, unpack them, and rewrite the dynamic relocations section to |
| 714 // contain unpacked data. |
| 715 template <typename ELF> |
| 716 bool ElfFile<ELF>::UnpackRelocations() { |
| 717 // Load the ELF file into libelf. |
| 718 if (!Load()) { |
| 719 LOG(ERROR) << "Failed to load as ELF"; |
| 720 return false; |
| 721 } |
| 722 |
| 723 typename ELF::Shdr* section_header = ELF::getshdr(relocations_section_); |
| 724 // Retrieve the current packed android relocations section data. |
| 725 Elf_Data* data = GetSectionData(relocations_section_); |
| 726 |
| 727 // Convert data to a vector of bytes. |
| 728 const uint8_t* packed_base = reinterpret_cast<uint8_t*>(data->d_buf); |
| 729 std::vector<uint8_t> packed( |
| 730 packed_base, |
| 731 packed_base + data->d_size / sizeof(packed[0])); |
| 732 |
| 733 if ((section_header->sh_type == SHT_ANDROID_RELA || section_header->sh_type ==
SHT_ANDROID_REL) && |
| 734 packed.size() > 3 && |
| 735 packed[0] == 'A' && |
| 736 packed[1] == 'P' && |
| 737 (packed[2] == 'U' || packed[2] == 'S') && |
| 738 packed[3] == '2') { |
| 739 LOG(INFO) << "Relocations : " << (relocations_type_ == REL ? "REL" : "RELA
"); |
| 740 } else { |
| 741 LOG(ERROR) << "Packed relocations not found (not packed?)"; |
| 742 return false; |
| 743 } |
| 744 |
| 745 return UnpackTypedRelocations(packed); |
| 746 } |
| 747 |
| 748 // Helper for UnpackRelocations(). Rel type is one of ELF::Rel or ELF::Rela. |
| 749 template <typename ELF> |
| 750 bool ElfFile<ELF>::UnpackTypedRelocations(const std::vector<uint8_t>& packed) { |
| 751 // Unpack the data to re-materialize the relative relocations. |
| 752 const size_t packed_bytes = packed.size() * sizeof(packed[0]); |
| 753 LOG(INFO) << "Packed : " << packed_bytes << " bytes"; |
| 754 std::vector<typename ELF::Rela> unpacked_relocations; |
| 755 RelocationPacker<ELF> packer; |
| 756 packer.UnpackRelocations(packed, &unpacked_relocations); |
| 757 |
| 758 const size_t relocation_entry_size = |
| 759 relocations_type_ == REL ? sizeof(typename ELF::Rel) : sizeof(typename ELF
::Rela); |
| 760 const size_t unpacked_bytes = unpacked_relocations.size() * relocation_entry_s
ize; |
| 761 LOG(INFO) << "Unpacked : " << unpacked_bytes << " bytes"; |
| 762 |
| 763 // Retrieve the current dynamic relocations section data. |
| 764 Elf_Data* data = GetSectionData(relocations_section_); |
| 765 |
| 766 LOG(INFO) << "Relocations : " << unpacked_relocations.size() << " entries
"; |
| 767 |
| 768 // If we found the same number of null relocation entries in the dynamic |
| 769 // relocations section as we hold as unpacked relative relocations, then |
| 770 // this is a padded file. |
| 771 |
| 772 const bool is_padded = packed_bytes == unpacked_bytes; |
| 773 |
| 774 // Unless padded, pre-apply relative relocations to account for the |
| 775 // hole, and pre-adjust all relocation offsets accordingly. |
| 776 typename ELF::Shdr* section_header = ELF::getshdr(relocations_section_); |
| 777 |
| 778 if (!is_padded) { |
| 779 LOG(INFO) << "Expansion : " << unpacked_bytes - packed_bytes << " bytes"
; |
| 780 } |
| 781 |
| 782 // Rewrite the current dynamic relocations section with unpacked version of |
| 783 // relocations. |
| 784 const void* section_data = nullptr; |
| 785 std::vector<typename ELF::Rel> unpacked_rel_relocations; |
| 786 if (relocations_type_ == RELA) { |
| 787 section_data = &unpacked_relocations[0]; |
| 788 } else if (relocations_type_ == REL) { |
| 789 ConvertRelaVectorToRelVector(unpacked_relocations, &unpacked_rel_relocations
); |
| 790 section_data = &unpacked_rel_relocations[0]; |
| 791 } else { |
| 792 NOTREACHED(); |
| 793 } |
| 794 |
| 795 ResizeSection(elf_, relocations_section_, unpacked_bytes, |
| 796 relocations_type_ == REL ? SHT_REL : SHT_RELA, relocations_type_); |
| 797 RewriteSectionData(relocations_section_, section_data, unpacked_bytes); |
| 798 |
| 799 // Rewrite .dynamic to remove two tags describing packed android relocations. |
| 800 data = GetSectionData(dynamic_section_); |
| 801 const typename ELF::Dyn* dynamic_base = reinterpret_cast<typename ELF::Dyn*>(d
ata->d_buf); |
| 802 std::vector<typename ELF::Dyn> dynamics( |
| 803 dynamic_base, |
| 804 dynamic_base + data->d_size / sizeof(dynamics[0])); |
| 805 { |
| 806 typename ELF::Dyn dyn; |
| 807 dyn.d_tag = relocations_type_ == REL ? DT_REL : DT_RELA; |
| 808 dyn.d_un.d_ptr = section_header->sh_addr; |
| 809 ReplaceDynamicEntry<ELF>(relocations_type_ == REL ? DT_ANDROID_REL : DT_ANDR
OID_RELA, |
| 810 dyn, &dynamics); |
| 811 } |
| 812 |
| 813 { |
| 814 typename ELF::Dyn dyn; |
| 815 dyn.d_tag = relocations_type_ == REL ? DT_RELSZ : DT_RELASZ; |
| 816 dyn.d_un.d_val = section_header->sh_size; |
| 817 ReplaceDynamicEntry<ELF>(relocations_type_ == REL ? DT_ANDROID_RELSZ : DT_AN
DROID_RELASZ, |
| 818 dyn, &dynamics); |
| 819 } |
| 820 |
| 821 const void* dynamics_data = &dynamics[0]; |
| 822 const size_t dynamics_bytes = dynamics.size() * sizeof(dynamics[0]); |
| 823 RewriteSectionData(dynamic_section_, dynamics_data, dynamics_bytes); |
| 824 |
| 825 Flush(); |
| 826 return true; |
| 827 } |
| 828 |
| 829 // Flush rewritten shared object file data. |
| 830 template <typename ELF> |
| 831 void ElfFile<ELF>::Flush() { |
| 832 // Flag all ELF data held in memory as needing to be written back to the |
| 833 // file, and tell libelf that we have controlled the file layout. |
| 834 elf_flagelf(elf_, ELF_C_SET, ELF_F_DIRTY); |
| 835 elf_flagelf(elf_, ELF_C_SET, ELF_F_LAYOUT); |
| 836 |
| 837 // Write ELF data back to disk. |
| 838 const off_t file_bytes = elf_update(elf_, ELF_C_WRITE); |
| 839 if (file_bytes == -1) { |
| 840 LOG(ERROR) << "elf_update failed: " << elf_errmsg(elf_errno()); |
| 841 } |
| 842 |
| 843 CHECK(file_bytes > 0); |
| 844 VLOG(1) << "elf_update returned: " << file_bytes; |
| 845 |
| 846 // Clean up libelf, and truncate the output file to the number of bytes |
| 847 // written by elf_update(). |
| 848 elf_end(elf_); |
| 849 elf_ = NULL; |
| 850 const int truncate = ftruncate(fd_, file_bytes); |
| 851 CHECK(truncate == 0); |
| 852 } |
| 853 |
| 854 template <typename ELF> |
| 855 void ElfFile<ELF>::ConvertRelArrayToRelaVector(const typename ELF::Rel* rel_arra
y, |
| 856 size_t rel_array_size, |
| 857 std::vector<typename ELF::Rela>*
rela_vector) { |
| 858 for (size_t i = 0; i<rel_array_size; ++i) { |
| 859 typename ELF::Rela rela; |
| 860 rela.r_offset = rel_array[i].r_offset; |
| 861 rela.r_info = rel_array[i].r_info; |
| 862 rela.r_addend = 0; |
| 863 rela_vector->push_back(rela); |
| 864 } |
| 865 } |
| 866 |
| 867 template <typename ELF> |
| 868 void ElfFile<ELF>::ConvertRelaVectorToRelVector(const std::vector<typename ELF::
Rela>& rela_vector, |
| 869 std::vector<typename ELF::Rel>*
rel_vector) { |
| 870 for (auto rela : rela_vector) { |
| 871 typename ELF::Rel rel; |
| 872 rel.r_offset = rela.r_offset; |
| 873 rel.r_info = rela.r_info; |
| 874 CHECK(rela.r_addend == 0); |
| 875 rel_vector->push_back(rel); |
| 876 } |
| 877 } |
| 878 |
| 879 template class ElfFile<ELF32_traits>; |
| 880 template class ElfFile<ELF64_traits>; |
| 881 |
| 882 } // namespace relocation_packer |
OLD | NEW |