Apply clang-format to folly/experimental/symbolizer/
[folly.git] / folly / experimental / symbolizer / Elf-inl.h
1 /*
2  * Copyright 2017 Facebook, Inc.
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 FOLLY_EXPERIMENTAL_SYMBOLIZER_ELF_H_
18 #error This file must be included from Elf.h
19 #endif
20
21 namespace folly {
22 namespace symbolizer {
23
24 template <class Fn>
25 const ElfShdr* ElfFile::iterateSections(Fn fn) const {
26   const ElfShdr* ptr = &at<ElfShdr>(elfHeader().e_shoff);
27   for (size_t i = 0; i < elfHeader().e_shnum; i++, ptr++) {
28     if (fn(*ptr)) {
29       return ptr;
30     }
31   }
32
33   return nullptr;
34 }
35
36 template <class Fn>
37 const ElfShdr* ElfFile::iterateSectionsWithType(uint32_t type, Fn fn) const {
38   return iterateSections(
39       [&](const ElfShdr& sh) { return sh.sh_type == type && fn(sh); });
40 }
41
42 template <class Fn>
43 const char* ElfFile::iterateStrings(const ElfShdr& stringTable, Fn fn) const {
44   validateStringTable(stringTable);
45
46   const char* start = file_ + stringTable.sh_offset;
47   const char* end = start + stringTable.sh_size;
48
49   const char* ptr = start;
50   while (ptr != end && !fn(ptr)) {
51     ptr += strlen(ptr) + 1;
52   }
53
54   return ptr != end ? ptr : nullptr;
55 }
56
57 template <class Fn>
58 const ElfSym* ElfFile::iterateSymbols(const ElfShdr& section, Fn fn) const {
59   FOLLY_SAFE_CHECK(
60       section.sh_entsize == sizeof(ElfSym),
61       "invalid entry size in symbol table");
62
63   const ElfSym* sym = &at<ElfSym>(section.sh_offset);
64   const ElfSym* end = sym + (section.sh_size / section.sh_entsize);
65
66   while (sym < end) {
67     if (fn(*sym)) {
68       return sym;
69     }
70
71     ++sym;
72   }
73
74   return nullptr;
75 }
76
77 template <class Fn>
78 const ElfSym* ElfFile::iterateSymbolsWithType(
79     const ElfShdr& section,
80     uint32_t type,
81     Fn fn) const {
82   // N.B. st_info has the same representation on 32- and 64-bit platforms
83   return iterateSymbols(section, [&](const ElfSym& sym) -> bool {
84     return ELF32_ST_TYPE(sym.st_info) == type && fn(sym);
85   });
86 }
87
88 } // namespace symbolizer
89 } // namespace folly