1 /*
2  * Copyright (C) 2017 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.h>
18 #include <stdint.h>
19 
20 #include <memory>
21 #include <string>
22 #include <utility>
23 
24 #include <7zCrc.h>
25 #include <Xz.h>
26 #include <XzCrc64.h>
27 
28 #include <unwindstack/DwarfError.h>
29 #include <unwindstack/DwarfSection.h>
30 #include <unwindstack/ElfInterface.h>
31 #include <unwindstack/Log.h>
32 #include <unwindstack/Regs.h>
33 
34 #include "DwarfDebugFrame.h"
35 #include "DwarfEhFrame.h"
36 #include "DwarfEhFrameWithHdr.h"
37 #include "MemoryBuffer.h"
38 #include "Symbols.h"
39 
40 namespace unwindstack {
41 
~ElfInterface()42 ElfInterface::~ElfInterface() {
43   for (auto symbol : symbols_) {
44     delete symbol;
45   }
46 }
47 
IsValidPc(uint64_t pc)48 bool ElfInterface::IsValidPc(uint64_t pc) {
49   if (!pt_loads_.empty()) {
50     for (auto& entry : pt_loads_) {
51       uint64_t start = entry.second.table_offset;
52       uint64_t end = start + entry.second.table_size;
53       if (pc >= start && pc < end) {
54         return true;
55       }
56     }
57     return false;
58   }
59 
60   // No PT_LOAD data, look for a fde for this pc in the section data.
61   if (debug_frame_ != nullptr && debug_frame_->GetFdeFromPc(pc) != nullptr) {
62     return true;
63   }
64 
65   if (eh_frame_ != nullptr && eh_frame_->GetFdeFromPc(pc) != nullptr) {
66     return true;
67   }
68 
69   return false;
70 }
71 
CreateGnuDebugdataMemory()72 Memory* ElfInterface::CreateGnuDebugdataMemory() {
73   if (gnu_debugdata_offset_ == 0 || gnu_debugdata_size_ == 0) {
74     return nullptr;
75   }
76 
77   // TODO: Only call these initialization functions once.
78   CrcGenerateTable();
79   Crc64GenerateTable();
80 
81   // Verify the request is not larger than the max size_t value.
82   if (gnu_debugdata_size_ > SIZE_MAX) {
83     return nullptr;
84   }
85   size_t initial_buffer_size;
86   if (__builtin_mul_overflow(5, gnu_debugdata_size_, &initial_buffer_size)) {
87     return nullptr;
88   }
89 
90   size_t buffer_increment;
91   if (__builtin_mul_overflow(2, gnu_debugdata_size_, &buffer_increment)) {
92     return nullptr;
93   }
94 
95   std::unique_ptr<uint8_t[]> src(new (std::nothrow) uint8_t[gnu_debugdata_size_]);
96   if (src.get() == nullptr) {
97     return nullptr;
98   }
99 
100   std::unique_ptr<MemoryBuffer> dst(new MemoryBuffer);
101   if (!dst->Resize(initial_buffer_size)) {
102     return nullptr;
103   }
104 
105   if (!memory_->ReadFully(gnu_debugdata_offset_, src.get(), gnu_debugdata_size_)) {
106     return nullptr;
107   }
108 
109   ISzAlloc alloc;
110   CXzUnpacker state;
111   alloc.Alloc = [](ISzAllocPtr, size_t size) { return malloc(size); };
112   alloc.Free = [](ISzAllocPtr, void* ptr) { return free(ptr); };
113   XzUnpacker_Construct(&state, &alloc);
114 
115   int return_val;
116   size_t src_offset = 0;
117   size_t dst_offset = 0;
118   ECoderStatus status;
119   do {
120     size_t src_remaining = gnu_debugdata_size_ - src_offset;
121     size_t dst_remaining = dst->Size() - dst_offset;
122     if (dst_remaining < buffer_increment) {
123       size_t new_size;
124       if (__builtin_add_overflow(dst->Size(), buffer_increment, &new_size) ||
125           !dst->Resize(new_size)) {
126         XzUnpacker_Free(&state);
127         return nullptr;
128       }
129       dst_remaining += buffer_increment;
130     }
131     return_val = XzUnpacker_Code(&state, dst->GetPtr(dst_offset), &dst_remaining, &src[src_offset],
132                                  &src_remaining, true, CODER_FINISH_ANY, &status);
133     src_offset += src_remaining;
134     dst_offset += dst_remaining;
135   } while (return_val == SZ_OK && status == CODER_STATUS_NOT_FINISHED);
136   XzUnpacker_Free(&state);
137   if (return_val != SZ_OK || !XzUnpacker_IsStreamWasFinished(&state)) {
138     return nullptr;
139   }
140 
141   // Shrink back down to the exact size.
142   if (!dst->Resize(dst_offset)) {
143     return nullptr;
144   }
145 
146   return dst.release();
147 }
148 
149 template <typename AddressType>
InitHeadersWithTemplate()150 void ElfInterface::InitHeadersWithTemplate() {
151   if (eh_frame_hdr_offset_ != 0) {
152     DwarfEhFrameWithHdr<AddressType>* eh_frame_hdr = new DwarfEhFrameWithHdr<AddressType>(memory_);
153     eh_frame_.reset(eh_frame_hdr);
154     if (!eh_frame_hdr->EhFrameInit(eh_frame_offset_, eh_frame_size_, eh_frame_section_bias_) ||
155         !eh_frame_->Init(eh_frame_hdr_offset_, eh_frame_hdr_size_, eh_frame_hdr_section_bias_)) {
156       eh_frame_.reset(nullptr);
157     }
158   }
159 
160   if (eh_frame_.get() == nullptr && eh_frame_offset_ != 0) {
161     // If there is an eh_frame section without an eh_frame_hdr section,
162     // or using the frame hdr object failed to init.
163     eh_frame_.reset(new DwarfEhFrame<AddressType>(memory_));
164     if (!eh_frame_->Init(eh_frame_offset_, eh_frame_size_, eh_frame_section_bias_)) {
165       eh_frame_.reset(nullptr);
166     }
167   }
168 
169   if (eh_frame_.get() == nullptr) {
170     eh_frame_hdr_offset_ = 0;
171     eh_frame_hdr_section_bias_ = 0;
172     eh_frame_hdr_size_ = static_cast<uint64_t>(-1);
173     eh_frame_offset_ = 0;
174     eh_frame_section_bias_ = 0;
175     eh_frame_size_ = static_cast<uint64_t>(-1);
176   }
177 
178   if (debug_frame_offset_ != 0) {
179     debug_frame_.reset(new DwarfDebugFrame<AddressType>(memory_));
180     if (!debug_frame_->Init(debug_frame_offset_, debug_frame_size_, debug_frame_section_bias_)) {
181       debug_frame_.reset(nullptr);
182       debug_frame_offset_ = 0;
183       debug_frame_size_ = static_cast<uint64_t>(-1);
184     }
185   }
186 }
187 
188 template <typename EhdrType, typename PhdrType, typename ShdrType>
ReadAllHeaders(int64_t * load_bias)189 bool ElfInterface::ReadAllHeaders(int64_t* load_bias) {
190   EhdrType ehdr;
191   if (!memory_->ReadFully(0, &ehdr, sizeof(ehdr))) {
192     last_error_.code = ERROR_MEMORY_INVALID;
193     last_error_.address = 0;
194     return false;
195   }
196 
197   // If we have enough information that this is an elf file, then allow
198   // malformed program and section headers.
199   ReadProgramHeaders<EhdrType, PhdrType>(ehdr, load_bias);
200   ReadSectionHeaders<EhdrType, ShdrType>(ehdr);
201   return true;
202 }
203 
204 template <typename EhdrType, typename PhdrType>
GetLoadBias(Memory * memory)205 int64_t ElfInterface::GetLoadBias(Memory* memory) {
206   EhdrType ehdr;
207   if (!memory->ReadFully(0, &ehdr, sizeof(ehdr))) {
208     return false;
209   }
210 
211   uint64_t offset = ehdr.e_phoff;
212   for (size_t i = 0; i < ehdr.e_phnum; i++, offset += ehdr.e_phentsize) {
213     PhdrType phdr;
214     if (!memory->ReadFully(offset, &phdr, sizeof(phdr))) {
215       return 0;
216     }
217 
218     // Find the first executable load when looking for the load bias.
219     if (phdr.p_type == PT_LOAD && (phdr.p_flags & PF_X)) {
220       return static_cast<uint64_t>(phdr.p_vaddr) - phdr.p_offset;
221     }
222   }
223   return 0;
224 }
225 
226 template <typename EhdrType, typename PhdrType>
ReadProgramHeaders(const EhdrType & ehdr,int64_t * load_bias)227 void ElfInterface::ReadProgramHeaders(const EhdrType& ehdr, int64_t* load_bias) {
228   uint64_t offset = ehdr.e_phoff;
229   bool first_exec_load_header = true;
230   for (size_t i = 0; i < ehdr.e_phnum; i++, offset += ehdr.e_phentsize) {
231     PhdrType phdr;
232     if (!memory_->ReadFully(offset, &phdr, sizeof(phdr))) {
233       return;
234     }
235 
236     switch (phdr.p_type) {
237     case PT_LOAD:
238     {
239       if ((phdr.p_flags & PF_X) == 0) {
240         continue;
241       }
242 
243       pt_loads_[phdr.p_offset] = LoadInfo{phdr.p_offset, phdr.p_vaddr,
244                                           static_cast<size_t>(phdr.p_memsz)};
245       // Only set the load bias from the first executable load header.
246       if (first_exec_load_header) {
247         *load_bias = static_cast<uint64_t>(phdr.p_vaddr) - phdr.p_offset;
248       }
249       first_exec_load_header = false;
250       break;
251     }
252 
253     case PT_GNU_EH_FRAME:
254       // This is really the pointer to the .eh_frame_hdr section.
255       eh_frame_hdr_offset_ = phdr.p_offset;
256       eh_frame_hdr_section_bias_ = static_cast<uint64_t>(phdr.p_vaddr) - phdr.p_offset;
257       eh_frame_hdr_size_ = phdr.p_memsz;
258       break;
259 
260     case PT_DYNAMIC:
261       dynamic_offset_ = phdr.p_offset;
262       dynamic_vaddr_start_ = phdr.p_vaddr;
263       if (__builtin_add_overflow(dynamic_vaddr_start_, phdr.p_memsz, &dynamic_vaddr_end_)) {
264         dynamic_offset_ = 0;
265         dynamic_vaddr_start_ = 0;
266         dynamic_vaddr_end_ = 0;
267       }
268       break;
269 
270     default:
271       HandleUnknownType(phdr.p_type, phdr.p_offset, phdr.p_filesz);
272       break;
273     }
274   }
275 }
276 
277 template <typename NhdrType>
ReadBuildID()278 std::string ElfInterface::ReadBuildID() {
279   // Ensure there is no overflow in any of the calulations below.
280   uint64_t tmp;
281   if (__builtin_add_overflow(gnu_build_id_offset_, gnu_build_id_size_, &tmp)) {
282     return "";
283   }
284 
285   uint64_t offset = 0;
286   while (offset < gnu_build_id_size_) {
287     if (gnu_build_id_size_ - offset < sizeof(NhdrType)) {
288       return "";
289     }
290     NhdrType hdr;
291     if (!memory_->ReadFully(gnu_build_id_offset_ + offset, &hdr, sizeof(hdr))) {
292       return "";
293     }
294     offset += sizeof(hdr);
295 
296     if (gnu_build_id_size_ - offset < hdr.n_namesz) {
297       return "";
298     }
299     if (hdr.n_namesz > 0) {
300       std::string name(hdr.n_namesz, '\0');
301       if (!memory_->ReadFully(gnu_build_id_offset_ + offset, &(name[0]), hdr.n_namesz)) {
302         return "";
303       }
304 
305       // Trim trailing \0 as GNU is stored as a C string in the ELF file.
306       if (name.back() == '\0')
307         name.resize(name.size() - 1);
308 
309       // Align hdr.n_namesz to next power multiple of 4. See man 5 elf.
310       offset += (hdr.n_namesz + 3) & ~3;
311 
312       if (name == "GNU" && hdr.n_type == NT_GNU_BUILD_ID) {
313         if (gnu_build_id_size_ - offset < hdr.n_descsz || hdr.n_descsz == 0) {
314           return "";
315         }
316         std::string build_id(hdr.n_descsz, '\0');
317         if (memory_->ReadFully(gnu_build_id_offset_ + offset, &build_id[0], hdr.n_descsz)) {
318           return build_id;
319         }
320         return "";
321       }
322     }
323     // Align hdr.n_descsz to next power multiple of 4. See man 5 elf.
324     offset += (hdr.n_descsz + 3) & ~3;
325   }
326   return "";
327 }
328 
329 template <typename EhdrType, typename ShdrType>
ReadSectionHeaders(const EhdrType & ehdr)330 void ElfInterface::ReadSectionHeaders(const EhdrType& ehdr) {
331   uint64_t offset = ehdr.e_shoff;
332   uint64_t sec_offset = 0;
333   uint64_t sec_size = 0;
334 
335   // Get the location of the section header names.
336   // If something is malformed in the header table data, we aren't going
337   // to terminate, we'll simply ignore this part.
338   ShdrType shdr;
339   if (ehdr.e_shstrndx < ehdr.e_shnum) {
340     uint64_t sh_offset = offset + ehdr.e_shstrndx * ehdr.e_shentsize;
341     if (memory_->ReadFully(sh_offset, &shdr, sizeof(shdr))) {
342       sec_offset = shdr.sh_offset;
343       sec_size = shdr.sh_size;
344     }
345   }
346 
347   // Skip the first header, it's always going to be NULL.
348   offset += ehdr.e_shentsize;
349   for (size_t i = 1; i < ehdr.e_shnum; i++, offset += ehdr.e_shentsize) {
350     if (!memory_->ReadFully(offset, &shdr, sizeof(shdr))) {
351       return;
352     }
353 
354     if (shdr.sh_type == SHT_SYMTAB || shdr.sh_type == SHT_DYNSYM) {
355       // Need to go get the information about the section that contains
356       // the string terminated names.
357       ShdrType str_shdr;
358       if (shdr.sh_link >= ehdr.e_shnum) {
359         continue;
360       }
361       uint64_t str_offset = ehdr.e_shoff + shdr.sh_link * ehdr.e_shentsize;
362       if (!memory_->ReadFully(str_offset, &str_shdr, sizeof(str_shdr))) {
363         continue;
364       }
365       if (str_shdr.sh_type != SHT_STRTAB) {
366         continue;
367       }
368       symbols_.push_back(new Symbols(shdr.sh_offset, shdr.sh_size, shdr.sh_entsize,
369                                      str_shdr.sh_offset, str_shdr.sh_size));
370     } else if (shdr.sh_type == SHT_PROGBITS && sec_size != 0) {
371       // Look for the .debug_frame and .gnu_debugdata.
372       if (shdr.sh_name < sec_size) {
373         std::string name;
374         if (memory_->ReadString(sec_offset + shdr.sh_name, &name, sec_size - shdr.sh_name)) {
375           if (name == ".debug_frame") {
376             debug_frame_offset_ = shdr.sh_offset;
377             debug_frame_size_ = shdr.sh_size;
378             debug_frame_section_bias_ = static_cast<uint64_t>(shdr.sh_addr) - shdr.sh_offset;
379           } else if (name == ".gnu_debugdata") {
380             gnu_debugdata_offset_ = shdr.sh_offset;
381             gnu_debugdata_size_ = shdr.sh_size;
382           } else if (name == ".eh_frame") {
383             eh_frame_offset_ = shdr.sh_offset;
384             eh_frame_section_bias_ = static_cast<uint64_t>(shdr.sh_addr) - shdr.sh_offset;
385             eh_frame_size_ = shdr.sh_size;
386           } else if (eh_frame_hdr_offset_ == 0 && name == ".eh_frame_hdr") {
387             eh_frame_hdr_offset_ = shdr.sh_offset;
388             eh_frame_hdr_section_bias_ = static_cast<uint64_t>(shdr.sh_addr) - shdr.sh_offset;
389             eh_frame_hdr_size_ = shdr.sh_size;
390           } else if (name == ".data") {
391             data_offset_ = shdr.sh_offset;
392             data_vaddr_start_ = shdr.sh_addr;
393             if (__builtin_add_overflow(data_vaddr_start_, shdr.sh_size, &data_vaddr_end_)) {
394               data_offset_ = 0;
395               data_vaddr_start_ = 0;
396               data_vaddr_end_ = 0;
397             }
398           }
399         }
400       }
401     } else if (shdr.sh_type == SHT_STRTAB) {
402       // In order to read soname, keep track of address to offset mapping.
403       strtabs_.push_back(std::make_pair<uint64_t, uint64_t>(static_cast<uint64_t>(shdr.sh_addr),
404                                                             static_cast<uint64_t>(shdr.sh_offset)));
405     } else if (shdr.sh_type == SHT_NOTE) {
406       if (shdr.sh_name < sec_size) {
407         std::string name;
408         if (memory_->ReadString(sec_offset + shdr.sh_name, &name, sec_size - shdr.sh_name) &&
409             name == ".note.gnu.build-id") {
410           gnu_build_id_offset_ = shdr.sh_offset;
411           gnu_build_id_size_ = shdr.sh_size;
412         }
413       }
414     }
415   }
416 }
417 
418 template <typename DynType>
GetSonameWithTemplate()419 std::string ElfInterface::GetSonameWithTemplate() {
420   if (soname_type_ == SONAME_INVALID) {
421     return "";
422   }
423   if (soname_type_ == SONAME_VALID) {
424     return soname_;
425   }
426 
427   soname_type_ = SONAME_INVALID;
428 
429   uint64_t soname_offset = 0;
430   uint64_t strtab_addr = 0;
431   uint64_t strtab_size = 0;
432 
433   // Find the soname location from the dynamic headers section.
434   DynType dyn;
435   uint64_t offset = dynamic_offset_;
436   uint64_t max_offset = offset + dynamic_vaddr_end_ - dynamic_vaddr_start_;
437   for (uint64_t offset = dynamic_offset_; offset < max_offset; offset += sizeof(DynType)) {
438     if (!memory_->ReadFully(offset, &dyn, sizeof(dyn))) {
439       last_error_.code = ERROR_MEMORY_INVALID;
440       last_error_.address = offset;
441       return "";
442     }
443 
444     if (dyn.d_tag == DT_STRTAB) {
445       strtab_addr = dyn.d_un.d_ptr;
446     } else if (dyn.d_tag == DT_STRSZ) {
447       strtab_size = dyn.d_un.d_val;
448     } else if (dyn.d_tag == DT_SONAME) {
449       soname_offset = dyn.d_un.d_val;
450     } else if (dyn.d_tag == DT_NULL) {
451       break;
452     }
453   }
454 
455   // Need to map the strtab address to the real offset.
456   for (const auto& entry : strtabs_) {
457     if (entry.first == strtab_addr) {
458       soname_offset = entry.second + soname_offset;
459       uint64_t soname_max = entry.second + strtab_size;
460       if (soname_offset >= soname_max) {
461         return "";
462       }
463       if (!memory_->ReadString(soname_offset, &soname_, soname_max - soname_offset)) {
464         return "";
465       }
466       soname_type_ = SONAME_VALID;
467       return soname_;
468     }
469   }
470   return "";
471 }
472 
473 template <typename SymType>
GetFunctionNameWithTemplate(uint64_t addr,std::string * name,uint64_t * func_offset)474 bool ElfInterface::GetFunctionNameWithTemplate(uint64_t addr, std::string* name,
475                                                uint64_t* func_offset) {
476   if (symbols_.empty()) {
477     return false;
478   }
479 
480   for (const auto symbol : symbols_) {
481     if (symbol->GetName<SymType>(addr, memory_, name, func_offset)) {
482       return true;
483     }
484   }
485   return false;
486 }
487 
488 template <typename SymType>
GetGlobalVariableWithTemplate(const std::string & name,uint64_t * memory_address)489 bool ElfInterface::GetGlobalVariableWithTemplate(const std::string& name, uint64_t* memory_address) {
490   if (symbols_.empty()) {
491     return false;
492   }
493 
494   for (const auto symbol : symbols_) {
495     if (symbol->GetGlobal<SymType>(memory_, name, memory_address)) {
496       return true;
497     }
498   }
499   return false;
500 }
501 
Step(uint64_t pc,Regs * regs,Memory * process_memory,bool * finished)502 bool ElfInterface::Step(uint64_t pc, Regs* regs, Memory* process_memory, bool* finished) {
503   last_error_.code = ERROR_NONE;
504   last_error_.address = 0;
505 
506   // Try the debug_frame first since it contains the most specific unwind
507   // information.
508   DwarfSection* debug_frame = debug_frame_.get();
509   if (debug_frame != nullptr && debug_frame->Step(pc, regs, process_memory, finished)) {
510     return true;
511   }
512 
513   // Try the eh_frame next.
514   DwarfSection* eh_frame = eh_frame_.get();
515   if (eh_frame != nullptr && eh_frame->Step(pc, regs, process_memory, finished)) {
516     return true;
517   }
518 
519   if (gnu_debugdata_interface_ != nullptr &&
520       gnu_debugdata_interface_->Step(pc, regs, process_memory, finished)) {
521     return true;
522   }
523 
524   // Set the error code based on the first error encountered.
525   DwarfSection* section = nullptr;
526   if (debug_frame_ != nullptr) {
527     section = debug_frame_.get();
528   } else if (eh_frame_ != nullptr) {
529     section = eh_frame_.get();
530   } else if (gnu_debugdata_interface_ != nullptr) {
531     last_error_ = gnu_debugdata_interface_->last_error();
532     return false;
533   } else {
534     return false;
535   }
536 
537   // Convert the DWARF ERROR to an external error.
538   DwarfErrorCode code = section->LastErrorCode();
539   switch (code) {
540     case DWARF_ERROR_NONE:
541       last_error_.code = ERROR_NONE;
542       break;
543 
544     case DWARF_ERROR_MEMORY_INVALID:
545       last_error_.code = ERROR_MEMORY_INVALID;
546       last_error_.address = section->LastErrorAddress();
547       break;
548 
549     case DWARF_ERROR_ILLEGAL_VALUE:
550     case DWARF_ERROR_ILLEGAL_STATE:
551     case DWARF_ERROR_STACK_INDEX_NOT_VALID:
552     case DWARF_ERROR_TOO_MANY_ITERATIONS:
553     case DWARF_ERROR_CFA_NOT_DEFINED:
554     case DWARF_ERROR_NO_FDES:
555       last_error_.code = ERROR_UNWIND_INFO;
556       break;
557 
558     case DWARF_ERROR_NOT_IMPLEMENTED:
559     case DWARF_ERROR_UNSUPPORTED_VERSION:
560       last_error_.code = ERROR_UNSUPPORTED;
561       break;
562   }
563   return false;
564 }
565 
566 // This is an estimation of the size of the elf file using the location
567 // of the section headers and size. This assumes that the section headers
568 // are at the end of the elf file. If the elf has a load bias, the size
569 // will be too large, but this is acceptable.
570 template <typename EhdrType>
GetMaxSizeWithTemplate(Memory * memory,uint64_t * size)571 void ElfInterface::GetMaxSizeWithTemplate(Memory* memory, uint64_t* size) {
572   EhdrType ehdr;
573   if (!memory->ReadFully(0, &ehdr, sizeof(ehdr))) {
574     return;
575   }
576   if (ehdr.e_shnum == 0) {
577     return;
578   }
579   *size = ehdr.e_shoff + ehdr.e_shentsize * ehdr.e_shnum;
580 }
581 
582 template <typename EhdrType, typename ShdrType>
GetBuildIDInfo(Memory * memory,uint64_t * build_id_offset,uint64_t * build_id_size)583 bool GetBuildIDInfo(Memory* memory, uint64_t* build_id_offset, uint64_t* build_id_size) {
584   EhdrType ehdr;
585   if (!memory->ReadFully(0, &ehdr, sizeof(ehdr))) {
586     return false;
587   }
588 
589   uint64_t offset = ehdr.e_shoff;
590   uint64_t sec_offset;
591   uint64_t sec_size;
592   ShdrType shdr;
593   if (ehdr.e_shstrndx >= ehdr.e_shnum) {
594     return false;
595   }
596 
597   uint64_t sh_offset = offset + ehdr.e_shstrndx * ehdr.e_shentsize;
598   if (!memory->ReadFully(sh_offset, &shdr, sizeof(shdr))) {
599     return false;
600   }
601   sec_offset = shdr.sh_offset;
602   sec_size = shdr.sh_size;
603 
604   // Skip the first header, it's always going to be NULL.
605   offset += ehdr.e_shentsize;
606   for (size_t i = 1; i < ehdr.e_shnum; i++, offset += ehdr.e_shentsize) {
607     if (!memory->ReadFully(offset, &shdr, sizeof(shdr))) {
608       return false;
609     }
610     std::string name;
611     if (shdr.sh_type == SHT_NOTE && shdr.sh_name < sec_size &&
612         memory->ReadString(sec_offset + shdr.sh_name, &name, sec_size - shdr.sh_name) &&
613         name == ".note.gnu.build-id") {
614       *build_id_offset = shdr.sh_offset;
615       *build_id_size = shdr.sh_size;
616       return true;
617     }
618   }
619 
620   return false;
621 }
622 
623 template <typename EhdrType, typename ShdrType, typename NhdrType>
ReadBuildIDFromMemory(Memory * memory)624 std::string ElfInterface::ReadBuildIDFromMemory(Memory* memory) {
625   uint64_t note_offset;
626   uint64_t note_size;
627   if (!GetBuildIDInfo<EhdrType, ShdrType>(memory, &note_offset, &note_size)) {
628     return "";
629   }
630 
631   // Ensure there is no overflow in any of the calculations below.
632   uint64_t tmp;
633   if (__builtin_add_overflow(note_offset, note_size, &tmp)) {
634     return "";
635   }
636 
637   uint64_t offset = 0;
638   while (offset < note_size) {
639     if (note_size - offset < sizeof(NhdrType)) {
640       return "";
641     }
642     NhdrType hdr;
643     if (!memory->ReadFully(note_offset + offset, &hdr, sizeof(hdr))) {
644       return "";
645     }
646     offset += sizeof(hdr);
647 
648     if (note_size - offset < hdr.n_namesz) {
649       return "";
650     }
651     if (hdr.n_namesz > 0) {
652       std::string name(hdr.n_namesz, '\0');
653       if (!memory->ReadFully(note_offset + offset, &(name[0]), hdr.n_namesz)) {
654         return "";
655       }
656 
657       // Trim trailing \0 as GNU is stored as a C string in the ELF file.
658       if (name.back() == '\0') name.resize(name.size() - 1);
659 
660       // Align hdr.n_namesz to next power multiple of 4. See man 5 elf.
661       offset += (hdr.n_namesz + 3) & ~3;
662 
663       if (name == "GNU" && hdr.n_type == NT_GNU_BUILD_ID) {
664         if (note_size - offset < hdr.n_descsz || hdr.n_descsz == 0) {
665           return "";
666         }
667         std::string build_id(hdr.n_descsz, '\0');
668         if (memory->ReadFully(note_offset + offset, &build_id[0], hdr.n_descsz)) {
669           return build_id;
670         }
671         return "";
672       }
673     }
674     // Align hdr.n_descsz to next power multiple of 4. See man 5 elf.
675     offset += (hdr.n_descsz + 3) & ~3;
676   }
677   return "";
678 }
679 
680 // Instantiate all of the needed template functions.
681 template void ElfInterface::InitHeadersWithTemplate<uint32_t>();
682 template void ElfInterface::InitHeadersWithTemplate<uint64_t>();
683 
684 template bool ElfInterface::ReadAllHeaders<Elf32_Ehdr, Elf32_Phdr, Elf32_Shdr>(int64_t*);
685 template bool ElfInterface::ReadAllHeaders<Elf64_Ehdr, Elf64_Phdr, Elf64_Shdr>(int64_t*);
686 
687 template void ElfInterface::ReadProgramHeaders<Elf32_Ehdr, Elf32_Phdr>(const Elf32_Ehdr&, int64_t*);
688 template void ElfInterface::ReadProgramHeaders<Elf64_Ehdr, Elf64_Phdr>(const Elf64_Ehdr&, int64_t*);
689 
690 template void ElfInterface::ReadSectionHeaders<Elf32_Ehdr, Elf32_Shdr>(const Elf32_Ehdr&);
691 template void ElfInterface::ReadSectionHeaders<Elf64_Ehdr, Elf64_Shdr>(const Elf64_Ehdr&);
692 
693 template std::string ElfInterface::ReadBuildID<Elf32_Nhdr>();
694 template std::string ElfInterface::ReadBuildID<Elf64_Nhdr>();
695 
696 template std::string ElfInterface::GetSonameWithTemplate<Elf32_Dyn>();
697 template std::string ElfInterface::GetSonameWithTemplate<Elf64_Dyn>();
698 
699 template bool ElfInterface::GetFunctionNameWithTemplate<Elf32_Sym>(uint64_t, std::string*,
700                                                                    uint64_t*);
701 template bool ElfInterface::GetFunctionNameWithTemplate<Elf64_Sym>(uint64_t, std::string*,
702                                                                    uint64_t*);
703 
704 template bool ElfInterface::GetGlobalVariableWithTemplate<Elf32_Sym>(const std::string&, uint64_t*);
705 template bool ElfInterface::GetGlobalVariableWithTemplate<Elf64_Sym>(const std::string&, uint64_t*);
706 
707 template void ElfInterface::GetMaxSizeWithTemplate<Elf32_Ehdr>(Memory*, uint64_t*);
708 template void ElfInterface::GetMaxSizeWithTemplate<Elf64_Ehdr>(Memory*, uint64_t*);
709 
710 template int64_t ElfInterface::GetLoadBias<Elf32_Ehdr, Elf32_Phdr>(Memory*);
711 template int64_t ElfInterface::GetLoadBias<Elf64_Ehdr, Elf64_Phdr>(Memory*);
712 
713 template std::string ElfInterface::ReadBuildIDFromMemory<Elf32_Ehdr, Elf32_Shdr, Elf32_Nhdr>(
714     Memory*);
715 template std::string ElfInterface::ReadBuildIDFromMemory<Elf64_Ehdr, Elf64_Shdr, Elf64_Nhdr>(
716     Memory*);
717 
718 }  // namespace unwindstack
719