Debian Codegraph @

src/binary/mach-o.cpp

raw
1 #include "binary/mach-o.hpp"
2
3 #include "utils/common.hpp"
4 #include "utils/utils.hpp"
5 #include "utils/io/file.hpp"
6 #include "utils/io/memory_file_view.hpp"
7
8 #if IS_APPLE
9
10 // A number of mach-o functions are deprecated as of macos 13
11 #pragma GCC diagnostic push
12 #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
13
14 #include <cstdio>
15 #include <cstring>
16 #include <mutex>
17 #include <string>
18 #include <type_traits>
19 #include <unordered_map>
20 #include <vector>
21
22 #include <iostream>
23 #include <iomanip>
24
25 #include <mach-o/loader.h>
26 #include <mach-o/swap.h>
27 #include <mach-o/fat.h>
28 #include <crt_externs.h>
29 #include <mach-o/nlist.h>
30 #include <mach-o/stab.h>
31 #include <mach-o/arch.h>
32
33 CPPTRACE_BEGIN_NAMESPACE
34 namespace detail {
35 bool is_mach_o(std::uint32_t magic) {
36 switch(magic) {
37 case FAT_MAGIC:
38 case FAT_CIGAM:
39 case MH_MAGIC:
40 case MH_CIGAM:
41 case MH_MAGIC_64:
42 case MH_CIGAM_64:
43 return true;
44 default:
45 return false;
46 }
47 }
48
49 bool file_is_mach_o(cstring_view object_path) noexcept {
50 auto file = raii_wrap(std::fopen(object_path.c_str(), "rb"), file_deleter);
51 if(file == nullptr) {
52 return false;
53 }
54 auto magic = load_bytes<std::uint32_t>(file, 0);
55 if(magic) {
56 return is_mach_o(magic.unwrap_value());
57 } else {
58 return false;
59 }
60 }
61
62 bool is_fat_magic(std::uint32_t magic) {
63 return magic == FAT_MAGIC || magic == FAT_CIGAM;
64 }
65
66 // Based on https://github.com/AlexDenisov/segment_dumper/blob/master/main.c
67 // and https://lowlevelbits.org/parsing-mach-o-files/
68 bool is_magic_64(std::uint32_t magic) {
69 return magic == MH_MAGIC_64 || magic == MH_CIGAM_64;
70 }
71
72 bool should_swap_bytes(std::uint32_t magic) {
73 return magic == MH_CIGAM || magic == MH_CIGAM_64 || magic == FAT_CIGAM;
74 }
75
76 void swap_mach_header(mach_header_64& header) {
77 swap_mach_header_64(&header, NX_UnknownByteOrder);
78 }
79
80 void swap_mach_header(mach_header& header) {
81 swap_mach_header(&header, NX_UnknownByteOrder);
82 }
83
84 void swap_segment_command(segment_command_64& segment) {
85 swap_segment_command_64(&segment, NX_UnknownByteOrder);
86 }
87
88 void swap_segment_command(segment_command& segment) {
89 swap_segment_command(&segment, NX_UnknownByteOrder);
90 }
91
92 void swap_nlist(struct nlist& entry) {
93 swap_nlist(&entry, 1, NX_UnknownByteOrder);
94 }
95
96 void swap_nlist(struct nlist_64& entry) {
97 swap_nlist_64(&entry, 1, NX_UnknownByteOrder);
98 }
99
100 #ifdef __LP64__
101 #define LP(x) x##_64
102 #else
103 #define LP(x) x
104 #endif
105
106 Result<const char*, internal_error> mach_o::symtab_info_data::get_string(std::size_t index) const {
107 if(stringtab && index < symtab.strsize) {
108 return stringtab.unwrap().data() + index;
109 } else {
110 return internal_error("can't retrieve symbol from symtab");
111 }
112 }
113
114 Result<monostate, internal_error> mach_o::load() {
115 if(magic == FAT_MAGIC || magic == FAT_CIGAM) {
116 return load_fat_mach();
117 } else {
118 fat_index = 0;
119 if(is_magic_64(magic)) {
120 return load_mach<64>();
121 } else {
122 return load_mach<32>();
123 }
124 }
125 }
126
127 Result<mach_o, internal_error> mach_o::open(std::unique_ptr<base_file> file) {
128 auto magic = file->read<std::uint32_t>(0);
129 if(!magic) {
130 return magic.unwrap_error();
131 }
132 if(!is_mach_o(magic.unwrap_value())) {
133 return internal_error("File is not mach-o {}", file->path());
134 }
135 mach_o obj(std::move(file), magic.unwrap_value());
136 auto result = obj.load();
137 if(result.is_error()) {
138 return result.unwrap_error();
139 } else {
140 return obj;
141 }
142 }
143
144 Result<mach_o, internal_error> mach_o::open(cstring_view object_path) {
145 auto file_res = file::open(object_path);
146 if(!file_res) {
147 return internal_error("Unable to read object file {}", object_path);
148 }
149 auto& file = file_res.unwrap_value();
150 return open(make_unique(std::move(file)));
151 }
152
153 Result<mach_o, internal_error> mach_o::open(cbspan object) {
154 return open(make_unique<memory_file_view>(object));
155 }
156
157 Result<std::uintptr_t, internal_error> mach_o::get_text_vmaddr() {
158 for(const auto& command : load_commands) {
159 if(command.cmd == LC_SEGMENT_64 || command.cmd == LC_SEGMENT) {
160 auto segment = command.cmd == LC_SEGMENT_64
161 ? load_segment_command<64>(command.file_offset)
162 : load_segment_command<32>(command.file_offset);
163 if(segment.is_error()) {
164 return std::move(segment).unwrap_error();
165 }
166 if(std::strcmp(segment.unwrap_value().segname, "__TEXT") == 0) {
167 return segment.unwrap_value().vmaddr;
168 }
169 }
170 }
171 // somehow no __TEXT section was found...
172 return internal_error("Couldn't find __TEXT section while parsing Mach-O object");
173 }
174
175 std::size_t mach_o::get_fat_index() const {
176 VERIFY(fat_index != std::numeric_limits<std::size_t>::max());
177 return fat_index;
178 }
179
180 void mach_o::print_segments() const {
181 int i = 0;
182 for(const auto& command : load_commands) {
183 if(command.cmd == LC_SEGMENT_64 || command.cmd == LC_SEGMENT) {
184 auto segment_load = command.cmd == LC_SEGMENT_64
185 ? load_segment_command<64>(command.file_offset)
186 : load_segment_command<32>(command.file_offset);
187 fprintf(stderr, "Load command %d\n", i);
188 if(segment_load.is_error()) {
189 fprintf(stderr, " error\n");
190 segment_load.drop_error();
191 continue;
192 }
193 auto& segment = segment_load.unwrap_value();
194 fprintf(stderr, " cmd %u\n", segment.cmd);
195 fprintf(stderr, " cmdsize %u\n", segment.cmdsize);
196 fprintf(stderr, " segname %s\n", segment.segname);
197 fprintf(stderr, " vmaddr 0x%llx\n", segment.vmaddr);
198 fprintf(stderr, " vmsize 0x%llx\n", segment.vmsize);
199 fprintf(stderr, " off 0x%llx\n", segment.fileoff);
200 fprintf(stderr, " filesize %llu\n", segment.filesize);
201 fprintf(stderr, " nsects %u\n", segment.nsects);
202 }
203 i++;
204 }
205 }
206
207 Result<std::vector<mach_o::pc_range>, internal_error> mach_o::get_pc_ranges() {
208 std::vector<pc_range> ranges;
209 for(const auto& command : load_commands) {
210 if(command.cmd == LC_SEGMENT_64 || command.cmd == LC_SEGMENT) {
211 auto segment_res = command.cmd == LC_SEGMENT_64
212 ? load_segment_command<64>(command.file_offset)
213 : load_segment_command<32>(command.file_offset);
214 if(segment_res.is_error()) {
215 return std::move(segment_res).unwrap_error();
216 }
217 auto& segment = segment_res.unwrap_value();
218 if(std::strcmp(segment.segname, "__TEXT") == 0) {
219 ranges.push_back({segment.vmaddr, segment.vmaddr + segment.vmsize});
220 }
221 }
222 }
223 return ranges;
224 }
225
226 Result<std::reference_wrapper<optional<mach_o::symtab_info_data>>, internal_error> mach_o::get_symtab_info() {
227 if(!symtab_info.has_value() && !tried_to_load_symtab) {
228 // don't try to load the symtab again if for some reason loading here fails
229 tried_to_load_symtab = true;
230 for(const auto& command : load_commands) {
231 if(command.cmd == LC_SYMTAB) {
232 symtab_info_data info;
233 auto symtab = load_symbol_table_command(command.file_offset);
234 if(!symtab) {
235 return std::move(symtab).unwrap_error();
236 }
237 info.symtab = symtab.unwrap_value();
238 auto string = load_string_table(info.symtab.stroff, info.symtab.strsize);
239 if(!string) {
240 return std::move(string).unwrap_error();
241 }
242 info.stringtab = std::move(string).unwrap_value();
243 symtab_info = std::move(info);
244 break;
245 }
246 }
247 }
248 return std::reference_wrapper<optional<symtab_info_data>>{symtab_info};
249 }
250
251 void mach_o::print_symbol_table_entry(
252 const nlist_64& entry,
253 const char* stringtab,
254 std::size_t stringsize,
255 std::size_t j
256 ) const {
257 const char* type = "";
258 if(entry.n_type & N_STAB) {
259 switch(entry.n_type) {
260 case N_SO: type = "N_SO"; break;
261 case N_OSO: type = "N_OSO"; break;
262 case N_BNSYM: type = "N_BNSYM"; break;
263 case N_ENSYM: type = "N_ENSYM"; break;
264 case N_FUN: type = "N_FUN"; break;
265 }
266 } else if((entry.n_type & N_TYPE) == N_SECT) {
267 type = "N_SECT";
268 }
269 fprintf(
270 stderr,
271 "%5llu %8llx %2llx %7s %2llu %4llx %16llx %s\n",
272 to_ull(j),
273 to_ull(entry.n_un.n_strx),
274 to_ull(entry.n_type),
275 type,
276 to_ull(entry.n_sect),
277 to_ull(entry.n_desc),
278 to_ull(entry.n_value),
279 stringtab == nullptr
280 ? "Stringtab error"
281 : entry.n_un.n_strx < stringsize
282 ? stringtab + entry.n_un.n_strx
283 : "String index out of bounds"
284 );
285 }
286
287 void mach_o::print_symbol_table() {
288 int i = 0;
289 for(const auto& command : load_commands) {
290 if(command.cmd == LC_SYMTAB) {
291 auto symtab_load = load_symbol_table_command(command.file_offset);
292 fprintf(stderr, "Load command %d\n", i);
293 if(symtab_load.is_error()) {
294 fprintf(stderr, " error\n");
295 symtab_load.drop_error();
296 continue;
297 }
298 auto& symtab = symtab_load.unwrap_value();
299 fprintf(stderr, " cmd %llu\n", to_ull(symtab.cmd));
300 fprintf(stderr, " cmdsize %llu\n", to_ull(symtab.cmdsize));
301 fprintf(stderr, " symoff 0x%llu\n", to_ull(symtab.symoff));
302 fprintf(stderr, " nsyms %llu\n", to_ull(symtab.nsyms));
303 fprintf(stderr, " stroff 0x%llu\n", to_ull(symtab.stroff));
304 fprintf(stderr, " strsize %llu\n", to_ull(symtab.strsize));
305 auto stringtab = load_string_table(symtab.stroff, symtab.strsize);
306 if(!stringtab) {
307 stringtab.drop_error();
308 }
309 for(std::size_t j = 0; j < symtab.nsyms; j++) {
310 auto entry = bits == 32
311 ? load_symtab_entry<32>(symtab.symoff, j)
312 : load_symtab_entry<64>(symtab.symoff, j);
313 if(!entry) {
314 fprintf(stderr, "error loading symtab entry\n");
315 entry.drop_error();
316 continue;
317 }
318 print_symbol_table_entry(
319 entry.unwrap_value(),
320 stringtab ? stringtab.unwrap_value().data() : nullptr,
321 symtab.strsize,
322 j
323 );
324 }
325 }
326 i++;
327 }
328 }
329
330 // produce information similar to dsymutil -dump-debug-map
331 Result<mach_o::debug_map, internal_error> mach_o::get_debug_map() {
332 // we have a bunch of symbols in our binary we need to pair up with symbols from various .o files
333 // first collect symbols and the objects they come from
334 debug_map debug_map;
335 auto symtab_info_res = get_symtab_info();
336 if(!symtab_info_res) {
337 return std::move(symtab_info_res).unwrap_error();
338 }
339 if(!symtab_info_res.unwrap_value().get()) {
340 return internal_error("No symtab info");
341 }
342 const auto& symtab_info = symtab_info_res.unwrap_value().get().unwrap();
343 const auto& symtab = symtab_info.symtab;
344 // TODO: Take timestamp into account?
345 std::string current_module;
346 optional<debug_map_entry> current_function;
347 for(std::size_t j = 0; j < symtab.nsyms; j++) {
348 auto load_entry = bits == 32
349 ? load_symtab_entry<32>(symtab.symoff, j)
350 : load_symtab_entry<64>(symtab.symoff, j);
351 if(!load_entry) {
352 return std::move(load_entry).unwrap_error();
353 }
354 auto& entry = load_entry.unwrap_value();
355 // entry.n_type & N_STAB indicates symbolic debug info
356 if(!(entry.n_type & N_STAB)) {
357 continue;
358 }
359 switch(entry.n_type) {
360 case N_SO:
361 // pass - these encode path and filename for the module, if applicable
362 break;
363 case N_OSO:
364 {
365 // sets the module
366 auto str = symtab_info.get_string(entry.n_un.n_strx);
367 if(!str) {
368 return std::move(str).unwrap_error();
369 }
370 current_module = str.unwrap_value();
371 }
372 break;
373 case N_BNSYM: break; // pass
374 case N_ENSYM: break; // pass
375 case N_FUN:
376 {
377 auto str = symtab_info.get_string(entry.n_un.n_strx);
378 if(!str) {
379 return std::move(str).unwrap_error();
380 }
381 if(str.unwrap_value()[0] == 0) {
382 // end of function scope
383 if(!current_function) { /**/ }
384 current_function.unwrap().size = entry.n_value;
385 debug_map[current_module].push_back(std::move(current_function).unwrap());
386 } else {
387 current_function = debug_map_entry{};
388 current_function.unwrap().source_address = entry.n_value;
389 current_function.unwrap().name = str.unwrap_value();
390 }
391 }
392 break;
393 }
394 }
395 return debug_map;
396 }
397
398 Result<const std::vector<mach_o::symbol_entry>&, internal_error> mach_o::symbol_table() {
399 if(symbols) {
400 return symbols.unwrap();
401 }
402 if(tried_to_load_symbols) {
403 return internal_error("previous symbol table load failed");
404 }
405 tried_to_load_symbols = true;
406 std::vector<symbol_entry> symbol_table;
407 // we have a bunch of symbols in our binary we need to pair up with symbols from various .o files
408 // first collect symbols and the objects they come from
409 auto symtab_info_res = get_symtab_info();
410 if(!symtab_info_res) {
411 return std::move(symtab_info_res).unwrap_error();
412 }
413 if(!symtab_info_res.unwrap_value().get()) {
414 return internal_error("No symtab info");
415 }
416 const auto& symtab_info = symtab_info_res.unwrap_value().get().unwrap();
417 const auto& symtab = symtab_info.symtab;
418 // TODO: Take timestamp into account?
419 for(std::size_t j = 0; j < symtab.nsyms; j++) {
420 auto load_entry = bits == 32
421 ? load_symtab_entry<32>(symtab.symoff, j)
422 : load_symtab_entry<64>(symtab.symoff, j);
423 if(!load_entry) {
424 return std::move(load_entry).unwrap_error();
425 }
426 auto& entry = load_entry.unwrap_value();
427 if(entry.n_type & N_STAB) {
428 continue;
429 }
430 if((entry.n_type & N_TYPE) == N_SECT) {
431 auto str = symtab_info.get_string(entry.n_un.n_strx);
432 if(!str) {
433 return std::move(str).unwrap_error();
434 }
435 symbol_table.push_back({
436 entry.n_value,
437 str.unwrap_value()
438 });
439 }
440 }
441 std::sort(
442 symbol_table.begin(),
443 symbol_table.end(),
444 [] (const symbol_entry& a, const symbol_entry& b) { return a.address < b.address; }
445 );
446 symbols = std::move(symbol_table);
447 return symbols.unwrap();
448 }
449
450 optional<std::string> mach_o::lookup_symbol(frame_ptr pc) {
451 auto symtab_ = symbol_table();
452 if(!symtab_) {
453 return nullopt;
454 }
455 const auto& symtab = symtab_.unwrap_value();;
456 auto it = first_less_than_or_equal(
457 symtab.begin(),
458 symtab.end(),
459 pc,
460 [] (frame_ptr pc, const symbol_entry& entry) {
461 return pc < entry.address;
462 }
463 );
464 if(it == symtab.end()) {
465 return nullopt;
466 }
467 ASSERT(pc >= it->address);
468 // TODO: We subtracted one from the address so name + diff won't show up in the objdump, decide if desirable
469 // to have an easier offset to lookup
470 return microfmt::format("{} + {}", it->name, pc - it->address);
471 }
472
473 // produce information similar to dsymutil -dump-debug-map
474 void mach_o::print_debug_map(const debug_map& debug_map) {
475 for(const auto& entry : debug_map) {
476 std::cout<<entry.first<<": "<< '\n';
477 for(const auto& symbol : entry.second) {
478 std::cerr
479 << " "
480 << symbol.name
481 << " "
482 << std::hex
483 << symbol.source_address
484 << " "
485 << symbol.size
486 << std::dec
487 << '\n';
488 }
489 }
490 }
491
492 template<std::size_t Bits>
493 Result<monostate, internal_error> mach_o::load_mach() {
494 static_assert(Bits == 32 || Bits == 64, "Unexpected Bits argument");
495 bits = Bits;
496 using Mach_Header = typename std::conditional<Bits == 32, mach_header, mach_header_64>::type;
497 std::size_t header_size = sizeof(Mach_Header);
498 auto load_header = file->read<Mach_Header>(load_base);
499 if(!load_header) {
500 return load_header.unwrap_error();
501 }
502 Mach_Header& header = load_header.unwrap_value();
503 magic = header.magic;
504 if(should_swap()) {
505 swap_mach_header(header);
506 }
507 cputype = header.cputype;
508 cpusubtype = header.cpusubtype;
509 filetype = header.filetype;
510 n_load_commands = header.ncmds;
511 sizeof_load_commands = header.sizeofcmds;
512 flags = header.flags;
513 // handle load commands
514 std::uint32_t ncmds = header.ncmds;
515 std::uint32_t load_commands_offset = load_base + header_size;
516 // iterate load commands
517 std::uint32_t actual_offset = load_commands_offset;
518 for(std::uint32_t i = 0; i < ncmds; i++) {
519 auto load_cmd = file->read<load_command>(actual_offset);
520 if(!load_cmd) {
521 return load_cmd.unwrap_error();
522 }
523 load_command& cmd = load_cmd.unwrap_value();
524 if(should_swap()) {
525 swap_load_command(&cmd, NX_UnknownByteOrder);
526 }
527 load_commands.push_back({ actual_offset, cmd.cmd, cmd.cmdsize });
528 actual_offset += cmd.cmdsize;
529 }
530 return monostate{};
531 }
532
533 Result<monostate, internal_error> mach_o::load_fat_mach() {
534 std::size_t header_size = sizeof(fat_header);
535 std::size_t arch_size = sizeof(fat_arch);
536 auto load_header = file->read<fat_header>(0);
537 if(!load_header) {
538 return load_header.unwrap_error();
539 }
540 fat_header& header = load_header.unwrap_value();
541 if(should_swap()) {
542 swap_fat_header(&header, NX_UnknownByteOrder);
543 }
544 // thread_local static struct LP(mach_header)* mhp = _NSGetMachExecuteHeader();
545 // off_t arch_offset = (off_t)header_size;
546 // for(std::size_t i = 0; i < header.nfat_arch; i++) {
547 // fat_arch arch = load_bytes<fat_arch>(file, arch_offset);
548 // if(should_swap()) {
549 // swap_fat_arch(&arch, 1, NX_UnknownByteOrder);
550 // }
551 // off_t mach_header_offset = (off_t)arch.offset;
552 // arch_offset += arch_size;
553 // std::uint32_t magic = load_bytes<std::uint32_t>(file, mach_header_offset);
554 // std::cerr<<"xxx: "<<arch.cputype<<" : "<<mhp->cputype<<std::endl;
555 // std::cerr<<" "<<arch.cpusubtype<<" : "<<static_cast<cpu_subtype_t>(mhp->cpusubtype & ~CPU_SUBTYPE_MASK)<<std::endl;
556 // if(
557 // arch.cputype == mhp->cputype &&
558 // static_cast<cpu_subtype_t>(mhp->cpusubtype & ~CPU_SUBTYPE_MASK) == arch.cpusubtype
559 // ) {
560 // load_base = mach_header_offset;
561 // fat_index = i;
562 // if(is_magic_64(magic)) {
563 // load_mach<64>(true);
564 // } else {
565 // load_mach<32>(true);
566 // }
567 // return;
568 // }
569 // }
570 std::vector<fat_arch> fat_arches;
571 fat_arches.reserve(header.nfat_arch);
572 off_t arch_offset = (off_t)header_size;
573 for(std::size_t i = 0; i < header.nfat_arch; i++) {
574 auto load_arch = file->read<fat_arch>(arch_offset);
575 if(!load_arch) {
576 return load_arch.unwrap_error();
577 }
578 fat_arch& arch = load_arch.unwrap_value();
579 if(should_swap()) {
580 swap_fat_arch(&arch, 1, NX_UnknownByteOrder);
581 }
582 fat_arches.push_back(arch);
583 arch_offset += arch_size;
584 }
585 thread_local static struct LP(mach_header)* mhp = _NSGetMachExecuteHeader();
586 fat_arch* best = NXFindBestFatArch(
587 mhp->cputype,
588 mhp->cpusubtype,
589 fat_arches.data(),
590 header.nfat_arch
591 );
592 if(best) {
593 off_t mach_header_offset = (off_t)best->offset;
594 auto magic = file->read<std::uint32_t>(mach_header_offset);
595 if(!magic) {
596 return magic.unwrap_error();
597 }
598 load_base = mach_header_offset;
599 fat_index = best - fat_arches.data();
600 if(is_magic_64(magic.unwrap_value())) {
601 load_mach<64>();
602 } else {
603 load_mach<32>();
604 }
605 return monostate{};
606 }
607 // If this is reached... something went wrong. The cpu we're on wasn't found.
608 return internal_error("Couldn't find appropriate architecture in fat Mach-O");
609 }
610
611 template<std::size_t Bits>
612 Result<segment_command_64, internal_error> mach_o::load_segment_command(std::uint32_t offset) const {
613 using Segment_Command = typename std::conditional<Bits == 32, segment_command, segment_command_64>::type;
614 auto load_segment = file->read<Segment_Command>(offset);
615 if(!load_segment) {
616 return load_segment.unwrap_error();
617 }
618 Segment_Command& segment = load_segment.unwrap_value();
619 ASSERT(segment.cmd == LC_SEGMENT_64 || segment.cmd == LC_SEGMENT);
620 if(should_swap()) {
621 swap_segment_command(segment);
622 }
623 // fields match just u64 instead of u32
624 segment_command_64 common;
625 common.cmd = segment.cmd;
626 common.cmdsize = segment.cmdsize;
627 static_assert(sizeof common.segname == 16 && sizeof segment.segname == 16, "xx");
628 memcpy(common.segname, segment.segname, 16);
629 common.vmaddr = segment.vmaddr;
630 common.vmsize = segment.vmsize;
631 common.fileoff = segment.fileoff;
632 common.filesize = segment.filesize;
633 common.maxprot = segment.maxprot;
634 common.initprot = segment.initprot;
635 common.nsects = segment.nsects;
636 common.flags = segment.flags;
637 return common;
638 }
639
640 Result<symtab_command, internal_error> mach_o::load_symbol_table_command(std::uint32_t offset) const {
641 auto load_symtab = file->read<symtab_command>(offset);
642 if(!load_symtab) {
643 return load_symtab.unwrap_error();
644 }
645 symtab_command& symtab = load_symtab.unwrap_value();
646 ASSERT(symtab.cmd == LC_SYMTAB);
647 if(should_swap()) {
648 swap_symtab_command(&symtab, NX_UnknownByteOrder);
649 }
650 return symtab;
651 }
652
653 template<std::size_t Bits>
654 Result<nlist_64, internal_error> mach_o::load_symtab_entry(std::uint32_t symbol_base, std::size_t index) const {
655 using Nlist = typename std::conditional<Bits == 32, struct nlist, struct nlist_64>::type;
656 uint32_t offset = load_base + symbol_base + index * sizeof(Nlist);
657 auto load_entry = file->read<Nlist>(offset);
658 if(!load_entry) {
659 return load_entry.unwrap_error();
660 }
661 Nlist& entry = load_entry.unwrap_value();
662 if(should_swap()) {
663 swap_nlist(entry);
664 }
665 // fields match just u64 instead of u32
666 nlist_64 common;
667 common.n_un.n_strx = entry.n_un.n_strx;
668 common.n_type = entry.n_type;
669 common.n_sect = entry.n_sect;
670 common.n_desc = entry.n_desc;
671 common.n_value = entry.n_value;
672 return common;
673 }
674
675 Result<std::vector<char>, internal_error> mach_o::load_string_table(std::uint32_t offset, std::uint32_t byte_count) const {
676 std::vector<char> buffer(byte_count + 1);
677 auto read_res = file->read_bytes(span<char>{buffer.data(), byte_count}, load_base + offset);
678 if(!read_res) {
679 return read_res.unwrap_error();
680 }
681 buffer[byte_count] = 0; // just out of an abundance of caution
682 return buffer;
683 }
684
685 bool mach_o::should_swap() const {
686 return should_swap_bytes(magic);
687 }
688
689 Result<bool, internal_error> macho_is_fat(cstring_view object_path) {
690 auto file = raii_wrap(std::fopen(object_path.c_str(), "rb"), file_deleter);
691 if(file == nullptr) {
692 return internal_error("Unable to read object file {}", object_path);
693 }
694 auto magic = load_bytes<std::uint32_t>(file, 0);
695 if(!magic) {
696 return magic.unwrap_error();
697 } else {
698 return is_fat_magic(magic.unwrap_value());
699 }
700 }
701
702 Result<maybe_owned<mach_o>, internal_error> open_mach_o_cached(const std::string& object_path) {
703 if(object_path.empty()) {
704 return internal_error{"empty object_path"};
705 }
706 if(get_cache_mode() == cache_mode::prioritize_memory) {
707 return mach_o::open(object_path)
708 .transform([](mach_o&& obj) {
709 return maybe_owned<mach_o>{detail::make_unique<mach_o>(std::move(obj))};
710 });
711 } else {
712 static std::mutex m;
713 std::unique_lock<std::mutex> lock{m};
714 // TODO: Re-evaluate storing the error
715 static std::unordered_map<std::string, Result<mach_o, internal_error>> cache;
716 auto it = cache.find(object_path);
717 if(it == cache.end()) {
718 auto res = cache.insert({ object_path, mach_o::open(object_path) });
719 VERIFY(res.second);
720 it = res.first;
721 }
722 return it->second.transform([](mach_o& obj) { return maybe_owned<mach_o>(&obj); });
723 }
724 }
725 }
726 CPPTRACE_END_NAMESPACE
727
728 #pragma GCC diagnostic pop
729
730 #endif