Debian Codegraph @

extra/gperftools/gperftools-2.15/src/base/elf_mem_image.cc

raw
1 // -*- Mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*-
2 // Copyright (c) 2008, Google Inc.
3 // All rights reserved.
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are
7 // met:
8 //
9 // * Redistributions of source code must retain the above copyright
10 // notice, this list of conditions and the following disclaimer.
11 // * Redistributions in binary form must reproduce the above
12 // copyright notice, this list of conditions and the following disclaimer
13 // in the documentation and/or other materials provided with the
14 // distribution.
15 // * Neither the name of Google Inc. nor the names of its
16 // contributors may be used to endorse or promote products derived from
17 // this software without specific prior written permission.
18 //
19 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
23 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
24 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
25 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
31 // ---
32 // Author: Paul Pluzhnikov
33 //
34 // Allow dynamic symbol lookup in an in-memory Elf image.
35 //
36
37 #include "base/elf_mem_image.h"
38
39 #ifdef HAVE_ELF_MEM_IMAGE // defined in elf_mem_image.h
40
41 #include <stddef.h> // for size_t, ptrdiff_t
42 #include "base/logging.h"
43
44 // From binutils/include/elf/common.h (this doesn't appear to be documented
45 // anywhere else).
46 //
47 // /* This flag appears in a Versym structure. It means that the symbol
48 // is hidden, and is only visible with an explicit version number.
49 // This is a GNU extension. */
50 // #define VERSYM_HIDDEN 0x8000
51 //
52 // /* This is the mask for the rest of the Versym information. */
53 // #define VERSYM_VERSION 0x7fff
54
55 #define VERSYM_VERSION 0x7fff
56
57 namespace base {
58
59 namespace {
60 template <int N> class ElfClass {
61 public:
62 static const int kElfClass = -1;
63 static int ElfBind(const ElfW(Sym) *) {
64 CHECK(false); // << "Unexpected word size";
65 return 0;
66 }
67 static int ElfType(const ElfW(Sym) *) {
68 CHECK(false); // << "Unexpected word size";
69 return 0;
70 }
71 };
72
73 template <> class ElfClass<32> {
74 public:
75 static const int kElfClass = ELFCLASS32;
76 static int ElfBind(const ElfW(Sym) *symbol) {
77 return ELF32_ST_BIND(symbol->st_info);
78 }
79 static int ElfType(const ElfW(Sym) *symbol) {
80 return ELF32_ST_TYPE(symbol->st_info);
81 }
82 };
83
84 template <> class ElfClass<64> {
85 public:
86 static const int kElfClass = ELFCLASS64;
87 static int ElfBind(const ElfW(Sym) *symbol) {
88 return ELF64_ST_BIND(symbol->st_info);
89 }
90 static int ElfType(const ElfW(Sym) *symbol) {
91 return ELF64_ST_TYPE(symbol->st_info);
92 }
93 };
94
95 typedef ElfClass<__WORDSIZE> CurrentElfClass;
96
97 // Extract an element from one of the ELF tables, cast it to desired type.
98 // This is just a simple arithmetic and a glorified cast.
99 // Callers are responsible for bounds checking.
100 template <class T>
101 const T* GetTableElement(const ElfW(Ehdr) *ehdr,
102 ElfW(Off) table_offset,
103 ElfW(Word) element_size,
104 size_t index) {
105 return reinterpret_cast<const T*>(reinterpret_cast<const char *>(ehdr)
106 + table_offset
107 + index * element_size);
108 }
109 } // namespace
110
111 const void *const ElfMemImage::kInvalidBase =
112 reinterpret_cast<const void *>(~0L);
113
114 ElfMemImage::ElfMemImage(const void *base) {
115 CHECK(base != kInvalidBase);
116 Init(base);
117 }
118
119 int ElfMemImage::GetNumSymbols() const {
120 if (!hash_) {
121 return 0;
122 }
123 // See http://www.caldera.com/developers/gabi/latest/ch5.dynamic.html#hash
124 return hash_[1];
125 }
126
127 const ElfW(Sym) *ElfMemImage::GetDynsym(int index) const {
128 CHECK_LT(index, GetNumSymbols());
129 return dynsym_ + index;
130 }
131
132 const ElfW(Versym) *ElfMemImage::GetVersym(int index) const {
133 CHECK_LT(index, GetNumSymbols());
134 return versym_ + index;
135 }
136
137 const ElfW(Phdr) *ElfMemImage::GetPhdr(int index) const {
138 CHECK_LT(index, ehdr_->e_phnum);
139 return GetTableElement<ElfW(Phdr)>(ehdr_,
140 ehdr_->e_phoff,
141 ehdr_->e_phentsize,
142 index);
143 }
144
145 const char *ElfMemImage::GetDynstr(ElfW(Word) offset) const {
146 CHECK_LT(offset, strsize_);
147 return dynstr_ + offset;
148 }
149
150 const void *ElfMemImage::GetSymAddr(const ElfW(Sym) *sym) const {
151 if (sym->st_shndx == SHN_UNDEF || sym->st_shndx >= SHN_LORESERVE) {
152 // Symbol corresponds to "special" (e.g. SHN_ABS) section.
153 return reinterpret_cast<const void *>(sym->st_value);
154 }
155 CHECK_LT(link_base_, sym->st_value);
156 return GetTableElement<char>(ehdr_, 0, 1, sym->st_value) - link_base_;
157 }
158
159 const ElfW(Verdef) *ElfMemImage::GetVerdef(int index) const {
160 CHECK_LE(index, verdefnum_);
161 const ElfW(Verdef) *version_definition = verdef_;
162 while (version_definition->vd_ndx < index && version_definition->vd_next) {
163 const char *const version_definition_as_char =
164 reinterpret_cast<const char *>(version_definition);
165 version_definition =
166 reinterpret_cast<const ElfW(Verdef) *>(version_definition_as_char +
167 version_definition->vd_next);
168 }
169 return version_definition->vd_ndx == index ? version_definition : NULL;
170 }
171
172 const ElfW(Verdaux) *ElfMemImage::GetVerdefAux(
173 const ElfW(Verdef) *verdef) const {
174 return reinterpret_cast<const ElfW(Verdaux) *>(verdef+1);
175 }
176
177 const char *ElfMemImage::GetVerstr(ElfW(Word) offset) const {
178 CHECK_LT(offset, strsize_);
179 return dynstr_ + offset;
180 }
181
182 void ElfMemImage::Init(const void *base) {
183 ehdr_ = NULL;
184 dynsym_ = NULL;
185 dynstr_ = NULL;
186 versym_ = NULL;
187 verdef_ = NULL;
188 hash_ = NULL;
189 strsize_ = 0;
190 verdefnum_ = 0;
191 link_base_ = ~0L; // Sentinel: PT_LOAD .p_vaddr can't possibly be this.
192 if (!base) {
193 return;
194 }
195 const intptr_t base_as_uintptr_t = reinterpret_cast<uintptr_t>(base);
196 // Fake VDSO has low bit set.
197 const bool fake_vdso = ((base_as_uintptr_t & 1) != 0);
198 base = reinterpret_cast<const void *>(base_as_uintptr_t & ~1);
199 const char *const base_as_char = reinterpret_cast<const char *>(base);
200 if (base_as_char[EI_MAG0] != ELFMAG0 || base_as_char[EI_MAG1] != ELFMAG1 ||
201 base_as_char[EI_MAG2] != ELFMAG2 || base_as_char[EI_MAG3] != ELFMAG3) {
202 RAW_DCHECK(false, "no ELF magic"); // at %p", base);
203 return;
204 }
205 int elf_class = base_as_char[EI_CLASS];
206 if (elf_class != CurrentElfClass::kElfClass) {
207 DCHECK_EQ(elf_class, CurrentElfClass::kElfClass);
208 return;
209 }
210 switch (base_as_char[EI_DATA]) {
211 case ELFDATA2LSB: {
212 if (__LITTLE_ENDIAN != __BYTE_ORDER) {
213 DCHECK_EQ(__LITTLE_ENDIAN, __BYTE_ORDER); // << ": wrong byte order";
214 return;
215 }
216 break;
217 }
218 case ELFDATA2MSB: {
219 if (__BIG_ENDIAN != __BYTE_ORDER) {
220 DCHECK_EQ(__BIG_ENDIAN, __BYTE_ORDER); // << ": wrong byte order";
221 return;
222 }
223 break;
224 }
225 default: {
226 RAW_DCHECK(false, "unexpected data encoding"); // << base_as_char[EI_DATA];
227 return;
228 }
229 }
230
231 ehdr_ = reinterpret_cast<const ElfW(Ehdr) *>(base);
232 const ElfW(Phdr) *dynamic_program_header = NULL;
233 for (int i = 0; i < ehdr_->e_phnum; ++i) {
234 const ElfW(Phdr) *const program_header = GetPhdr(i);
235 switch (program_header->p_type) {
236 case PT_LOAD:
237 if (link_base_ == ~0L) {
238 link_base_ = program_header->p_vaddr;
239 }
240 break;
241 case PT_DYNAMIC:
242 dynamic_program_header = program_header;
243 break;
244 }
245 }
246 if (link_base_ == ~0L || !dynamic_program_header) {
247 RAW_DCHECK(~0L != link_base_, "no PT_LOADs in VDSO");
248 RAW_DCHECK(dynamic_program_header, "no PT_DYNAMIC in VDSO");
249 // Mark this image as not present. Can not recur infinitely.
250 Init(0);
251 return;
252 }
253 ptrdiff_t relocation =
254 base_as_char - reinterpret_cast<const char *>(link_base_);
255 ElfW(Dyn) *dynamic_entry =
256 reinterpret_cast<ElfW(Dyn) *>(dynamic_program_header->p_vaddr +
257 relocation);
258 for (; dynamic_entry->d_tag != DT_NULL; ++dynamic_entry) {
259 ElfW(Xword) value = dynamic_entry->d_un.d_val;
260 if (fake_vdso) {
261 // A complication: in the real VDSO, dynamic entries are not relocated
262 // (it wasn't loaded by a dynamic loader). But when testing with a
263 // "fake" dlopen()ed vdso library, the loader relocates some (but
264 // not all!) of them before we get here.
265 if (dynamic_entry->d_tag == DT_VERDEF) {
266 // The only dynamic entry (of the ones we care about) libc-2.3.6
267 // loader doesn't relocate.
268 value += relocation;
269 }
270 } else {
271 // Real VDSO. Everything needs to be relocated.
272 value += relocation;
273 }
274 switch (dynamic_entry->d_tag) {
275 case DT_HASH:
276 hash_ = reinterpret_cast<ElfW(Word) *>(value);
277 break;
278 case DT_SYMTAB:
279 dynsym_ = reinterpret_cast<ElfW(Sym) *>(value);
280 break;
281 case DT_STRTAB:
282 dynstr_ = reinterpret_cast<const char *>(value);
283 break;
284 case DT_VERSYM:
285 versym_ = reinterpret_cast<ElfW(Versym) *>(value);
286 break;
287 case DT_VERDEF:
288 verdef_ = reinterpret_cast<ElfW(Verdef) *>(value);
289 break;
290 case DT_VERDEFNUM:
291 verdefnum_ = dynamic_entry->d_un.d_val;
292 break;
293 case DT_STRSZ:
294 strsize_ = dynamic_entry->d_un.d_val;
295 break;
296 default:
297 // Unrecognized entries explicitly ignored.
298 break;
299 }
300 }
301 if (!hash_ || !dynsym_ || !dynstr_ || !versym_ ||
302 !verdef_ || !verdefnum_ || !strsize_) {
303 RAW_DCHECK(hash_, "invalid VDSO (no DT_HASH)");
304 RAW_DCHECK(dynsym_, "invalid VDSO (no DT_SYMTAB)");
305 RAW_DCHECK(dynstr_, "invalid VDSO (no DT_STRTAB)");
306 RAW_DCHECK(versym_, "invalid VDSO (no DT_VERSYM)");
307 RAW_DCHECK(verdef_, "invalid VDSO (no DT_VERDEF)");
308 RAW_DCHECK(verdefnum_, "invalid VDSO (no DT_VERDEFNUM)");
309 RAW_DCHECK(strsize_, "invalid VDSO (no DT_STRSZ)");
310 // Mark this image as not present. Can not recur infinitely.
311 Init(0);
312 return;
313 }
314 }
315
316 bool ElfMemImage::LookupSymbol(const char *name,
317 const char *version,
318 int type,
319 SymbolInfo *info) const {
320 for (SymbolIterator it = begin(); it != end(); ++it) {
321 if (strcmp(it->name, name) == 0 && strcmp(it->version, version) == 0 &&
322 CurrentElfClass::ElfType(it->symbol) == type) {
323 if (info) {
324 *info = *it;
325 }
326 return true;
327 }
328 }
329 return false;
330 }
331
332 bool ElfMemImage::LookupSymbolByAddress(const void *address,
333 SymbolInfo *info_out) const {
334 for (SymbolIterator it = begin(); it != end(); ++it) {
335 const char *const symbol_start =
336 reinterpret_cast<const char *>(it->address);
337 const char *const symbol_end = symbol_start + it->symbol->st_size;
338 if (symbol_start <= address && address < symbol_end) {
339 if (info_out) {
340 // Client wants to know details for that symbol (the usual case).
341 if (CurrentElfClass::ElfBind(it->symbol) == STB_GLOBAL) {
342 // Strong symbol; just return it.
343 *info_out = *it;
344 return true;
345 } else {
346 // Weak or local. Record it, but keep looking for a strong one.
347 *info_out = *it;
348 }
349 } else {
350 // Client only cares if there is an overlapping symbol.
351 return true;
352 }
353 }
354 }
355 return false;
356 }
357
358 ElfMemImage::SymbolIterator::SymbolIterator(const void *const image, int index)
359 : index_(index), image_(image) {
360 }
361
362 const ElfMemImage::SymbolInfo *ElfMemImage::SymbolIterator::operator->() const {
363 return &info_;
364 }
365
366 const ElfMemImage::SymbolInfo& ElfMemImage::SymbolIterator::operator*() const {
367 return info_;
368 }
369
370 bool ElfMemImage::SymbolIterator::operator==(const SymbolIterator &rhs) const {
371 return this->image_ == rhs.image_ && this->index_ == rhs.index_;
372 }
373
374 bool ElfMemImage::SymbolIterator::operator!=(const SymbolIterator &rhs) const {
375 return !(*this == rhs);
376 }
377
378 ElfMemImage::SymbolIterator &ElfMemImage::SymbolIterator::operator++() {
379 this->Update(1);
380 return *this;
381 }
382
383 ElfMemImage::SymbolIterator ElfMemImage::begin() const {
384 SymbolIterator it(this, 0);
385 it.Update(0);
386 return it;
387 }
388
389 ElfMemImage::SymbolIterator ElfMemImage::end() const {
390 return SymbolIterator(this, GetNumSymbols());
391 }
392
393 void ElfMemImage::SymbolIterator::Update(int increment) {
394 const ElfMemImage *image = reinterpret_cast<const ElfMemImage *>(image_);
395 CHECK(image->IsPresent() || increment == 0);
396 if (!image->IsPresent()) {
397 return;
398 }
399 index_ += increment;
400 if (index_ >= image->GetNumSymbols()) {
401 index_ = image->GetNumSymbols();
402 return;
403 }
404 const ElfW(Sym) *symbol = image->GetDynsym(index_);
405 const ElfW(Versym) *version_symbol = image->GetVersym(index_);
406 CHECK(symbol && version_symbol);
407 const char *const symbol_name = image->GetDynstr(symbol->st_name);
408 const ElfW(Versym) version_index = version_symbol[0] & VERSYM_VERSION;
409 const ElfW(Verdef) *version_definition = NULL;
410 const char *version_name = "";
411 if (symbol->st_shndx == SHN_UNDEF) {
412 // Undefined symbols reference DT_VERNEED, not DT_VERDEF, and
413 // version_index could well be greater than verdefnum_, so calling
414 // GetVerdef(version_index) may trigger assertion.
415 } else {
416 version_definition = image->GetVerdef(version_index);
417 }
418 if (version_definition) {
419 // I am expecting 1 or 2 auxiliary entries: 1 for the version itself,
420 // optional 2nd if the version has a parent.
421 CHECK_LE(1, version_definition->vd_cnt);
422 CHECK_LE(version_definition->vd_cnt, 2);
423 const ElfW(Verdaux) *version_aux = image->GetVerdefAux(version_definition);
424 version_name = image->GetVerstr(version_aux->vda_name);
425 }
426 info_.name = symbol_name;
427 info_.version = version_name;
428 info_.address = image->GetSymAddr(symbol);
429 info_.symbol = symbol;
430 }
431
432 } // namespace base
433
434 #endif // HAVE_ELF_MEM_IMAGE