1 /*
2  * Copyright (C) 2016 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 #ifndef _LIBUNWINDSTACK_SYMBOLS_H
18 #define _LIBUNWINDSTACK_SYMBOLS_H
19 
20 #include <stdint.h>
21 
22 #include <optional>
23 #include <string>
24 #include <unordered_map>
25 
26 namespace unwindstack {
27 
28 // Forward declaration.
29 class Memory;
30 
31 class Symbols {
32   struct Info {
33     uint64_t addr;  // Symbol address.
34     uint32_t size;  // Symbol size in bytes. Zero if not a function.
35     uint32_t name;  // Offset in .strtab.
36   };
37 
38  public:
39   Symbols(uint64_t offset, uint64_t size, uint64_t entry_size, uint64_t str_offset,
40           uint64_t str_size);
41   virtual ~Symbols() = default;
42 
43   template <typename SymType>
44   bool GetName(uint64_t addr, Memory* elf_memory, std::string* name, uint64_t* func_offset);
45 
46   template <typename SymType>
47   bool GetGlobal(Memory* elf_memory, const std::string& name, uint64_t* memory_address);
48 
ClearCache()49   void ClearCache() {
50     symbols_.clear();
51     remap_.reset();
52   }
53 
54  private:
55   template <typename SymType>
56   const Info* ReadFuncInfo(uint32_t symbol_index, Memory* elf_memory);
57 
58   template <typename SymType, bool RemapIndices>
59   const Info* BinarySearch(uint64_t addr, Memory* elf_memory);
60 
61   template <typename SymType>
62   void BuildRemapTable(Memory* elf_memory);
63 
64   const uint64_t offset_;
65   const uint64_t count_;
66   const uint64_t entry_size_;
67   const uint64_t str_offset_;
68   const uint64_t str_end_;
69 
70   std::unordered_map<uint32_t, Info> symbols_;  // Cache of read symbols (keyed by symbol index).
71   std::optional<std::vector<uint32_t>> remap_;  // Indices of function symbols sorted by address.
72 };
73 
74 }  // namespace unwindstack
75 
76 #endif  // _LIBUNWINDSTACK_SYMBOLS_H
77