Class: Cfg2asm::CFG::Disassembler

Inherits:
Object
  • Object
show all
Defined in:
lib/cfg2asm/cfg/disassembler.rb

Overview

Disassemble and print comments from cfg files

Instance Method Summary collapse

Constructor Details

#initialize(out) ⇒ Disassembler

Returns a new instance of Disassembler.



7
8
9
# File 'lib/cfg2asm/cfg/disassembler.rb', line 7

def initialize(out)
  @out = out
end

Instance Method Details

#disassemble(nmethod, print_comments) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/cfg2asm/cfg/disassembler.rb', line 11

def disassemble(nmethod, print_comments)
  require_crabstone

  comments = nmethod.comments
  comments_n = 0

  case [nmethod.code.arch, nmethod.code.arch_width]
  when %w[AMD64 64]
    crabstone_arch = [Crabstone::ARCH_X86, Crabstone::MODE_64]
  when %w[aarch64 64]
    crabstone_arch = [Crabstone::ARCH_ARM64, Crabstone::MODE_ARM]
  else
    raise "Unknown architecture #{nmethod.code.arch} and bit width #{nmethod.code.arch_width}"
  end

  cs = Crabstone::Disassembler.new(*crabstone_arch)
  begin
    cs.disasm(nmethod.code.code, nmethod.code.base).each do |i|
      if print_comments
        # Print comments associated to the instruction.
        last_comment = i.address + i.bytes.length - nmethod.code.base
        while comments_n < comments.length && comments[comments_n].offset < last_comment
          if comments[comments_n].offset == -1
            @out.printf("\t\t\t\t;%<comment>s\n", comment: comments[comments_n].comment)
          else
            @out.printf(
              "\t\t\t\t;Comment %<loc>i:\t%<comment>s\n",
              loc: comments[comments_n].offset,
              comment: comments[comments_n].comment
            )
          end
          comments_n += 1
        end
      end

      # Print the instruction.
      @out.printf(
        "\t0x%<address>x:\t%<instruction>s\t%<details>s\n",
        address: i.address,
        instruction: i.mnemonic,
        details: i.op_str
      )
    end
  rescue StandardError => e
    raise "Disassembly error: #{e.message}"
  ensure
    cs.close
  end
end

#require_crabstoneObject



61
62
63
64
65
66
67
68
69
# File 'lib/cfg2asm/cfg/disassembler.rb', line 61

def require_crabstone
  require 'crabstone'
rescue LoadError => e
  if $DEBUG
    raise e
  else
    raise 'Could not load Capstone - is it installed?'
  end
end