disasm.cpp 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <AK/OwnPtr.h>
  8. #include <AK/QuickSort.h>
  9. #include <AK/Vector.h>
  10. #include <LibCore/ArgsParser.h>
  11. #include <LibCore/MappedFile.h>
  12. #include <LibCore/System.h>
  13. #include <LibELF/Image.h>
  14. #include <LibMain/Main.h>
  15. #include <LibX86/Disassembler.h>
  16. #include <LibX86/ELFSymbolProvider.h>
  17. #include <string.h>
  18. ErrorOr<int> serenity_main(Main::Arguments args)
  19. {
  20. char const* path = nullptr;
  21. Core::ArgsParser args_parser;
  22. args_parser.set_general_help(
  23. "Disassemble an executable, and show human-readable "
  24. "assembly code for each function.");
  25. args_parser.add_positional_argument(path, "Path to i386 binary file", "path");
  26. args_parser.parse(args);
  27. RefPtr<Core::MappedFile> file;
  28. u8 const* asm_data = nullptr;
  29. size_t asm_size = 0;
  30. if ((TRY(Core::System::stat(path))).st_size > 0) {
  31. file = TRY(Core::MappedFile::map(path));
  32. asm_data = static_cast<u8 const*>(file->data());
  33. asm_size = file->size();
  34. }
  35. struct Symbol {
  36. size_t value;
  37. size_t size;
  38. StringView name;
  39. size_t address() const { return value; }
  40. size_t address_end() const { return value + size; }
  41. bool contains(size_t virtual_address) { return address() <= virtual_address && virtual_address < address_end(); }
  42. };
  43. Vector<Symbol> symbols;
  44. size_t file_offset = 0;
  45. Vector<Symbol>::Iterator current_symbol = symbols.begin();
  46. OwnPtr<X86::ELFSymbolProvider> symbol_provider; // nullptr for non-ELF disassembly.
  47. OwnPtr<ELF::Image> elf;
  48. if (asm_size >= 4 && strncmp(reinterpret_cast<char const*>(asm_data), "\u007fELF", 4) == 0) {
  49. elf = make<ELF::Image>(asm_data, asm_size);
  50. if (elf->is_valid()) {
  51. symbol_provider = make<X86::ELFSymbolProvider>(*elf);
  52. elf->for_each_section_of_type(SHT_PROGBITS, [&](ELF::Image::Section const& section) {
  53. // FIXME: Disassemble all SHT_PROGBITS sections, not just .text.
  54. if (section.name() != ".text")
  55. return IterationDecision::Continue;
  56. asm_data = reinterpret_cast<u8 const*>(section.raw_data());
  57. asm_size = section.size();
  58. file_offset = section.address();
  59. return IterationDecision::Break;
  60. });
  61. symbols.ensure_capacity(elf->symbol_count() + 1);
  62. symbols.append({ 0, 0, StringView() }); // Sentinel.
  63. elf->for_each_symbol([&](ELF::Image::Symbol const& symbol) {
  64. symbols.append({ symbol.value(), symbol.size(), symbol.name() });
  65. return IterationDecision::Continue;
  66. });
  67. quick_sort(symbols, [](auto& a, auto& b) {
  68. if (a.value != b.value)
  69. return a.value < b.value;
  70. if (a.size != b.size)
  71. return a.size < b.size;
  72. return a.name < b.name;
  73. });
  74. if constexpr (DISASM_DUMP_DEBUG) {
  75. for (size_t i = 0; i < symbols.size(); ++i)
  76. dbgln("{}: {:p}, {}", symbols[i].name, symbols[i].value, symbols[i].size);
  77. }
  78. }
  79. }
  80. X86::SimpleInstructionStream stream(asm_data, asm_size);
  81. X86::Disassembler disassembler(stream);
  82. bool is_first_symbol = true;
  83. bool current_instruction_is_in_symbol = false;
  84. for (;;) {
  85. auto offset = stream.offset();
  86. auto insn = disassembler.next();
  87. if (!insn.has_value())
  88. break;
  89. // Prefix regions of instructions belonging to a symbol with the symbol's name.
  90. // Separate regions of instructions belonging to distinct symbols with newlines,
  91. // and separate regions of instructions not belonging to symbols from regions belonging to symbols with newlines.
  92. // Interesting cases:
  93. // - More than 1 symbol covering a region of instructions (ICF, D1/D2)
  94. // - Symbols of size 0 that don't cover any instructions but are at an address (want to print them, separated from instructions both before and after)
  95. // Invariant: current_symbol is the largest instruction containing insn, or it is the largest instruction that has an address less than the instruction's address.
  96. size_t virtual_offset = file_offset + offset;
  97. if (current_symbol < symbols.end() && !current_symbol->contains(virtual_offset)) {
  98. if (!is_first_symbol && current_instruction_is_in_symbol) {
  99. // The previous instruction was part of a symbol that doesn't cover the current instruction, so separate it from the current instruction with a newline.
  100. outln();
  101. current_instruction_is_in_symbol = (current_symbol + 1 < symbols.end() && (current_symbol + 1)->contains(virtual_offset));
  102. }
  103. // Try to find symbol covering current instruction, if one exists.
  104. while (current_symbol + 1 < symbols.end() && !(current_symbol + 1)->contains(virtual_offset) && (current_symbol + 1)->address() <= virtual_offset) {
  105. ++current_symbol;
  106. if (!is_first_symbol)
  107. outln("\n({} ({:p}-{:p}))\n", current_symbol->name, current_symbol->address(), current_symbol->address_end());
  108. }
  109. while (current_symbol + 1 < symbols.end() && (current_symbol + 1)->contains(virtual_offset)) {
  110. if (!is_first_symbol && !current_instruction_is_in_symbol)
  111. outln();
  112. ++current_symbol;
  113. current_instruction_is_in_symbol = true;
  114. outln("{} ({:p}-{:p}):", current_symbol->name, current_symbol->address(), current_symbol->address_end());
  115. }
  116. is_first_symbol = false;
  117. }
  118. size_t length = insn.value().length();
  119. StringBuilder builder;
  120. builder.appendff("{: 8x}:\t", virtual_offset);
  121. for (size_t i = 0; i < 7; i++) {
  122. if (i < length)
  123. builder.appendff("{:02x} ", asm_data[offset + i]);
  124. else
  125. builder.append(" "sv);
  126. }
  127. builder.append("\t"sv);
  128. builder.append(insn.value().to_string(virtual_offset, symbol_provider));
  129. outln("{}", builder.string_view());
  130. for (size_t bytes_printed = 7; bytes_printed < length; bytes_printed += 7) {
  131. builder.clear();
  132. builder.appendff("{:p} ", virtual_offset + bytes_printed);
  133. for (size_t i = bytes_printed; i < bytes_printed + 7 && i < length; i++)
  134. builder.appendff(" {:02x}", asm_data[offset + i]);
  135. outln("{}", builder.string_view());
  136. }
  137. }
  138. return 0;
  139. }