1 /*
2  * Copyright (C) 2019 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 SRC_KALLSYMS_KERNEL_SYMBOL_MAP_H_
18 #define SRC_KALLSYMS_KERNEL_SYMBOL_MAP_H_
19 
20 #include <stdint.h>
21 
22 #include <array>
23 #include <forward_list>
24 #include <string>
25 #include <vector>
26 
27 namespace perfetto {
28 
29 namespace base {
30 class StringView;
31 }
32 
33 // A parser and memory-efficient container for /proc/kallsyms.
34 // It can store a full kernel symbol table in ~1.2MB of memory and perform fast
35 // lookups using logarithmic binary searches + bounded linear scans.
36 //
37 // /proc/kallsyms is a ~10 MB text file that contains the map of kernel symbols,
38 // as follows:
39 // ffffff8f77682f8c t el0_sync_invalid
40 // ffffff8f77683060 t el0_irq_invalid
41 // ...
42 // In a typipcal Android kernel, it consists of 213K lines. Out of these, only
43 // 116K are interesting for the sake of symbolizing kernel functions, the rest
44 // are .rodata (variables), weak or other useless symbols.
45 // Still, even keeping around 116K pointers would require 116K * 8 ~= 1 MB of
46 // memory, without accounting for any strings for the symbols names.
47 // The SUM(str.len) for the 116K symbol names adds up to 2.7 MB (without
48 // counting their addresses).
49 // However consider the following:
50 // - Symbol addresses are mostly contiguous. Modulo the initial KASLR loading
51 //   address, most symbols are few hundreds bytes apart from each other.
52 // - Symbol names are made of tokens that are quite frequent (token: the result
53 //   of name.split('_')). If we tokenize the 2.7 MB of strings, the resulting
54 //   SUM(distinct_token.len) goes down 2.7MB -> 146 KB. This is because tokens
55 //   like "get", "set" or "event" show up thousands of times.
56 // - Symbol names are ASCII strings using only 7 out of 8 bits.
57 //
58 // In the light of this, the in-memory architecture of this data structure is
59 // as follows:
60 // We keep two tables around: (1) a token table and (2) a symbol table. Both
61 // table are a flat byte vector with some sparse lookaside index to make lookups
62 // faster and avoid full linear scans.
63 //
64 // Token table
65 // -----------
66 // The token table is a flat char buffer. Tokens are variable size (>0). Each
67 // token is identified by its ordinality, so token id 3 is the 3rd token in
68 // the table. All tokens are concatenated together.
69 // Given the ASCII encoding, the MSB is used as a terminator. So instead of
70 // wasting an extra NUL byte for each string, the last char of each token has
71 // the MSB set.
72 // Furthermore, a lookaside index stores the offset of tokens (i.e. Token N
73 // starts at offset O in the buffer) to allow fast lookups. In order to avoid
74 // wasting too much memory, the index is sparse and track the offsets of only
75 // one every kTokenIndexSamplinig tokens.
76 // When looking up a token ID N, the table seeks at the offset of the closest
77 // token <= N, and then scans linearly the next (at most kTokenIndexSamplinig)
78 // tokens, counting the MSBs found, until the right token id is found.
79 // buf:   set*get*kernel*load*fpsimd*return*wrapper*el0*skip*sync*neon*bit*aes
80 //        ^                   ^                         ^
81 //        |                   |                         |
82 // index: 0@0                 4@15                      8@21
83 
84 // Symbol table
85 // ------------
86 // The symbol table is a flat char buffer that stores for each symbol: its
87 // address + the list of token indexes in the token table. The main caveats are
88 // that:
89 // - Symbol addresses are delta encoded (delta from prev symbol's addr).
90 // - Both delta addresses and token indexes are var-int encoded.
91 // - The LSB of token indexes is used as EOF marker (i.e. the next varint is
92 //   the delta-addr for the next symbol). This time the LSB is used because of
93 //   the varint encoding.
94 // At parsing time symbols are ordered by address and tokens are sorted by
95 // frequency, so that the top used 64 tokens can be represented with 1 byte.
96 // (Rationale for 64: 1 byte = 8 bits. The MSB bit of each byte is used for the
97 // varint encoding, the LSB bit of each number is used as end-of-tokens marker.
98 // There are 6 bits left -> 64 indexes can be represented using one byte).
99 // In summary the symbol table looks as follows:
100 //
101 // Base address: 0xbeef0000
102 // Symbol buffer:
103 // 0 1|0  4|0  6|1    // 0xbeef0000: 1,4,6 -> get_fpsimd_wrapper
104 // 8 7|0  3|1         // 0xbeef0008: 7,3   -> el0_load
105 // ...
106 // Like in the case of the token table, a lookaside index keeps track of the
107 // offset of one every kSymIndexSamplinig addresses.
108 // The Lookup(ADDR) function operates as follows:
109 // 1. Performs a logarithmic binary search in the symbols index, finding the
110 //    offset of the closest addres <= ADDR.
111 // 2. Skip over at most kSymIndexSamplinig until the symbol is found.
112 // 3. For each token index, lookup the corresponding token string and
113 //    concatenate them to build the symbol name.
114 
115 class KernelSymbolMap {
116  public:
117   // The two constants below are changeable only for the benchmark use.
118   // Trades off size of the root |index_| vs worst-case linear scans size.
119   // A higher number makes the index more sparse.
120   static size_t kSymIndexSampling;
121 
122   // Trades off size of the TokenTable |index_| vs worst-case linear scans size.
123   static size_t kTokenIndexSampling;
124 
125   // Parses a kallsyms file. Returns the number of valid symbols decoded.
126   size_t Parse(const std::string& kallsyms_path);
127 
128   // Looks up the closest symbol (i.e. the one with the highest address <=
129   // |addr|) from its absolute 64-bit address.
130   // Returns an empty string if the symbol is not found (which can happen only
131   // if the passed |addr| is < min(addr)).
132   std::string Lookup(uint64_t addr);
133 
134   // Returns the numberr of valid symbols decoded.
num_syms()135   size_t num_syms() const { return num_syms_; }
136 
137   // Returns the size in bytes used by the adddress table (without counting
138   // the tokens).
addr_bytes()139   size_t addr_bytes() const { return buf_.size() + index_.size() * 8; }
140 
141   // Returns the total memory usage in bytes.
size_bytes()142   size_t size_bytes() const { return addr_bytes() + tokens_.size_bytes(); }
143 
144   // Token table.
145   class TokenTable {
146    public:
147     using TokenId = uint32_t;
148     TokenTable();
149     ~TokenTable();
150     TokenId Add(const std::string&);
151     base::StringView Lookup(TokenId);
size_bytes()152     size_t size_bytes() const { return buf_.size() + index_.size() * 4; }
153 
shrink_to_fit()154     void shrink_to_fit() {
155       buf_.shrink_to_fit();
156       index_.shrink_to_fit();
157     }
158 
159    private:
160     TokenId num_tokens_ = 0;
161 
162     std::vector<char> buf_;  // Token buffer.
163 
164     // The value i-th in the vector contains the offset (within |buf_|) of the
165     // (i * kTokenIndexSamplinig)-th token.
166     std::vector<uint32_t> index_;
167   };
168 
169  private:
170   TokenTable tokens_;  // Token table.
171 
172   uint64_t base_addr_ = 0;    // Address of the first symbol (after sorting).
173   size_t num_syms_ = 0;       // Number of valid symbols stored.
174   std::vector<uint8_t> buf_;  // Symbol buffer.
175 
176   // The key is (address - base_addr_), the value is the byte offset in |buf_|
177   // where the symbol entry starts (i.e. the start of the varint that tells the
178   // delta from the previous symbol).
179   std::vector<std::pair<uint32_t /*rel_addr*/, uint32_t /*offset*/>> index_;
180 };
181 
182 }  // namespace perfetto
183 
184 #endif  // SRC_KALLSYMS_KERNEL_SYMBOL_MAP_H_
185