• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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)) {
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) &&
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       if (soname_offset >= entry.second + strtab_size) {
460         return "";
461       }
462       if (!memory_->ReadString(soname_offset, &soname_)) {
463         return "";
464       }
465       soname_type_ = SONAME_VALID;
466       return soname_;
467     }
468   }
469   return "";
470 }
471 
472 template <typename SymType>
GetFunctionNameWithTemplate(uint64_t addr,std::string * name,uint64_t * func_offset)473 bool ElfInterface::GetFunctionNameWithTemplate(uint64_t addr, std::string* name,
474                                                uint64_t* func_offset) {
475   if (symbols_.empty()) {
476     return false;
477   }
478 
479   for (const auto symbol : symbols_) {
480     if (symbol->GetName<SymType>(addr, memory_, name, func_offset)) {
481       return true;
482     }
483   }
484   return false;
485 }
486 
487 template <typename SymType>
GetGlobalVariableWithTemplate(const std::string & name,uint64_t * memory_address)488 bool ElfInterface::GetGlobalVariableWithTemplate(const std::string& name, uint64_t* memory_address) {
489   if (symbols_.empty()) {
490     return false;
491   }
492 
493   for (const auto symbol : symbols_) {
494     if (symbol->GetGlobal<SymType>(memory_, name, memory_address)) {
495       return true;
496     }
497   }
498   return false;
499 }
500 
Step(uint64_t pc,Regs * regs,Memory * process_memory,bool * finished)501 bool ElfInterface::Step(uint64_t pc, Regs* regs, Memory* process_memory, bool* finished) {
502   last_error_.code = ERROR_NONE;
503   last_error_.address = 0;
504 
505   // Try the debug_frame first since it contains the most specific unwind
506   // information.
507   DwarfSection* debug_frame = debug_frame_.get();
508   if (debug_frame != nullptr && debug_frame->Step(pc, regs, process_memory, finished)) {
509     return true;
510   }
511 
512   // Try the eh_frame next.
513   DwarfSection* eh_frame = eh_frame_.get();
514   if (eh_frame != nullptr && eh_frame->Step(pc, regs, process_memory, finished)) {
515     return true;
516   }
517 
518   if (gnu_debugdata_interface_ != nullptr &&
519       gnu_debugdata_interface_->Step(pc, regs, process_memory, finished)) {
520     return true;
521   }
522 
523   // Set the error code based on the first error encountered.
524   DwarfSection* section = nullptr;
525   if (debug_frame_ != nullptr) {
526     section = debug_frame_.get();
527   } else if (eh_frame_ != nullptr) {
528     section = eh_frame_.get();
529   } else if (gnu_debugdata_interface_ != nullptr) {
530     last_error_ = gnu_debugdata_interface_->last_error();
531     return false;
532   } else {
533     return false;
534   }
535 
536   // Convert the DWARF ERROR to an external error.
537   DwarfErrorCode code = section->LastErrorCode();
538   switch (code) {
539     case DWARF_ERROR_NONE:
540       last_error_.code = ERROR_NONE;
541       break;
542 
543     case DWARF_ERROR_MEMORY_INVALID:
544       last_error_.code = ERROR_MEMORY_INVALID;
545       last_error_.address = section->LastErrorAddress();
546       break;
547 
548     case DWARF_ERROR_ILLEGAL_VALUE:
549     case DWARF_ERROR_ILLEGAL_STATE:
550     case DWARF_ERROR_STACK_INDEX_NOT_VALID:
551     case DWARF_ERROR_TOO_MANY_ITERATIONS:
552     case DWARF_ERROR_CFA_NOT_DEFINED:
553     case DWARF_ERROR_NO_FDES:
554       last_error_.code = ERROR_UNWIND_INFO;
555       break;
556 
557     case DWARF_ERROR_NOT_IMPLEMENTED:
558     case DWARF_ERROR_UNSUPPORTED_VERSION:
559       last_error_.code = ERROR_UNSUPPORTED;
560       break;
561   }
562   return false;
563 }
564 
565 // This is an estimation of the size of the elf file using the location
566 // of the section headers and size. This assumes that the section headers
567 // are at the end of the elf file. If the elf has a load bias, the size
568 // will be too large, but this is acceptable.
569 template <typename EhdrType>
GetMaxSizeWithTemplate(Memory * memory,uint64_t * size)570 void ElfInterface::GetMaxSizeWithTemplate(Memory* memory, uint64_t* size) {
571   EhdrType ehdr;
572   if (!memory->ReadFully(0, &ehdr, sizeof(ehdr))) {
573     return;
574   }
575   if (ehdr.e_shnum == 0) {
576     return;
577   }
578   *size = ehdr.e_shoff + ehdr.e_shentsize * ehdr.e_shnum;
579 }
580 
581 template <typename EhdrType, typename ShdrType>
GetBuildIDInfo(Memory * memory,uint64_t * build_id_offset,uint64_t * build_id_size)582 bool GetBuildIDInfo(Memory* memory, uint64_t* build_id_offset, uint64_t* build_id_size) {
583   EhdrType ehdr;
584   if (!memory->ReadFully(0, &ehdr, sizeof(ehdr))) {
585     return false;
586   }
587 
588   uint64_t offset = ehdr.e_shoff;
589   uint64_t sec_offset;
590   uint64_t sec_size;
591   ShdrType shdr;
592   if (ehdr.e_shstrndx >= ehdr.e_shnum) {
593     return false;
594   }
595 
596   uint64_t sh_offset = offset + ehdr.e_shstrndx * ehdr.e_shentsize;
597   if (!memory->ReadFully(sh_offset, &shdr, sizeof(shdr))) {
598     return false;
599   }
600   sec_offset = shdr.sh_offset;
601   sec_size = shdr.sh_size;
602 
603   // Skip the first header, it's always going to be NULL.
604   offset += ehdr.e_shentsize;
605   for (size_t i = 1; i < ehdr.e_shnum; i++, offset += ehdr.e_shentsize) {
606     if (!memory->ReadFully(offset, &shdr, sizeof(shdr))) {
607       return false;
608     }
609     std::string name;
610     if (shdr.sh_type == SHT_NOTE && shdr.sh_name < sec_size &&
611         memory->ReadString(sec_offset + shdr.sh_name, &name) && name == ".note.gnu.build-id") {
612       *build_id_offset = shdr.sh_offset;
613       *build_id_size = shdr.sh_size;
614       return true;
615     }
616   }
617 
618   return false;
619 }
620 
621 template <typename EhdrType, typename ShdrType, typename NhdrType>
ReadBuildIDFromMemory(Memory * memory)622 std::string ElfInterface::ReadBuildIDFromMemory(Memory* memory) {
623   uint64_t note_offset;
624   uint64_t note_size;
625   if (!GetBuildIDInfo<EhdrType, ShdrType>(memory, &note_offset, &note_size)) {
626     return "";
627   }
628 
629   // Ensure there is no overflow in any of the calculations below.
630   uint64_t tmp;
631   if (__builtin_add_overflow(note_offset, note_size, &tmp)) {
632     return "";
633   }
634 
635   uint64_t offset = 0;
636   while (offset < note_size) {
637     if (note_size - offset < sizeof(NhdrType)) {
638       return "";
639     }
640     NhdrType hdr;
641     if (!memory->ReadFully(note_offset + offset, &hdr, sizeof(hdr))) {
642       return "";
643     }
644     offset += sizeof(hdr);
645 
646     if (note_size - offset < hdr.n_namesz) {
647       return "";
648     }
649     if (hdr.n_namesz > 0) {
650       std::string name(hdr.n_namesz, '\0');
651       if (!memory->ReadFully(note_offset + offset, &(name[0]), hdr.n_namesz)) {
652         return "";
653       }
654 
655       // Trim trailing \0 as GNU is stored as a C string in the ELF file.
656       if (name.back() == '\0') name.resize(name.size() - 1);
657 
658       // Align hdr.n_namesz to next power multiple of 4. See man 5 elf.
659       offset += (hdr.n_namesz + 3) & ~3;
660 
661       if (name == "GNU" && hdr.n_type == NT_GNU_BUILD_ID) {
662         if (note_size - offset < hdr.n_descsz || hdr.n_descsz == 0) {
663           return "";
664         }
665         std::string build_id(hdr.n_descsz - 1, '\0');
666         if (memory->ReadFully(note_offset + offset, &build_id[0], hdr.n_descsz)) {
667           return build_id;
668         }
669         return "";
670       }
671     }
672     // Align hdr.n_descsz to next power multiple of 4. See man 5 elf.
673     offset += (hdr.n_descsz + 3) & ~3;
674   }
675   return "";
676 }
677 
678 // Instantiate all of the needed template functions.
679 template void ElfInterface::InitHeadersWithTemplate<uint32_t>();
680 template void ElfInterface::InitHeadersWithTemplate<uint64_t>();
681 
682 template bool ElfInterface::ReadAllHeaders<Elf32_Ehdr, Elf32_Phdr, Elf32_Shdr>(int64_t*);
683 template bool ElfInterface::ReadAllHeaders<Elf64_Ehdr, Elf64_Phdr, Elf64_Shdr>(int64_t*);
684 
685 template void ElfInterface::ReadProgramHeaders<Elf32_Ehdr, Elf32_Phdr>(const Elf32_Ehdr&, int64_t*);
686 template void ElfInterface::ReadProgramHeaders<Elf64_Ehdr, Elf64_Phdr>(const Elf64_Ehdr&, int64_t*);
687 
688 template void ElfInterface::ReadSectionHeaders<Elf32_Ehdr, Elf32_Shdr>(const Elf32_Ehdr&);
689 template void ElfInterface::ReadSectionHeaders<Elf64_Ehdr, Elf64_Shdr>(const Elf64_Ehdr&);
690 
691 template std::string ElfInterface::ReadBuildID<Elf32_Nhdr>();
692 template std::string ElfInterface::ReadBuildID<Elf64_Nhdr>();
693 
694 template std::string ElfInterface::GetSonameWithTemplate<Elf32_Dyn>();
695 template std::string ElfInterface::GetSonameWithTemplate<Elf64_Dyn>();
696 
697 template bool ElfInterface::GetFunctionNameWithTemplate<Elf32_Sym>(uint64_t, std::string*,
698                                                                    uint64_t*);
699 template bool ElfInterface::GetFunctionNameWithTemplate<Elf64_Sym>(uint64_t, std::string*,
700                                                                    uint64_t*);
701 
702 template bool ElfInterface::GetGlobalVariableWithTemplate<Elf32_Sym>(const std::string&, uint64_t*);
703 template bool ElfInterface::GetGlobalVariableWithTemplate<Elf64_Sym>(const std::string&, uint64_t*);
704 
705 template void ElfInterface::GetMaxSizeWithTemplate<Elf32_Ehdr>(Memory*, uint64_t*);
706 template void ElfInterface::GetMaxSizeWithTemplate<Elf64_Ehdr>(Memory*, uint64_t*);
707 
708 template int64_t ElfInterface::GetLoadBias<Elf32_Ehdr, Elf32_Phdr>(Memory*);
709 template int64_t ElfInterface::GetLoadBias<Elf64_Ehdr, Elf64_Phdr>(Memory*);
710 
711 template std::string ElfInterface::ReadBuildIDFromMemory<Elf32_Ehdr, Elf32_Shdr, Elf32_Nhdr>(
712     Memory*);
713 template std::string ElfInterface::ReadBuildIDFromMemory<Elf64_Ehdr, Elf64_Shdr, Elf64_Nhdr>(
714     Memory*);
715 
716 }  // namespace unwindstack
717