Debian Codegraph @

src/binary/elf.cpp

raw
1 #include "binary/elf.hpp"
2
3 #include "utils/error.hpp"
4 #include "utils/io/base_file.hpp"
5 #include "utils/io/memory_file_view.hpp"
6 #include "utils/optional.hpp"
7 #include "utils/io/file.hpp"
8 #include "utils/string_view.hpp"
9
10 #if IS_LINUX
11
12 #include <array>
13 #include <cstdint>
14 #include <cstdio>
15 #include <cstring>
16 #include <mutex>
17 #include <type_traits>
18 #include <unordered_map>
19
20 #include <elf.h>
21
22 CPPTRACE_BEGIN_NAMESPACE
23 namespace detail {
24 elf::elf(
25 std::unique_ptr<base_file> file,
26 bool is_little_endian,
27 bool is_64
28 ) : file(std::move(file)), is_little_endian(is_little_endian), is_64(is_64) {}
29
30 Result<elf, internal_error> elf::open(std::unique_ptr<base_file> file) {
31 // Initial checks/metadata
32 auto magic = file->read<std::array<char, 4>>(0);
33 if(magic.is_error()) {
34 return std::move(magic).unwrap_error();
35 }
36 if(magic.unwrap_value() != (std::array<char, 4>{0x7F, 'E', 'L', 'F'})) {
37 return internal_error("File is not ELF {}", file->path());
38 }
39 auto ei_class = file->read<std::uint8_t>(4);
40 if(ei_class.is_error()) {
41 return std::move(ei_class).unwrap_error();
42 }
43 bool is_64 = ei_class.unwrap_value() == 2;
44 auto ei_data = file->read<std::uint8_t>(5);
45 if(ei_data.is_error()) {
46 return std::move(ei_data).unwrap_error();
47 }
48 bool is_little_endian = ei_data.unwrap_value() == 1;
49 auto ei_version = file->read<std::uint8_t>(6);
50 if(ei_version.is_error()) {
51 return std::move(ei_version).unwrap_error();
52 }
53 if(ei_version.unwrap_value() != 1) {
54 return internal_error("Unexpected ELF version {}", file->path());
55 }
56 return elf(std::move(file), is_little_endian, is_64);
57 }
58
59 Result<elf, internal_error> elf::open(cstring_view object_path) {
60 auto file_res = file::open(object_path);
61 if(!file_res) {
62 return internal_error("Unable to read object file {}", object_path);
63 }
64 auto& file = file_res.unwrap_value();
65 return open(make_unique(std::move(file)));
66 }
67
68 Result<elf, internal_error> elf::open(cbspan object) {
69 return open(make_unique<memory_file_view>(object));
70 }
71
72 Result<std::uintptr_t, internal_error> elf::get_module_image_base() {
73 // get image base
74 if(is_64) {
75 return get_module_image_base_impl<64>();
76 } else {
77 return get_module_image_base_impl<32>();
78 }
79 }
80
81 template<std::size_t Bits>
82 Result<std::uintptr_t, internal_error> elf::get_module_image_base_impl() {
83 static_assert(Bits == 32 || Bits == 64, "Unexpected Bits argument");
84 using PHeader = typename std::conditional<Bits == 32, Elf32_Phdr, Elf64_Phdr>::type;
85 auto header = get_header_info();
86 if(header.is_error()) {
87 return std::move(header).unwrap_error();
88 }
89 const auto& header_info = header.unwrap_value();
90 // PT_PHDR will occur at most once
91 // Should be somewhat reliable https://stackoverflow.com/q/61568612/15675011
92 // It should occur at the beginning but may as well loop just in case
93 for(unsigned i = 0; i < header_info.e_phnum; i++) {
94 auto loaded_ph = file->read<PHeader>(header_info.e_phoff + header_info.e_phentsize * i);
95 if(loaded_ph.is_error()) {
96 return std::move(loaded_ph).unwrap_error();
97 }
98 const PHeader& program_header = loaded_ph.unwrap_value();
99 if(byteswap_if_needed(program_header.p_type) == PT_PHDR) {
100 return byteswap_if_needed(program_header.p_vaddr) -
101 byteswap_if_needed(program_header.p_offset);
102 }
103 }
104 // Apparently some objects like shared objects can end up missing this header. 0 as a base seems correct.
105 return 0;
106 }
107
108 optional<std::string> elf::lookup_symbol(frame_ptr pc) {
109 if(auto symtab = get_symtab()) {
110 if(auto symbol = lookup_symbol(pc, symtab.unwrap_value())) {
111 return symbol;
112 }
113 }
114 if(auto dynamic_symtab = get_dynamic_symtab()) {
115 if(auto symbol = lookup_symbol(pc, dynamic_symtab.unwrap_value())) {
116 return symbol;
117 }
118 }
119 return nullopt;
120 }
121
122 optional<std::string> elf::lookup_symbol(frame_ptr pc, const optional<symtab_info>& maybe_symtab) {
123 if(!maybe_symtab) {
124 return nullopt;
125 }
126 auto& symtab = maybe_symtab.unwrap();
127 if(symtab.strtab_link == SHN_UNDEF) {
128 return nullopt;
129 }
130 auto strtab_ = get_strtab(symtab.strtab_link);
131 if(strtab_.is_error()) {
132 return nullopt;
133 }
134 auto& strtab = strtab_.unwrap_value();
135 auto it = first_less_than_or_equal(
136 symtab.entries.begin(),
137 symtab.entries.end(),
138 pc,
139 [] (frame_ptr pc, const symtab_entry& entry) {
140 return pc < entry.st_value;
141 }
142 );
143 if(it == symtab.entries.end()) {
144 return nullopt;
145 }
146 if(pc <= it->st_value + it->st_size) {
147 return strtab.data() + it->st_name;
148 }
149 return nullopt;
150 }
151
152 Result<std::vector<elf::pc_range>, internal_error> elf::get_pc_ranges() {
153 std::vector<pc_range> vec;
154 auto header_info_ = get_header_info();
155 if(header_info_.is_error()) {
156 return header_info_.unwrap_error();
157 }
158 auto& header_info = header_info_.unwrap_value();
159 auto strtab_ = get_strtab(header_info.e_shstrndx);
160 if(strtab_.is_error()) {
161 return strtab_.unwrap_error();
162 }
163 auto& strtab = strtab_.unwrap_value();
164 auto sections_res = get_sections();
165 if(!sections_res) {
166 return sections_res.unwrap_error();
167 }
168 const auto& sections = sections_res.unwrap_value();
169 for(const auto& section : sections) {
170 if(string_view(strtab.data() + section.sh_name) == ".text") {
171 vec.push_back(
172 pc_range{to<frame_ptr>(section.sh_addr), to<frame_ptr>(section.sh_addr + section.sh_size)}
173 );
174 }
175 }
176 return vec;
177 }
178
179 Result<optional<std::vector<elf::symbol_entry>>, internal_error> elf::get_symtab_entries() {
180 return resolve_symtab_entries(get_symtab());
181 }
182 Result<optional<std::vector<elf::symbol_entry>>, internal_error> elf::get_dynamic_symtab_entries() {
183 return resolve_symtab_entries(get_dynamic_symtab());
184 }
185
186 Result<optional<std::vector<elf::symbol_entry>>, internal_error> elf::resolve_symtab_entries(
187 const Result<const optional<elf::symtab_info> &, internal_error>& symtab
188 ) {
189 if(!symtab) {
190 return symtab.unwrap_error();
191 }
192 if(!symtab.unwrap_value()) {
193 return nullopt;
194 }
195 const auto& info = symtab.unwrap_value().unwrap();
196 optional<const std::vector<char>&> strtab;
197 if(info.strtab_link != SHN_UNDEF) {
198 auto strtab_ = get_strtab(info.strtab_link);
199 if(strtab_.is_error()) {
200 return strtab_.unwrap_error();
201 }
202 strtab = strtab_.unwrap_value();
203 }
204 std::vector<symbol_entry> res;
205 for(const auto& entry : info.entries) {
206 res.push_back({
207 strtab.has_value() ? strtab.unwrap().data() + entry.st_name : "<strtab error>",
208 entry.st_shndx,
209 entry.st_value,
210 entry.st_size
211 });
212 }
213 return res;
214 }
215
216 template<typename T, typename std::enable_if<std::is_integral<T>::value, int>::type>
217 T elf::byteswap_if_needed(T value) {
218 if(detail::is_little_endian() == is_little_endian) {
219 return value;
220 } else {
221 return byteswap(value);
222 }
223 }
224
225 Result<const elf::header_info&, internal_error> elf::get_header_info() {
226 if(header) {
227 return header.unwrap();
228 }
229 if(tried_to_load_header) {
230 return internal_error("previous header load failed {}", file->path());
231 }
232 tried_to_load_header = true;
233 if(is_64) {
234 return get_header_info_impl<64>();
235 } else {
236 return get_header_info_impl<32>();
237 }
238 }
239
240 template<std::size_t Bits>
241 Result<const elf::header_info&, internal_error> elf::get_header_info_impl() {
242 static_assert(Bits == 32 || Bits == 64, "Unexpected Bits argument");
243 using Header = typename std::conditional<Bits == 32, Elf32_Ehdr, Elf64_Ehdr>::type;
244 auto loaded_header = file->read<Header>(0);
245 if(loaded_header.is_error()) {
246 return std::move(loaded_header).unwrap_error();
247 }
248 const Header& file_header = loaded_header.unwrap_value();
249 if(file_header.e_ehsize != sizeof(Header)) {
250 return internal_error("ELF file header size mismatch {}", file->path());
251 }
252 header_info info;
253 info.e_phoff = byteswap_if_needed(file_header.e_phoff);
254 info.e_phnum = byteswap_if_needed(file_header.e_phnum);
255 info.e_phentsize = byteswap_if_needed(file_header.e_phentsize);
256 info.e_shoff = byteswap_if_needed(file_header.e_shoff);
257 info.e_shnum = byteswap_if_needed(file_header.e_shnum);
258 info.e_shentsize = byteswap_if_needed(file_header.e_shentsize);
259 info.e_shstrndx = byteswap_if_needed(file_header.e_shstrndx);
260 header = info;
261 return header.unwrap();
262 }
263
264 Result<const std::vector<elf::section_info>&, internal_error> elf::get_sections() {
265 if(did_load_sections) {
266 return sections;
267 }
268 if(tried_to_load_sections) {
269 return internal_error("previous sections load failed {}", file->path());
270 }
271 tried_to_load_sections = true;
272 if(is_64) {
273 return get_sections_impl<64>();
274 } else {
275 return get_sections_impl<32>();
276 }
277 }
278
279 template<std::size_t Bits>
280 Result<const std::vector<elf::section_info>&, internal_error> elf::get_sections_impl() {
281 static_assert(Bits == 32 || Bits == 64, "Unexpected Bits argument");
282 using SHeader = typename std::conditional<Bits == 32, Elf32_Shdr, Elf64_Shdr>::type;
283 auto header = get_header_info();
284 if(header.is_error()) {
285 return std::move(header).unwrap_error();
286 }
287 const auto& header_info = header.unwrap_value();
288 for(unsigned i = 0; i < header_info.e_shnum; i++) {
289 auto loaded_sh = file->read<SHeader>(header_info.e_shoff + header_info.e_shentsize * i);
290 if(loaded_sh.is_error()) {
291 return std::move(loaded_sh).unwrap_error();
292 }
293 const SHeader& section_header = loaded_sh.unwrap_value();
294 section_info info;
295 info.sh_name = byteswap_if_needed(section_header.sh_name);
296 info.sh_type = byteswap_if_needed(section_header.sh_type);
297 info.sh_addr = byteswap_if_needed(section_header.sh_addr);
298 info.sh_offset = byteswap_if_needed(section_header.sh_offset);
299 info.sh_size = byteswap_if_needed(section_header.sh_size);
300 info.sh_entsize = byteswap_if_needed(section_header.sh_entsize);
301 info.sh_link = byteswap_if_needed(section_header.sh_link);
302 sections.push_back(info);
303 }
304 did_load_sections = true;
305 return sections;
306 }
307
308 Result<const std::vector<char>&, internal_error> elf::get_strtab(std::size_t index) {
309 auto res = strtab_entries.insert({index, {}});
310 auto it = res.first;
311 auto did_insert = res.second;
312 auto& entry = it->second;
313 if(!did_insert) {
314 if(entry.did_load_strtab) {
315 return entry.data;
316 }
317 if(entry.tried_to_load_strtab) {
318 return internal_error("previous strtab load failed {}", file->path());
319 }
320 }
321 entry.tried_to_load_strtab = true;
322 auto sections_ = get_sections();
323 if(sections_.is_error()) {
324 return std::move(sections_).unwrap_error();
325 }
326 const auto& sections = sections_.unwrap_value();
327 if(index >= sections.size()) {
328 return internal_error("requested strtab section index out of range");
329 }
330 const auto& section = sections[index];
331 if(section.sh_type != SHT_STRTAB) {
332 return internal_error("requested strtab section not a strtab (requested {} of {})", index, file->path());
333 }
334 entry.data.resize(section.sh_size + 1);
335 auto read_res = file->read_bytes(
336 span<char>{entry.data.data(), to<std::size_t>(section.sh_size)},
337 section.sh_offset
338 );
339 if(!read_res) {
340 return read_res.unwrap_error();
341 }
342 entry.data[section.sh_size] = 0; // just out of an abundance of caution
343 entry.did_load_strtab = true;
344 return entry.data;
345 }
346
347 Result<const optional<elf::symtab_info>&, internal_error> elf::get_symtab() {
348 if(did_load_symtab) {
349 return symtab;
350 }
351 if(tried_to_load_symtab) {
352 return internal_error("previous symtab load failed {}", file->path());
353 }
354 tried_to_load_symtab = true;
355 if(is_64) {
356 auto res = get_symtab_impl<64>(false);
357 if(res.has_value()) {
358 symtab = std::move(res).unwrap_value();
359 did_load_symtab = true;
360 return symtab;
361 } else {
362 return std::move(res).unwrap_error();
363 }
364 } else {
365 auto res = get_symtab_impl<32>(false);
366 if(res.has_value()) {
367 symtab = std::move(res).unwrap_value();
368 did_load_symtab = true;
369 return symtab;
370 } else {
371 return std::move(res).unwrap_error();
372 }
373 }
374 }
375
376 Result<const optional<elf::symtab_info>&, internal_error> elf::get_dynamic_symtab() {
377 if(did_load_dynamic_symtab) {
378 return dynamic_symtab;
379 }
380 if(tried_to_load_dynamic_symtab) {
381 return internal_error("previous dynamic symtab load failed {}", file->path());
382 }
383 tried_to_load_dynamic_symtab = true;
384 if(is_64) {
385 auto res = get_symtab_impl<64>(true);
386 if(res.has_value()) {
387 dynamic_symtab = std::move(res).unwrap_value();
388 did_load_dynamic_symtab = true;
389 return dynamic_symtab;
390 } else {
391 return std::move(res).unwrap_error();
392 }
393 } else {
394 auto res = get_symtab_impl<32>(true);
395 if(res.has_value()) {
396 dynamic_symtab = std::move(res).unwrap_value();
397 did_load_dynamic_symtab = true;
398 return dynamic_symtab;
399 } else {
400 return std::move(res).unwrap_error();
401 }
402 }
403 }
404
405 template<std::size_t Bits>
406 Result<optional<elf::symtab_info>, internal_error> elf::get_symtab_impl(bool dynamic) {
407 // https://refspecs.linuxfoundation.org/elf/elf.pdf
408 // page 66: only one sht_symtab and sht_dynsym section per file
409 // page 32: symtab spec
410 static_assert(Bits == 32 || Bits == 64, "Unexpected Bits argument");
411 using SymEntry = typename std::conditional<Bits == 32, Elf32_Sym, Elf64_Sym>::type;
412 auto sections_ = get_sections();
413 if(sections_.is_error()) {
414 return std::move(sections_).unwrap_error();
415 }
416 const auto& sections = sections_.unwrap_value();
417 optional<symtab_info> symbol_table;
418 for(const auto& section : sections) {
419 if(section.sh_type == (dynamic ? SHT_DYNSYM : SHT_SYMTAB)) {
420 if(section.sh_entsize != sizeof(SymEntry)) {
421 return internal_error("elf seems corrupted, sym entry mismatch {}", file->path());
422 }
423 if(section.sh_size % section.sh_entsize != 0) {
424 return internal_error("elf seems corrupted, sym entry vs section size mismatch {}", file->path());
425 }
426 std::vector<SymEntry> buffer(section.sh_size / section.sh_entsize);
427 auto res = file->read_span(make_span(buffer.begin(), buffer.end()), section.sh_offset);
428 if(!res) {
429 return res.unwrap_error();
430 }
431 symbol_table = symtab_info{};
432 symbol_table.unwrap().entries.reserve(buffer.size());
433 for(const auto& entry : buffer) {
434 symtab_entry normalized;
435 normalized.st_name = byteswap_if_needed(entry.st_name);
436 normalized.st_info = byteswap_if_needed(entry.st_info);
437 normalized.st_other = byteswap_if_needed(entry.st_other);
438 normalized.st_shndx = byteswap_if_needed(entry.st_shndx);
439 normalized.st_value = byteswap_if_needed(entry.st_value);
440 normalized.st_size = byteswap_if_needed(entry.st_size);
441 // on arm I've observed zero-size symbols that overlap with symbols we care about
442 // this interferes with some symbol lookup - that could be fixed by enhancing the logic there but
443 // also it's easy to just exclude zero-size symbols here
444 // 1413: 00000000000349e0 0 NOTYPE LOCAL DEFAULT 13 $x
445 // 32341: 00000000000349e0 220 FUNC GLOBAL DEFAULT 13 _Z33stacktrace_from_current_rethrow_3RSt6vectorIiSaIiEE
446 if(normalized.st_size != 0) {
447 symbol_table.unwrap().entries.push_back(normalized);
448 }
449 }
450 std::sort(
451 symbol_table.unwrap().entries.begin(),
452 symbol_table.unwrap().entries.end(),
453 [] (const symtab_entry& a, const symtab_entry& b) {
454 return a.st_value < b.st_value;
455 }
456 );
457 symbol_table.unwrap().strtab_link = section.sh_link;
458 break;
459 }
460 }
461 return symbol_table;
462 }
463
464 Result<maybe_owned<elf>, internal_error> open_elf_cached(const std::string& object_path) {
465 if(object_path.empty()) {
466 return internal_error{"empty object_path"};
467 }
468 if(get_cache_mode() == cache_mode::prioritize_memory) {
469 return elf::open(object_path)
470 .transform([](elf&& obj) { return maybe_owned<elf>{detail::make_unique<elf>(std::move(obj))}; });
471 } else {
472 static std::mutex m;
473 std::unique_lock<std::mutex> lock{m};
474 // TODO: Re-evaluate storing the error
475 static std::unordered_map<std::string, Result<elf, internal_error>> cache;
476 auto it = cache.find(object_path);
477 if(it == cache.end()) {
478 auto res = cache.emplace(object_path, elf::open(object_path));
479 VERIFY(res.second);
480 it = res.first;
481 }
482 return it->second.transform([](elf& obj) { return maybe_owned<elf>(&obj); });
483 }
484 }
485 }
486 CPPTRACE_END_NAMESPACE
487
488 #endif