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