code
stringlengths
26
124k
docstring
stringlengths
23
125k
func_name
stringlengths
1
98
language
stringclasses
1 value
repo
stringlengths
5
53
path
stringlengths
7
151
url
stringlengths
50
211
license
stringclasses
7 values
def c_program_epilog if defined? @need_geteip_stub and @need_geteip_stub return if new_label('metasm_intern_geteip') != 'metasm_intern_geteip' # already defined elsewhere eax = Reg.new(0, @cpusz) label = new_label('geteip') @source << Label.new('metasm_intern_geteip') instr 'call', Expression[label] @source << Label.new(label) instr 'pop', eax instr 'add', eax, Expression['metasm_intern_geteip', :-, label] instr 'ret' end #File.open('m-dbg-precomp.c', 'w') { |fd| fd.puts @parser } #File.open('m-dbg-src.asm', 'w') { |fd| fd.puts @source } end
adds the metasm_intern_geteip function, which returns its own address in eax (used for PIC addressing)
c_program_epilog
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/compile_c.rb
BSD-3-Clause
def dbg_alloc_bphw(dbg, bp) if not bp.internal[:dr] may = [0, 1, 2, 3] dbg.breakpoint_thread.values.each { |bb| may.delete bb.internal[:dr] } raise 'alloc_bphw: no free debugregister' if may.empty? bp.internal[:dr] = may.first end bp.internal[:type] ||= :x bp.internal[:len] ||= 1 bp.internal[:dr] end
allocate a debug register for a hwbp by checking the list of hwbp existing in dbg
dbg_alloc_bphw
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/debug.rb
BSD-3-Clause
def dbg_stacktrace(dbg, rec=500) ret = [] s = dbg.addrname!(dbg.pc) yield(dbg.pc, s) if block_given? ret << [dbg.pc, s] fp = dbg.get_reg_value(dbg_register_list[6]) stack = dbg.get_reg_value(dbg_register_list[7]) - 8 while fp > stack and fp <= stack+0x10000 and rec != 0 rec -= 1 ra = dbg.resolve_expr Indirection[fp+4, 4] s = dbg.addrname!(ra) yield(ra, s) if block_given? ret << [ra, s] stack = fp # ensure we walk the stack upwards fp = dbg.resolve_expr Indirection[fp, 4] end ret end
return (yield) a list of [addr, symbolic name]
dbg_stacktrace
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/debug.rb
BSD-3-Clause
def dbg_func_arg(dbg, argnr) dbg.memory_read_int(Expression[:esp, :+, 4*(argnr+1)]) end
retrieve the current function arguments only valid at function entry (eg right after the call)
dbg_func_arg
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/debug.rb
BSD-3-Clause
def decode_findopcode(edata) di = DecodedInstruction.new self while edata.ptr < edata.data.length pfx = di.instruction.prefix || {} byte = edata.data[edata.ptr] byte = byte.unpack('C').first if byte.kind_of?(::String) return di if di.opcode = @bin_lookaside[byte].find { |op| # fetch the relevant bytes from edata bseq = edata.data[edata.ptr, op.bin.length].unpack('C*') # check against full opcode mask op.bin.zip(bseq, op.bin_mask).all? { |b1, b2, m| b2 and ((b1 & m) == (b2 & m)) } and # check special cases !( # fail if any of those is true (fld = op.fields[:seg2A] and (bseq[fld[0]] >> fld[1]) & @fields_mask[:seg2A] == 1) or (fld = op.fields[:seg3A] and (bseq[fld[0]] >> fld[1]) & @fields_mask[:seg3A] < 4) or (fld = op.fields[:seg3A] || op.fields[:seg3] and (bseq[fld[0]] >> fld[1]) & @fields_mask[:seg3] > 5) or (op.props[:modrmA] and fld = op.fields[:modrm] and (bseq[fld[0]] >> fld[1]) & 0xC0 == 0xC0) or (op.props[:modrmR] and fld = op.fields[:modrm] and (bseq[fld[0]] >> fld[1]) & 0xC0 != 0xC0) or (fld = op.fields[:vex_vvvv] and @size != 64 and (bseq[fld[0]] >> fld[1]) & @fields_mask[:vex_vvvv] < 8) or (sz = op.props[:opsz] and opsz(di, op) != sz) or (sz = op.props[:adsz] and adsz(di, op) != sz) or (ndpfx = op.props[:needpfx] and not pfx[:list].to_a.include? ndpfx) or (pfx[:adsz] and op.props[:adsz] and op.props[:adsz] == @size) or # return non-ambiguous opcode (eg push.i16 in 32bit mode) / sync with addop_post in opcode.rb (pfx[:opsz] and not op.props[:opsz] and (op.args == [:i] or op.args == [:farptr] or op.name == 'ret')) or (pfx[:adsz] and not op.props[:adsz] and (op.props[:strop] or op.props[:stropz] or op.args.include?(:mrm_imm) or op.args.include?(:modrm) or op.name =~ /loop|xlat/)) or (op.name == 'nop' and op.bin[0] == 0x90 and di.instruction.prefix and di.instruction.prefix[:rex_b]) ) } break if not decode_prefix(di.instruction, edata.get_byte) di.bin_length += 1 end end
tries to find the opcode encoded at edata.ptr if no match, tries to match a prefix (update di.instruction.prefix) on match, edata.ptr points to the first byte of the opcode (after prefixes)
decode_findopcode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/decode.rb
BSD-3-Clause
def decode_instr_interpret(di, addr) if di.opcode.props[:setip] and di.instruction.args.last.kind_of? Expression and di.instruction.opname !~ /^i?ret/ delta = di.instruction.args.last.reduce arg = Expression[[addr, :+, di.bin_length], :+, delta].reduce di.instruction.args[-1] = Expression[arg] end di end
converts relative jump/call offsets to absolute addresses adds the eip delta to the offset +off+ of the instruction (may be an Expression) + its bin_length do not call twice on the same di !
decode_instr_interpret
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/decode.rb
BSD-3-Clause
def decode_cc_to_expr(cc) case cc when 'o'; Expression[:eflag_o] when 'no'; Expression[:'!', :eflag_o] when 'b', 'nae', 'c'; Expression[:eflag_c] when 'nb', 'ae', 'nc'; Expression[:'!', :eflag_c] when 'z', 'e'; Expression[:eflag_z] when 'nz', 'ne'; Expression[:'!', :eflag_z] when 'be', 'na'; Expression[:eflag_c, :|, :eflag_z] when 'nbe', 'a'; Expression[:'!', [:eflag_c, :|, :eflag_z]] when 's'; Expression[:eflag_s] when 'ns'; Expression[:'!', :eflag_s] when 'p', 'pe'; Expression::Unknown when 'np', 'po'; Expression::Unknown when 'l', 'nge'; Expression[:eflag_s, :'!=', :eflag_o] when 'nl', 'ge'; Expression[:eflag_s, :==, :eflag_o] when 'le', 'ng'; Expression[[:eflag_s, :'!=', :eflag_o], :|, :eflag_z] when 'nle', 'g'; Expression[[:eflag_s, :==, :eflag_o], :&, :eflag_z] when 'ecxz'; Expression[:'!', register_symbols[1]] when 'cxz'; Expression[:'!', [register_symbols[1], :&, 0xffff]] end end
interprets a condition code (in an opcode name) as an expression involving backtracked eflags eflag_p is never computed, and this returns Expression::Unknown for this flag ex: 'z' => Expression[:eflag_z]
decode_cc_to_expr
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/decode.rb
BSD-3-Clause
def init_backtrace_binding @backtrace_binding ||= {} eax, ecx, edx, ebx, esp, ebp, esi, edi = register_symbols ebx = ebx mask = lambda { |di| (1 << opsz(di))-1 } # 32bits => 0xffff_ffff sign = lambda { |v, di| Expression[[[v, :&, mask[di]], :>>, opsz(di)-1], :'!=', 0] } opcode_list.map { |ol| ol.basename }.uniq.sort.each { |op| binding = case op when 'mov', 'movzx', 'movd', 'movq'; lambda { |di, a0, a1| { a0 => Expression[a1] } } when 'movsx', 'movsxd' lambda { |di, a0, a1| sz1 = di.instruction.args[1].sz sign1 = Expression[[a1, :>>, sz1-1], :&, 1] { a0 => Expression[[a1, :|, [sign1, :*, (-1 << sz1)]], :&, mask[di]] } } when 'lea'; lambda { |di, a0, a1| { a0 => a1.target } } when 'xchg'; lambda { |di, a0, a1| { a0 => Expression[a1], a1 => Expression[a0] } } when 'add', 'sub', 'or', 'xor', 'and', 'pxor', 'adc', 'sbb' lambda { |di, a0, a1| e_op = { 'add' => :+, 'sub' => :-, 'or' => :|, 'and' => :&, 'xor' => :^, 'pxor' => :^, 'adc' => :+, 'sbb' => :- }[op] ret = Expression[a0, e_op, a1] ret = Expression[ret, e_op, :eflag_c] if op == 'adc' or op == 'sbb' # optimises eax ^ eax => 0 # avoid hiding memory accesses (to not hide possible fault) ret = Expression[ret.reduce] if not a0.kind_of? Indirection { a0 => ret } } when 'xadd'; lambda { |di, a0, a1| { a0 => Expression[a0, :+, a1], a1 => Expression[a0] } } when 'inc'; lambda { |di, a0| { a0 => Expression[a0, :+, 1] } } when 'dec'; lambda { |di, a0| { a0 => Expression[a0, :-, 1] } } when 'not'; lambda { |di, a0| { a0 => Expression[a0, :^, mask[di]] } } when 'neg'; lambda { |di, a0| { a0 => Expression[:-, a0] } } when 'rol', 'ror' lambda { |di, a0, a1| e_op = (op[2] == ?r ? :>> : :<<) inv_op = {:<< => :>>, :>> => :<< }[e_op] sz = [a1, :%, opsz(di)] isz = [[opsz(di), :-, a1], :%, opsz(di)] # ror a, b => (a >> b) | (a << (32-b)) { a0 => Expression[[[a0, e_op, sz], :|, [a0, inv_op, isz]], :&, mask[di]] } } when 'sar', 'shl', 'sal'; lambda { |di, a0, a1| { a0 => Expression[a0, (op[-1] == ?r ? :>> : :<<), [a1, :%, [opsz(di), 32].max]] } } when 'shr'; lambda { |di, a0, a1| { a0 => Expression[[a0, :&, mask[di]], :>>, [a1, :%, opsz(di)]] } } when 'cwd', 'cdq', 'cqo'; lambda { |di| { Expression[edx, :&, mask[di]] => Expression[mask[di], :*, sign[eax, di]] } } when 'cbw', 'cwde', 'cdqe'; lambda { |di| o2 = opsz(di)/2 ; m2 = (1 << o2) - 1 { Expression[eax, :&, mask[di]] => Expression[[eax, :&, m2], :|, [m2 << o2, :*, [[eax, :>>, o2-1], :&, 1]]] } } when 'push' lambda { |di, a0| { esp => Expression[esp, :-, opsz(di)/8], Indirection[esp, opsz(di)/8, di.address] => Expression[a0] } } when 'pop' lambda { |di, a0| { esp => Expression[esp, :+, opsz(di)/8], a0 => Indirection[esp, opsz(di)/8, di.address] } } when 'pushfd', 'pushf' # TODO Unknown per bit lambda { |di| efl = Expression[0x202] bts = lambda { |pos, v| efl = Expression[efl, :|, [[v, :&, 1], :<<, pos]] } bts[0, :eflag_c] bts[6, :eflag_z] bts[7, :eflag_s] bts[11, :eflag_o] { esp => Expression[esp, :-, opsz(di)/8], Indirection[esp, opsz(di)/8, di.address] => efl } } when 'popfd', 'popf' lambda { |di| bt = lambda { |pos| Expression[[Indirection[esp, opsz(di)/8, di.address], :>>, pos], :&, 1] } { esp => Expression[esp, :+, opsz(di)/8], :eflag_c => bt[0], :eflag_z => bt[6], :eflag_s => bt[7], :eflag_o => bt[11] } } when 'sahf' lambda { |di| bt = lambda { |pos| Expression[[eax, :>>, pos], :&, 1] } { :eflag_c => bt[0], :eflag_z => bt[6], :eflag_s => bt[7] } } when 'lahf' lambda { |di| efl = Expression[2] bts = lambda { |pos, v| efl = Expression[efl, :|, [[v, :&, 1], :<<, pos]] } bts[0, :eflag_c] #bts[2, :eflag_p] #bts[4, :eflag_a] bts[6, :eflag_z] bts[7, :eflag_s] { eax => efl } } when 'pushad' lambda { |di| ret = {} st_off = 0 register_symbols.reverse_each { |r| ret[Indirection[Expression[esp, :+, st_off].reduce, opsz(di)/8, di.address]] = Expression[r] st_off += opsz(di)/8 } ret[esp] = Expression[esp, :-, st_off] ret } when 'popad' lambda { |di| ret = {} st_off = 0 register_symbols.reverse_each { |r| ret[r] = Indirection[Expression[esp, :+, st_off].reduce, opsz(di)/8, di.address] st_off += opsz(di)/8 } ret[esp] = Expression[esp, :+, st_off] # esp is not popped ret } when 'call' lambda { |di, a0| sz = opsz(di)/8 if a0.kind_of? Farptr { esp => Expression[esp, :-, 2*sz], Indirection[esp, sz, di.address] => Expression[di.next_addr], Indirection[[esp, :+, sz], sz, di.address] => Expression::Unknown } else { esp => Expression[esp, :-, sz], Indirection[esp, sz, di.address] => Expression[di.next_addr] } end } when 'callf' lambda { |di, a0| sz = opsz(di)/8 { esp => Expression[esp, :-, 2*sz], Indirection[esp, sz, di.address] => Expression[di.next_addr], Indirection[[esp, :+, sz], sz, di.address] => Expression::Unknown } } when 'ret'; lambda { |di, *a| { esp => Expression[esp, :+, [opsz(di)/8, :+, a[0] || 0]] } } when 'retf';lambda { |di, *a| { esp => Expression[esp, :+, [opsz(di)/4, :+, a[0] || 0]] } } when 'loop', 'loopz', 'loopnz'; lambda { |di, a0| { ecx => Expression[ecx, :-, 1] } } when 'enter' lambda { |di, a0, a1| sz = opsz(di)/8 depth = a1.reduce % 32 b = { Indirection[ebp, sz, di.address] => Expression[ebp], Indirection[[esp, :+, a0.reduce+sz*depth], sz, di.address] => Expression[ebp], ebp => Expression[esp, :-, sz], esp => Expression[esp, :-, a0.reduce+sz*depth+sz] } (1..depth).each { |i| b[Indirection[[esp, :+, a0.reduce+i*sz], sz, di.address]] = b[Indirection[[ebp, :-, i*sz], sz, di.address]] = Expression::Unknown # TODO Indirection[[ebp, :-, i*sz], sz, di.address] } b } when 'leave'; lambda { |di| { ebp => Indirection[[ebp], opsz(di)/8, di.address], esp => Expression[ebp, :+, opsz(di)/8] } } when 'aaa'; lambda { |di| { eax => Expression::Unknown, :incomplete_binding => Expression[1] } } when 'imul' lambda { |di, *a| if not a[1] # 1 operand from: store result in edx:eax bd = {} m = mask[di] s = opsz(di) e = Expression[Expression.make_signed(Expression[a[0], :&, m], s), :*, Expression.make_signed(Expression[eax, :&, m], s)] if s == 8 bd[Expression[eax, :&, 0xffff]] = e else bd[Expression[eax, :&, m]] = Expression[e, :&, m] bd[Expression[edx, :&, m]] = Expression[[e, :>>, opsz(di)], :&, m] end # XXX eflags? next bd end if a[2]; e = Expression[a[1], :*, a[2]] else e = Expression[[a[0], :*, a[1]], :&, (1 << (di.instruction.args.first.sz || opsz(di))) - 1] end { a[0] => e } } when 'mul' lambda { |di, *a| m = mask[di] e = Expression[a, :*, [eax, :&, m]] if opsz(di) == 8 { Expression[eax, :&, 0xffff] => e } else { Expression[eax, :&, m] => Expression[e, :&, m], Expression[edx, :&, m] => Expression[[e, :>>, opsz(di)], :&, m] } end } when 'div', 'idiv'; lambda { |di, *a| { eax => Expression::Unknown, edx => Expression::Unknown, :incomplete_binding => Expression[1] } } when 'rdtsc'; lambda { |di| { eax => Expression::Unknown, edx => Expression::Unknown, :incomplete_binding => Expression[1] } } when /^(stos|movs|lods|scas|cmps)[bwd]$/ lambda { |di, *a| next {:incomplete_binding => 1} if di.opcode.args.include?(:regxmm) # XXX movsd xmm0, xmm1... op =~ /^(stos|movs|lods|scas|cmps)([bwd])$/ e_op = $1 sz = { 'b' => 1, 'w' => 2, 'd' => 4 }[$2] eax_ = Reg.new(0, 8*sz).symbolic dir = :+ if di.block and (di.block.list.find { |ddi| ddi.opcode.name == 'std' } rescue nil) dir = :- end pesi = Indirection[esi, sz, di.address] pedi = Indirection[edi, sz, di.address] pfx = di.instruction.prefix || {} bd = case e_op when 'movs' case pfx[:rep] when nil; { pedi => pesi, esi => Expression[esi, dir, sz], edi => Expression[edi, dir, sz] } else { pedi => pesi, esi => Expression[esi, dir, [sz ,:*, ecx]], edi => Expression[edi, dir, [sz, :*, ecx]], ecx => 0 } end when 'stos' case pfx[:rep] when nil; { pedi => Expression[eax_], edi => Expression[edi, dir, sz] } else { pedi => Expression[eax_], edi => Expression[edi, dir, [sz, :*, ecx]], ecx => 0 } end when 'lods' case pfx[:rep] when nil; { eax_ => pesi, esi => Expression[esi, dir, sz] } else { eax_ => Indirection[[esi, dir, [sz, :*, [ecx, :-, 1]]], sz, di.address], esi => Expression[esi, dir, [sz, :*, ecx]], ecx => 0 } end when 'scas' case pfx[:rep] when nil; { edi => Expression[edi, dir, sz] } else { edi => Expression::Unknown, ecx => Expression::Unknown } end when 'cmps' case pfx[:rep] when nil; { edi => Expression[edi, dir, sz], esi => Expression[esi, dir, sz] } else { edi => Expression::Unknown, esi => Expression::Unknown, ecx => Expression::Unknown } end end bd[:incomplete_binding] = Expression[1] if pfx[:rep] bd } when 'clc'; lambda { |di| { :eflag_c => Expression[0] } } when 'stc'; lambda { |di| { :eflag_c => Expression[1] } } when 'cmc'; lambda { |di| { :eflag_c => Expression[:'!', :eflag_c] } } when 'cld'; lambda { |di| { :eflag_d => Expression[0] } } when 'std'; lambda { |di| { :eflag_d => Expression[1] } } when 'setalc'; lambda { |di| { Reg.new(0, 8).symbolic => Expression[:eflag_c, :*, 0xff] } } when /^set/; lambda { |di, *a| { a[0] => Expression[decode_cc_to_expr(op[/^set(.*)/, 1])] } } when /^cmov/; lambda { |di, *a| fl = decode_cc_to_expr(op[/^cmov(.*)/, 1]) ; { a[0] => Expression[[fl, :*, a[1]], :|, [[1, :-, fl], :*, a[0]]] } } when /^j/ lambda { |di, a0| ret = { 'dummy_metasm_0' => Expression[a0] } # mark modr/m as read if fl = decode_cc_to_expr(op[/^j(.*)/, 1]) and fl != Expression::Unknown ret['dummy_metasm_1'] = fl # mark eflags as read end ret } when 'fstenv', 'fnstenv' lambda { |di, a0| # stores the address of the last non-control fpu instr run lastfpuinstr = di.block.list[0...di.block.list.index(di)].reverse.find { |pdi| case pdi.opcode.name when /fn?init|fn?clex|fldcw|fn?st[cs]w|fn?stenv|fldenv|fn?save|frstor|f?wait/ when /^f/; true end } if di.block lastfpuinstr = lastfpuinstr.address if lastfpuinstr ret = {} save_at = lambda { |off, val| ret[Indirection[a0.target + off, 4, di.address]] = val } save_at[0, Expression::Unknown] save_at[4, Expression::Unknown] save_at[8, Expression::Unknown] save_at[12, lastfpuinstr || Expression::Unknown] save_at[16, Expression::Unknown] save_at[20, Expression::Unknown] save_at[24, Expression::Unknown] ret } when 'bt'; lambda { |di, a0, a1| { :eflag_c => Expression[[a0, :>>, [a1, :%, opsz(di)]], :&, 1] } } when 'bts'; lambda { |di, a0, a1| { :eflag_c => Expression[[a0, :>>, [a1, :%, opsz(di)]], :&, 1], a0 => Expression[a0, :|, [1, :<<, [a1, :%, opsz(di)]]] } } when 'btr'; lambda { |di, a0, a1| { :eflag_c => Expression[[a0, :>>, [a1, :%, opsz(di)]], :&, 1], a0 => Expression[a0, :&, [[1, :<<, [a1, :%, opsz(di)]], :^, mask[di]]] } } when 'btc'; lambda { |di, a0, a1| { :eflag_c => Expression[[a0, :>>, [a1, :%, opsz(di)]], :&, 1], a0 => Expression[a0, :^, [1, :<<, [a1, :%, opsz(di)]]] } } when 'bswap' lambda { |di, a0| case opsz(di) when 64 { a0 => Expression[ [[[[a0, :&, 0xff000000_00000000], :>>, 56], :|, [[a0, :&, 0x00ff0000_00000000], :>>, 40]], :|, [[[a0, :&, 0x0000ff00_00000000], :>>, 24], :|, [[a0, :&, 0x000000ff_00000000], :>>, 8]]], :|, [[[[a0, :&, 0x00000000_ff000000], :<<, 8], :|, [[a0, :&, 0x00000000_00ff0000], :<<, 24]], :|, [[[a0, :&, 0x00000000_0000ff00], :<<, 40], :|, [[a0, :&, 0x00000000_000000ff], :<<, 56]]]] } when 32 { a0 => Expression[ [[[a0, :&, 0xff000000], :>>, 24], :|, [[a0, :&, 0x00ff0000], :>>, 8]], :|, [[[a0, :&, 0x0000ff00], :<<, 8], :|, [[a0, :&, 0x000000ff], :<<, 24]]] } when 16 # bswap ax => mov ax, 0 { a0 => 0 } end } when 'nop', 'pause', 'wait', 'cmp', 'test'; lambda { |di, *a| {} } end # add eflags side-effects full_binding = case op when 'adc', 'add', 'and', 'cmp', 'or', 'sbb', 'sub', 'xor', 'test', 'xadd' lambda { |di, a0, a1| e_op = { 'adc' => :+, 'add' => :+, 'xadd' => :+, 'and' => :&, 'cmp' => :-, 'or' => :|, 'sbb' => :-, 'sub' => :-, 'xor' => :^, 'test' => :& }[op] res = Expression[[a0, :&, mask[di]], e_op, [a1, :&, mask[di]]] res = Expression[res, e_op, :eflag_c] if op == 'adc' or op == 'sbb' ret = (binding ? binding[di, a0, a1] : {}) ret[:eflag_z] = Expression[[res, :&, mask[di]], :==, 0] ret[:eflag_s] = sign[res, di] ret[:eflag_c] = case e_op when :+; Expression[res, :>, mask[di]] when :-; Expression[[a0, :&, mask[di]], :<, [a1, :&, mask[di]]] else Expression[0] end ret[:eflag_o] = case e_op when :+; Expression[[sign[a0, di], :==, sign[a1, di]], :'&&', [sign[a0, di], :'!=', sign[res, di]]] when :-; Expression[[sign[a0, di], :==, [:'!', sign[a1, di]]], :'&&', [sign[a0, di], :'!=', sign[res, di]]] else Expression[0] end ret } when 'inc', 'dec', 'neg', 'shl', 'shr', 'sar', 'ror', 'rol', 'rcr', 'rcl', 'shld', 'shrd' lambda { |di, a0, *a| ret = (binding ? binding[di, a0, *a] : {}) res = ret[a0] || Expression::Unknown ret[:eflag_z] = Expression[[res, :&, mask[di]], :==, 0] ret[:eflag_s] = sign[res, di] case op when 'neg'; ret[:eflag_c] = Expression[[res, :&, mask[di]], :'!=', 0] when 'inc', 'dec' # don't touch carry flag else ret[:eflag_c] = Expression::Unknown # :incomplete_binding ? end ret[:eflag_o] = case op when 'inc'; Expression[[a0, :&, mask[di]], :==, mask[di] >> 1] when 'dec'; Expression[[res , :&, mask[di]], :==, mask[di] >> 1] when 'neg'; Expression[[a0, :&, mask[di]], :==, (mask[di]+1) >> 1] else Expression::Unknown end ret } when 'imul', 'mul', 'idiv', 'div', /^(scas|cmps)[bwdq]$/ lambda { |di, *a| ret = (binding ? binding[di, *a] : {}) ret[:eflag_z] = ret[:eflag_s] = ret[:eflag_c] = ret[:eflag_o] = Expression::Unknown # :incomplete_binding ? ret } end @backtrace_binding[op] ||= full_binding || binding if full_binding || binding } @backtrace_binding end
populate the @backtrace_binding hash with default values
init_backtrace_binding
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/decode.rb
BSD-3-Clause
def get_jump_condition(di) ecx = register_symbols[1] case di.opcode.name when /^j(.*)/ decode_cc_to_expr($1) when /^loop(.+)?/ e = Expression[ecx, :'!=', 0] e = Expression[e, :'||', decode_cc_to_expr($1)] if $1 e end end
returns the condition (bool Expression) under which a conditionnal jump is taken returns nil if not a conditionnal jump backtrace for the condition must include the jump itself (eg loop -> ecx--)
get_jump_condition
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/decode.rb
BSD-3-Clause
def fix_fwdemu_binding(di, fbd) if di.instruction.args.grep(ModRM).find { |m| m.seg and m.symbolic(di).target.lexpr =~ /^segment_base_/ } fbd = fbd.dup fbd[:incomplete_binding] = Expression[1] end case di.opcode.name when 'push', 'call' fbd = fbd.dup sz = opsz(di)/8 esp = register_symbols[4] if i = fbd.delete(Indirection[esp, sz]) fbd[Indirection[[esp, :-, sz], sz]] = i end when 'pop', 'ret' # nothing to do when /^(push|pop|call|ret|enter|leave|stos|movs|lods|scas|cmps)/ fbd = fbd.dup fbd[:incomplete_binding] = Expression[1] # TODO end fbd end
patch a forward binding from the backtrace binding fixes fwdemu for push/pop/call/ret
fix_fwdemu_binding
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/decode.rb
BSD-3-Clause
def get_xrefs_x_jmptable(dasm, di, mrm, sz) # include the symbolic dest for backtrack stuff ret = [Expression[mrm.symbolic(di)]] i = mrm.i if di.block.list.length == 2 and di.block.list[0].opcode.name =~ /^mov/ and a0 = di.block.list[0].instruction.args[0] and a0.respond_to? :symbolic and a0.symbolic == i.symbolic i = di.block.list[0].instruction.args[1] end pb = di.block.from_normal.to_a if pb.length == 1 and pdi = dasm.decoded[pb[0]] and pdi.opcode.name =~ /^jn?be?/ and ppdi = pdi.block.list[-2] and ppdi.opcode.name == 'cmp' and ppdi.instruction.args[0].symbolic == i.symbolic and lim = Expression[ppdi.instruction.args[1]].reduce and lim.kind_of? Integer # cmp eax, 42 ; jbe switch ; switch: jmp [base+4*eax] s = dasm.get_section_at(mrm.imm) lim += 1 if pdi.opcode.name[-1] == ?e lim.times { |v| dasm.add_xref(s[1]+s[0].ptr, Xref.new(:r, di.address, sz/8)) ret << Indirection[[mrm.imm, :+, v*sz/8], sz/8, di.address] s[0].read(sz/8) } l = dasm.auto_label_at(mrm.imm, 'jmp_table', 'xref') replace_instr_arg_immediate(di.instruction, mrm.imm, Expression[l]) # add 'case 1' comments cases = {} ret.each_with_index { |ind, idx| idx -= 1 # ret[0] = symbolic next if idx < 0 a = dasm.backtrace(ind, di.address) if a.length == 1 and a[0].kind_of?(Expression) and addr = a[0].reduce and addr.kind_of?(::Integer) (cases[addr] ||= []) << idx end } cases.each { |addr, list| dasm.add_comment(addr, "case #{list.join(', ')}:") } return ret end puts "unrecognized jmp table pattern, using wild guess for #{di}" if $VERBOSE di.add_comment 'wildguess' if s = dasm.get_section_at(mrm.imm - 3*sz/8) v = -3 else s = dasm.get_section_at(mrm.imm) v = 0 end while s[0].ptr < s[0].length ptr = dasm.normalize s[0].decode_imm("u#{sz}".to_sym, @endianness) diff = Expression[ptr, :-, di.address].reduce if (diff.kind_of? ::Integer and diff.abs < 4096) or (di.opcode.basename == 'call' and ptr != 0 and dasm.get_section_at(ptr)) dasm.add_xref(s[1]+s[0].ptr-sz/8, Xref.new(:r, di.address, sz/8)) ret << Indirection[[mrm.imm, :+, v*sz/8], sz/8, di.address] elsif v > 0 break end v += 1 end ret end
we detected a jmp table (jmp [base+4*idx]) try to return an accurate dest list
get_xrefs_x_jmptable
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/decode.rb
BSD-3-Clause
def backtrace_is_function_return(expr, di=nil) expr = Expression[expr].reduce_rec expr.kind_of? Indirection and expr.len == @size/8 and expr.target == Expression[register_symbols[4]] end
checks if expr is a valid return expression matching the :saveip instruction
backtrace_is_function_return
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/decode.rb
BSD-3-Clause
def backtrace_update_function_binding(dasm, faddr, f, retaddrlist, *wantregs) b = f.backtrace_binding esp, ebp = register_symbols[4, 2] # XXX handle retaddrlist for multiple/mixed thunks if retaddrlist and not dasm.decoded[retaddrlist.first] and di = dasm.decoded[faddr] # no return instruction, must be a thunk : find the last instruction (to backtrace from it) done = [] while ndi = dasm.decoded[di.block.to_subfuncret.to_a.first] || dasm.decoded[di.block.to_normal.to_a.first] and ndi.kind_of? DecodedInstruction and not done.include? ndi.address done << ndi.address di = ndi end if not di.block.to_subfuncret.to_a.first and di.block.to_normal and di.block.to_normal.length > 1 thunklast = di.block.list.last.address end end bt_val = lambda { |r| next if not retaddrlist b[r] = Expression::Unknown # TODO :pending or something ? (for recursive lazy functions) bt = [] retaddrlist.each { |retaddr| bt |= dasm.backtrace(Expression[r], (thunklast ? thunklast : retaddr), :include_start => true, :snapshot_addr => faddr, :origin => retaddr, :from_subfuncret => thunklast) } if bt.length != 1 b[r] = Expression::Unknown else b[r] = bt.first end } if not wantregs.empty? wantregs.each(&bt_val) else if dasm.function_blocks(faddr, true).length < 20 register_symbols.each(&bt_val) else [ebp, esp].each(&bt_val) end end backtrace_update_function_binding_check(dasm, faddr, f, b, &bt_val) b end
updates the function backtrace_binding if the function is big and no specific register is given, do nothing (the binding will be lazily updated later, on demand) XXX assume retaddrlist is either a list of addr of ret or a list with a single entry which is an external function name (thunk)
backtrace_update_function_binding
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/decode.rb
BSD-3-Clause
def backtrace_is_stack_address(expr) Expression[expr].expr_externals.include? register_symbols[4] end
returns true if the expression is an address on the stack
backtrace_is_stack_address
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/decode.rb
BSD-3-Clause
def replace_instr_arg_immediate(i, old, new) i.args.map! { |a| case a when Expression; a == old ? new : Expression[a.bind(old => new).reduce] when ModRM a.imm = (a.imm == old ? new : Expression[a.imm.bind(old => new).reduce]) if a.imm a else a end } end
updates an instruction's argument replacing an expression with another (eg label renamed)
replace_instr_arg_immediate
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/decode.rb
BSD-3-Clause
def decode_c_function_prototype(cp, sym, orig=nil) sym = cp.toplevel.symbol[sym] if sym.kind_of?(::String) df = DecodedFunction.new orig ||= Expression[sym.name] new_bt = lambda { |expr, rlen| df.backtracked_for << BacktraceTrace.new(expr, orig, expr, rlen ? :r : :x, rlen) } # return instr emulation if sym.has_attribute 'noreturn' or sym.has_attribute '__noreturn__' df.noreturn = true else new_bt[Indirection[:esp, @size/8, orig], nil] end # register dirty (XXX assume standard ABI) [:eax, :ecx, :edx].each { |r| df.backtrace_binding.update r => Expression::Unknown } # emulate ret <n> al = cp.typesize[:ptr] stackoff = al if sym.has_attribute 'fastcall' stackoff = sym.type.args.to_a[2..-1].to_a.inject(al) { |sum, a| sum += (cp.sizeof(a) + al - 1) / al * al } elsif sym.has_attribute 'stdcall' stackoff = sym.type.args.to_a.inject(al) { |sum, a| sum += (cp.sizeof(a) + al - 1) / al * al } end df.backtrace_binding[:esp] = Expression[:esp, :+, stackoff] # scan args for function pointers # TODO walk structs/unions.. stackoff = al sym.type.args.to_a.each { |a| p = Indirection[[:esp, :+, stackoff], al, orig] stackoff += (cp.sizeof(a) + al - 1) / al * al if a.type.untypedef.kind_of? C::Pointer pt = a.type.untypedef.type.untypedef if pt.kind_of? C::Function new_bt[p, nil] df.backtracked_for.last.detached = true elsif pt.kind_of? C::Struct new_bt[p, al] else new_bt[p, cp.sizeof(nil, pt)] end end } df end
returns a DecodedFunction from a parsed C function prototype TODO rebacktrace already decoded functions (load a header file after dasm finished) TODO walk structs args
decode_c_function_prototype
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/decode.rb
BSD-3-Clause
def disassembler_default_btbind_callback esp = register_symbols[4] lambda { |dasm, bind, funcaddr, calladdr, expr, origin, maxdepth| @dasm_func_default_off ||= {} if off = @dasm_func_default_off[[dasm, calladdr]] bind = bind.merge(esp => Expression[esp, :+, off]) break bind end break bind if not odi = dasm.decoded[origin] or odi.opcode.basename != 'ret' expr = expr.reduce_rec if expr.kind_of? Expression break bind unless expr.kind_of? Indirection and expr.origin == origin break bind unless expr.externals.reject { |e| e =~ /^autostackoffset_/ } == [esp] curfunc = dasm.function[funcaddr] if curfunc.backtrace_binding and tk = curfunc.backtrace_binding[:thunk] and dasm.function[tk] curfunc = dasm.function[tk] end # scan from calladdr for the probable parent function start func_start = nil dasm.backtrace_walk(true, calladdr, false, false, nil, maxdepth) { |ev, foo, h| if ev == :up and h[:sfret] != :subfuncret and di = dasm.decoded[h[:to]] and di.opcode.basename == 'call' func_start = h[:from] break elsif ev == :end # entrypoints are functions too func_start = h[:addr] break end } break bind if not func_start puts "automagic #{Expression[funcaddr]}: found func start for #{dasm.decoded[origin]} at #{Expression[func_start]}" if dasm.debug_backtrace s_off = "autostackoffset_#{Expression[funcaddr]}_#{Expression[calladdr]}" list = dasm.backtrace(expr.bind(esp => Expression[esp, :+, s_off]), calladdr, :include_start => true, :snapshot_addr => func_start, :maxdepth => maxdepth, :origin => origin) # check if this backtrace made us find our binding if off = @dasm_func_default_off[[dasm, calladdr]] bind = bind.merge(esp => Expression[esp, :+, off]) break bind elsif not curfunc.btbind_callback break curfunc.backtrace_binding end e_expr = list.find { |e_expr_| # TODO cleanup this e_expr_ = Expression[e_expr_].reduce_rec next if not e_expr_.kind_of? Indirection off = Expression[[esp, :+, s_off], :-, e_expr_.target].reduce off.kind_of? Integer and off >= @size/8 and off < 10*@size/8 and (off % (@size/8)) == 0 } || list.first e_expr = e_expr.rexpr if e_expr.kind_of? Expression and e_expr.op == :+ and not e_expr.lexpr break bind unless e_expr.kind_of? Indirection off = Expression[[esp, :+, s_off], :-, e_expr.target].reduce if off.kind_of? Expression bd = off.externals.grep(/^autostackoffset_/).inject({}) { |bd_, xt| bd_.update xt => @size/8 } bd.delete s_off if off.bind(bd).reduce == @size/8 # all __cdecl off = @size/8 else # check if all calls are to the same extern func bd.delete_if { |k, v| k !~ /^autostackoffset_#{Expression[funcaddr]}_/ } bd.each_key { |k| bd[k] = 0 } if off.bind(bd).reduce.kind_of? Integer off = off.bind(bd).reduce / (bd.length + 1) end end end if off.kind_of? Integer if off < @size/8 or off > 20*@size/8 or (off % (@size/8)) != 0 puts "autostackoffset: ignoring off #{off} for #{Expression[funcaddr]} from #{dasm.decoded[calladdr]}" if $VERBOSE off = :unknown end end bind = bind.merge esp => Expression[esp, :+, off] if off != :unknown if funcaddr != :default if not off.kind_of? ::Integer #XXX we allow the current function to return, so we should handle the func backtracking its esp #(and other register that are saved and restored in epilog) puts "stackoff #{dasm.decoded[calladdr]} | #{Expression[func_start]} | #{expr} | #{e_expr} | #{off}" if dasm.debug_backtrace else puts "autostackoffset: found #{off} for #{Expression[funcaddr]} from #{dasm.decoded[calladdr]}" if $VERBOSE curfunc.btbind_callback = nil curfunc.backtrace_binding = bind # rebacktrace the return address, so that other unknown funcs that depend on us are solved dasm.backtrace(Indirection[esp, @size/8, origin], origin, :origin => origin) end else if off.kind_of? ::Integer and dasm.decoded[calladdr] puts "autostackoffset: found #{off-@size/8} for #{dasm.decoded[calladdr]}" if $VERBOSE di = dasm.decoded[calladdr] di.comment.delete_if { |c| c =~ /^stackoff=/ } if di.comment di.add_comment "stackoff=#{off-@size/8}" @dasm_func_default_off[[dasm, calladdr]] = off dasm.backtrace(Indirection[esp, @size/8, origin], origin, :origin => origin) elsif cachedoff = @dasm_func_default_off[[dasm, calladdr]] bind[esp] = Expression[esp, :+, cachedoff] elsif off.kind_of? ::Integer dasm.decoded[calladdr].add_comment "stackoff=#{off-@size/8}" end puts "stackoff #{dasm.decoded[calladdr]} | #{Expression[func_start]} | #{expr} | #{e_expr} | #{off}" if dasm.debug_backtrace end bind } end
the lambda for the :default backtrace_binding callback of the disassembler tries to determine the stack offset of unprototyped functions working: checks that origin is a ret, that expr is an indirection from esp and that expr.origin is the ret bt_walk from calladdr until we finds a call into us, and assumes it is the current function start TODO handle foo: call bar ; bar: pop eax ; call <withourcallback> ; ret -> bar is not the function start (foo is) then backtrace expr from calladdr to funcstart (snapshot), using esp -> esp+<stackoffvariable> from the result, compute stackoffvariable (only if trivial) will not work if the current function calls any other unknown function (unless all are __cdecl) will not work if the current function is framed (ebp leave ret): in this case the function will return, but its esp will be unknown if the stack offset is found and funcaddr is a string, fixup the static binding and remove the dynamic binding TODO dynamise thunks bt_for & bt_cb
disassembler_default_btbind_callback
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/decode.rb
BSD-3-Clause
def disassembler_default_btfor_callback lambda { |dasm, btfor, funcaddr, calladdr| if funcaddr != :default; btfor elsif di = dasm.decoded[calladdr] and (di.opcode.name == 'call' or di.opcode.name == 'jmp'); btfor else [] end } end
the :default backtracked_for callback returns empty unless funcaddr is not default or calladdr is a call or a jmp
disassembler_default_btfor_callback
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/decode.rb
BSD-3-Clause
def disassembler_default_func esp = register_symbols[4] cp = new_cparser cp.parse 'void stdfunc(void);' f = decode_c_function_prototype(cp, 'stdfunc', :default) f.backtrace_binding[esp] = Expression[esp, :+, :unknown] f.btbind_callback = disassembler_default_btbind_callback f.btfor_callback = disassembler_default_btfor_callback f end
returns a DecodedFunction suitable for :default uses disassembler_default_bt{for/bind}_callback
disassembler_default_func
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/decode.rb
BSD-3-Clause
def code_binding(dasm, entry, finish=nil) entry = dasm.normalize(entry) finish = dasm.normalize(finish) if finish lastdi = nil binding = {} bt = lambda { |from, expr, inc_start| ret = dasm.backtrace(Expression[expr], from, :snapshot_addr => entry, :include_start => inc_start) ret.length == 1 ? ret.first : Expression::Unknown } # walk blocks, search for finish, scan memory writes todo = [entry] done = [Expression::Unknown] while addr = todo.pop addr = dasm.normalize(addr) next if done.include? addr or addr == finish or not dasm.decoded[addr].kind_of? DecodedInstruction done << addr b = dasm.decoded[addr].block next if b.list.find { |di| a = di.address if a == finish lastdi = b.list[b.list.index(di) - 1] true else # check writes from the instruction get_xrefs_w(dasm, di).each { |waddr, len| # we want the ptr expressed with reg values at entry ptr = bt[a, waddr, false] binding[Indirection[ptr, len, a]] = bt[a, Indirection[waddr, len, a], true] } false end } hasnext = false b.each_to_samefunc(dasm) { |t| hasnext = true if t == finish lastdi = b.list.last else todo << t end } # check end of sequence if not hasnext raise "two-ended code_binding #{lastdi} & #{b.list.last}" if lastdi lastdi = b.list.last if lastdi.opcode.props[:setip] e = get_xrefs_x(dasm, lastdi) raise 'bad code_binding ending' if e.to_a.length != 1 or not lastdi.opcode.props[:stopexec] binding[:ip] = bt[lastdi.address, e.first, false] elsif not lastdi.opcode.props[:stopexec] binding[:ip] = lastdi.next_addr end end end binding.delete_if { |k, v| Expression[k] == Expression[v] } # add register binding raise "no code_binding end" if not lastdi and not finish register_symbols.each { |reg| val = if lastdi; bt[lastdi.address, reg, true] else bt[finish, reg, false] end next if val == Expression[reg] mask = 0xffff_ffff # dont use 1<<@size, because 16bit code may use e.g. edi (through opszoverride) mask = 0xffff_ffff_ffff_ffff if @size == 64 val = Expression[val, :&, mask].reduce binding[reg] = Expression[val] } binding end
computes the binding of the sequence of code starting at entry included the binding is a hash showing the value of modified elements at the end of the code sequence, relative to their value at entry the elements are all the registers and the memory written to if finish is nil, the binding will include :ip, which is the address to be executed next (if it exists) the binding will not include memory access from subfunctions entry should be an entrypoint of the disassembler if finish is nil the code sequence must have only one end, with no to_normal
code_binding
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/decode.rb
BSD-3-Clause
def name_local_vars(dasm, funcaddr) esp = register_symbols[4] func = dasm.function[funcaddr] subs = [] dasm.trace_function_register(funcaddr, esp => 0) { |di, r, off, trace| next if r.to_s =~ /flag/ if di.opcode.name == 'call' and tf = di.block.to_normal.find { |t| dasm.function[t] and dasm.function[t].localvars } subs << [trace[esp], dasm.function[tf].localvars] end di.instruction.args.grep(ModRM).each { |mrm| b = mrm.b || (mrm.i if mrm.s == 1) # its a modrm => b is read, so ignore r/off (not yet applied), use trace only stackoff = trace[b.symbolic] if b next if not stackoff imm = mrm.imm || Expression[0] frameoff = imm + stackoff if frameoff.kind_of?(::Integer) # XXX register args ? non-ABI standard register args ? (eg optimized x64) str = 'var_%X' % (-frameoff) str = 'arg_%X' % (frameoff-@size/8) if frameoff > 0 str = func.get_localvar_stackoff(frameoff, di, str) if func imm = imm.expr if imm.kind_of?(ExpressionString) mrm.imm = ExpressionString.new(imm, str, :stackvar) end } off = off.reduce if off.kind_of?(Expression) next unless off.kind_of?(Integer) off } # if subfunctions are called at a fixed stack offset, rename var_3c -> subarg_0 if func and func.localvars and not subs.empty? and subs.all? { |sb| sb[0] == subs.first[0] } func.localvars.each { |varoff, varname| subargnames = subs.map { |o, sb| sb[varoff-o+@size/8] }.compact if subargnames.uniq.length == 1 varname.replace 'sub'+subargnames[0] end } end end
trace the stack pointer register across a function, rename occurences of esp+XX to esp+var_XX
name_local_vars
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/decode.rb
BSD-3-Clause
def decompile_makestackvars(dasm, funcstart, blocks) oldfuncbd = dasm.address_binding[funcstart] dasm.address_binding[funcstart] = { :esp => :frameptr } # this would suffice, the rest here is just optimisation patched_binding = [funcstart] # list of addresses to cleanup later ebp_frame = true # pretrace esp and ebp for each function block (cleared later) # TODO with more than 1 unknown __stdcall ext func per path, esp -> unknown, which makes very ugly C (*esp-- = 12...); add heuristics ? blocks.each { |block| blockstart = block.address if not dasm.address_binding[blockstart] patched_binding << blockstart dasm.address_binding[blockstart] = {} foo = dasm.backtrace(:esp, blockstart, :snapshot_addr => funcstart) if foo.length == 1 and ee = foo.first and ee.kind_of? Expression and (ee == Expression[:frameptr] or (ee.lexpr == :frameptr and ee.op == :+ and ee.rexpr.kind_of? ::Integer)) dasm.address_binding[blockstart][:esp] = ee end if ebp_frame foo = dasm.backtrace(:ebp, blockstart, :snapshot_addr => funcstart) if foo.length == 1 and ee = foo.first and ee.kind_of? Expression and (ee == Expression[:frameptr] or (ee.lexpr == :frameptr and ee.op == :+ and ee.rexpr.kind_of? ::Integer)) dasm.address_binding[blockstart][:ebp] = ee else ebp_frame = false # func does not use ebp as frame ptr, no need to bt for later blocks end end end yield block } ensure patched_binding.each { |a| dasm.address_binding.delete a } dasm.address_binding[funcstart] = oldfuncbd if oldfuncbd end
temporarily setup dasm.address_binding so that backtracking stack-related offsets resolve in :frameptr (relative to func start)
decompile_makestackvars
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/decompile.rb
BSD-3-Clause
def decompile_func_finddeps(dcmp, blocks, func) deps_r = {} ; deps_w = {} ; deps_to = {} deps_subfunc = {} # things read/written by subfuncs # find read/writes by each block blocks.each { |b, to| deps_r[b] = [] ; deps_w[b] = [] ; deps_to[b] = to deps_subfunc[b] = [] blk = dcmp.dasm.decoded[b].block blk.list.each { |di| a = di.backtrace_binding.values w = [] di.backtrace_binding.keys.each { |k| case k when ::Symbol; w |= [k] else a |= Expression[k].externals # if dword [eax] <- 42, eax is read end } a << :eax if di.opcode.name == 'ret' and (not func.type.kind_of? C::BaseType or func.type.type.name != :void) # standard ABI deps_r[b] |= a.map { |ee| Expression[ee].externals.grep(::Symbol) }.flatten - [:unknown] - deps_w[b] deps_w[b] |= w.map { |ee| Expression[ee].externals.grep(::Symbol) }.flatten - [:unknown] } stackoff = nil blk.each_to_normal { |t| t = dcmp.backtrace_target(t, blk.list.last.address) next if not t = dcmp.c_parser.toplevel.symbol[t] t.type = C::Function.new(C::BaseType.new(:int)) if not t.type.kind_of? C::Function # XXX this may seem a bit extreme, and yes, it is. stackoff ||= Expression[dcmp.dasm.backtrace(:esp, blk.list.last.address, :snapshot_addr => blocks.first[0]).first, :-, :esp].reduce # things that are needed by the subfunction if t.has_attribute('fastcall') a = t.type.args.to_a dep = [:ecx, :edx] dep.shift if not a[0] or a[0].has_attribute('unused') dep.pop if not a[1] or a[1].has_attribute('unused') deps_subfunc[b] |= dep end t.type.args.to_a.each { |arg| if reg = arg.has_attribute('register') deps_subfunc[b] |= [reg.to_sym] end } } if stackoff # last block instr == subfunction call deps_r[b] |= deps_subfunc[b] - deps_w[b] deps_w[b] |= [:eax, :ecx, :edx] # standard ABI end } bt = blocks.transpose roots = bt[0] - bt[1].flatten # XXX jmp 1stblock ? # find regs read and never written (must have been set by caller and are part of the func ABI) uninitialized = lambda { |b, r, done| if not deps_r[b] elsif deps_r[b].include?(r) blk = dcmp.dasm.decoded[b].block bw = [] rdi = blk.list.find { |di| a = di.backtrace_binding.values w = [] di.backtrace_binding.keys.each { |k| case k when ::Symbol; w |= [k] else a |= Expression[k].externals # if dword [eax] <- 42, eax is read end } a << :eax if di.opcode.name == 'ret' and (not func.type.kind_of? C::BaseType or func.type.type.name != :void) # standard ABI next true if (a.map { |ee| Expression[ee].externals.grep(::Symbol) }.flatten - [:unknown] - bw).include? r bw |= w.map { |ee| Expression[ee].externals.grep(::Symbol) }.flatten - [:unknown] false } if r == :eax and (rdi || blk.list.last).opcode.name == 'ret' func.type.type = C::BaseType.new(:void) false elsif rdi and rdi.backtrace_binding[r] false # mov al, 42 ; ret -> don't regarg eax else true end elsif deps_w[b].include?(r) else done << b (deps_to[b] - done).find { |tb| uninitialized[tb, r, done] } end } regargs = [] register_symbols.each { |r| if roots.find { |root| uninitialized[root, r, []] } regargs << r end } # TODO honor user-defined prototype if available (eg no, really, eax is not read in this function returning al) regargs.sort_by { |r| r.to_s }.each { |r| a = C::Variable.new(r.to_s, C::BaseType.new(:int, :unsigned)) a.add_attribute("register(#{r})") func.type.args << a } # remove writes from a block if no following block read the value dw = {} deps_w.each { |b, deps| dw[b] = deps.reject { |dep| ret = true done = [] todo = deps_to[b].dup while a = todo.pop next if done.include? a done << a if not deps_r[a] or deps_r[a].include? dep ret = false break elsif not deps_w[a].include? dep todo.concat deps_to[a] end end ret } } dw end
list variable dependency for each block, remove useless writes returns { blockaddr => [list of vars that are needed by a following block] }
decompile_func_finddeps
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/decompile.rb
BSD-3-Clause
def encode(reg = 0, endianness = :little) reg = reg.val if reg.kind_of? Argument case @adsz when 16; encode16(reg, endianness) when 32; encode32(reg, endianness) end end
The argument is an integer representing the 'reg' field of the mrm caller is responsible for setting the adsz returns an array, 1 element per possible immediate size (for un-reduce()able Expression)
encode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/encode.rb
BSD-3-Clause
def encode_instr_op(program, i, op) base = op.bin.dup oi = op.args.zip(i.args) set_field = lambda { |f, v| v ||= 0 # ST => ST(0) fld = op.fields[f] base[fld[0]] |= v << fld[1] } size = i.prefix[:sz] || @size # # handle prefixes and bit fields # pfx = i.prefix.map { |k, v| case k when :jmp; {:jmp => 0x3e, :nojmp => 0x2e}[v] when :lock; 0xf0 when :rep; {'repnz' => 0xf2, 'repz' => 0xf3, 'rep' => 0xf2}[v] when :jmphint; {'hintjmp' => 0x3e, 'hintnojmp' => 0x2e}[v] when :seg; [0x26, 0x2E, 0x36, 0x3E, 0x64, 0x65][v.val] end }.compact.pack 'C*' if op.name == 'movsx' or op.name == 'movzx' pfx << 0x66 if size == 48-i.args[0].sz elsif op.name == 'crc32' pfx << 0x66 if size == 48-i.args[1].sz else opsz = op.props[:argsz] oi.each { |oa, ia| case oa when :reg, :reg_eax, :modrm, :mrm_imm raise EncodeError, "Incompatible arg size in #{i}" if ia.sz and opsz and opsz != ia.sz opsz = ia.sz end } pfx << 0x66 if (op.props[:opsz] and size == 48 - op.props[:opsz]) or (not op.props[:argsz] and opsz and size == 48 - opsz) opsz ||= op.props[:opsz] end opsz ||= size if op.props[:adsz] and size == 48 - op.props[:adsz] pfx << 0x67 adsz = 48 - size end adsz ||= size # addrsize override / segment override if mrm = i.args.grep(ModRM).first if not op.props[:adsz] and ((mrm.b and mrm.b.sz == 48 - adsz) or (mrm.i and mrm.i.sz == 48 - adsz)) pfx << 0x67 adsz = 48 - adsz end pfx << [0x26, 0x2E, 0x36, 0x3E, 0x64, 0x65][mrm.seg.val] if mrm.seg end # # encode embedded arguments # postponed = [] oi.each { |oa, ia| case oa when :reg, :seg3, :seg3A, :seg2, :seg2A, :eeec, :eeed, :eeet, :regfp, :regmmx, :regxmm, :regymm # field arg set_field[oa, ia.val] pfx << 0x66 if oa == :regmmx and op.props[:xmmx] and ia.sz == 128 when :vexvreg, :vexvxmm, :vexvymm set_field[:vex_vvvv, ia.val ^ 0xf] when :imm_val1, :imm_val3, :reg_cl, :reg_eax, :reg_dx, :regfp0 # implicit else postponed << [oa, ia] end } if !(op.args & [:modrm, :modrmmmx, :modrmxmm, :modrmymm]).empty? # reg field of modrm regval = (base[-1] >> 3) & 7 base.pop end # convert label name for jmp/call/loop to relative offset if op.props[:setip] and op.name[0, 3] != 'ret' and i.args.first.kind_of? Expression postlabel = program.new_label('post'+op.name) target = postponed.first[1] target = target.rexpr if target.kind_of? Expression and target.op == :+ and not target.lexpr postponed.first[1] = Expression[target, :-, postlabel] end pfx << op.props[:needpfx] if op.props[:needpfx] # # append other arguments # ret = EncodedData.new(pfx + base.pack('C*')) postponed.each { |oa, ia| case oa when :farptr; ed = ia.encode(@endianness, "a#{opsz}".to_sym) when :modrm, :modrmmmx, :modrmxmm, :modrmymm if ia.kind_of? ModRM ed = ia.encode(regval, @endianness) if ed.kind_of?(::Array) if ed.length > 1 # we know that no opcode can have more than 1 modrm ary = [] ed.each { |m| ary << (ret.dup << m) } ret = ary next else ed = ed.first end end else ed = ModRM.encode_reg(ia, regval) end when :mrm_imm; ed = ia.imm.encode("a#{adsz}".to_sym, @endianness) when :i8, :u8, :u16; ed = ia.encode(oa, @endianness) when :i; ed = ia.encode("a#{opsz}".to_sym, @endianness) when :i4xmm, :i4ymm; ed = ia.val << 4 # u8 else raise SyntaxError, "Internal error: want to encode field #{oa.inspect} as arg in #{i}" end if ret.kind_of?(::Array) ret.each { |e| e << ed } else ret << ed end } # we know that no opcode with setip accept both modrm and immediate arg, so ret is not an ::Array ret.add_export(postlabel, ret.virtsize) if postlabel ret end
returns all forms of the encoding of instruction i using opcode op program may be used to create a new label for relative jump/call
encode_instr_op
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/encode.rb
BSD-3-Clause
def symbolic(di=nil) s = Sym[@val] if @sz == 8 and to_s[-1] == ?h Expression[[Sym[@val-4], :>>, 8], :&, 0xff] elsif @sz == 8 Expression[s, :&, 0xff] elsif @sz == 16 Expression[s, :&, 0xffff] else s end end
returns a symbolic representation of the register: eax => :eax cx => :ecx & 0xffff ah => (:eax >> 8) & 0xff
symbolic
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/main.rb
BSD-3-Clause
def share?(other) other.val % (other.sz >> 1) == @val % (@sz >> 1) and (other.sz != @sz or @sz != 8 or other.val == @val) end
checks if two registers have bits in common
share?
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/main.rb
BSD-3-Clause
def initialize(adsz, sz, s, i, b, imm, seg = nil) @adsz, @sz = adsz, sz @s, @i = s, i if i @b = b if b @imm = imm if imm @seg = seg if seg end
creates a new ModRM with the specified attributes: - adsz (16/32), sz (8/16/32: byte ptr, word ptr, dword ptr) - s, i, b, imm - segment selector override
initialize
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/main.rb
BSD-3-Clause
def symbolic(di=nil) p = nil p = Expression[p, :+, @b.symbolic(di)] if b p = Expression[p, :+, [@s, :*, @i.symbolic(di)]] if i p = Expression[p, :+, @imm] if imm p = Expression["segment_base_#@seg", :+, p] if seg and seg.val != ((b && (@b.val == 4 || @b.val == 5)) ? 2 : 3) Indirection[p.reduce, @sz/8, (di.address if di)] end
returns the symbolic representation of the ModRM (ie an Indirection) segment selectors are represented as eg "segment_base_fs" not present when same as implicit (ds:edx, ss:esp)
symbolic
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/main.rb
BSD-3-Clause
def initialize(*a) super() @size = (a & [16, 32]).first || 32 a.delete @size @endianness = (a & [:big, :little]).first || :little a.delete @endianness @family = a.pop || :latest raise "Invalid arguments #{a.inspect}" if not a.empty? raise "Invalid Ia32 family #{@family.inspect}" if not respond_to?("init_#@family") end
Create a new instance of an Ia32 cpu arguments (any order) - size in bits (16, 32) [32] - instruction set (386, 486, pentium...) [latest] - endianness [:little]
initialize
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/main.rb
BSD-3-Clause
def tune_prepro(pp, nodefine = false) super(pp) return if nodefine pp.define_weak('_M_IX86', 500) pp.define_weak('_X86_') pp.define_weak('__i386__') end
defines some preprocessor macros to say who we are: _M_IX86 = 500, _X86_, __i386__ pass any value in nodefine to just call super w/o defining anything of our own
tune_prepro
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/main.rb
BSD-3-Clause
def str_to_reg(str) Reg.s_to_i.has_key?(str) ? Reg.from_str(str) : SimdReg.s_to_i.has_key?(str) ? SimdReg.from_str(str) : nil end
returns a Reg/SimdReg object if the arg is a valid register (eg 'ax' => Reg.new(0, 16)) returns nil if str is invalid
str_to_reg
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/main.rb
BSD-3-Clause
def instr_args_regs(i) i = i.instruction if i.kind_of?(DecodedInstruction) i.args.grep(Reg) end
returns the list of Regs in the instruction arguments may be converted into symbols through Reg#symbolic
instr_args_regs
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/main.rb
BSD-3-Clause
def instr_args_memoryptr(i) i = i.instruction if i.kind_of?(DecodedInstruction) i.args.grep(ModRM) end
returns the list of ModRMs in the instruction arguments may be converted into Indirection through ModRM#symbolic
instr_args_memoryptr
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/main.rb
BSD-3-Clause
def instr_args_memoryptr_getbase(mrm) mrm.b || (mrm.i if mrm.s == 1) end
return the 'base' of the ModRM (Reg/nil)
instr_args_memoryptr_getbase
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/main.rb
BSD-3-Clause
def instr_args_memoryptr_setoffset(mrm, imm) mrm.imm = (imm ? Expression[imm] : imm) end
define ModRM offset (eg to changing imm into an ExpressionString)
instr_args_memoryptr_setoffset
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/main.rb
BSD-3-Clause
def init_386_common_only init_cpu_constants addop_macro1 'adc', 2 addop_macro1 'add', 0 addop_macro1 'and', 4, :unsigned_imm addop 'bswap', [0x0F, 0xC8], :reg addop 'call', [0xE8], nil, :stopexec, :setip, :i, :saveip addop 'call', [0xFF], 2, :stopexec, :setip, :saveip addop('cbw', [0x98]) { |o| o.props[:opsz] = 16 } addop('cwde', [0x98]) { |o| o.props[:opsz] = 32 } addop('cwd', [0x99]) { |o| o.props[:opsz] = 16 } addop('cdq', [0x99]) { |o| o.props[:opsz] = 32 } addop_macro1 'cmp', 7 addop_macrostr 'cmps', [0xA6], :stropz addop 'dec', [0x48], :reg addop 'dec', [0xFE], 1, {:w => [0, 0]} addop 'div', [0xF6], 6, {:w => [0, 0]} addop 'enter', [0xC8], nil, :u16, :u8 addop 'idiv', [0xF6], 7, {:w => [0, 0]} addop 'imul', [0xF6], 5, {:w => [0, 0]} # implicit eax, but different semantic from imul eax, ebx (the implicit version updates edx:eax) addop 'imul', [0x0F, 0xAF], :mrm addop 'imul', [0x69], :mrm, {:s => [0, 1]}, :i addop 'inc', [0x40], :reg addop 'inc', [0xFE], 0, {:w => [0, 0]} addop 'int', [0xCC], nil, :imm_val3, :stopexec addop 'int', [0xCD], nil, :u8 addop_macrotttn 'j', [0x70], nil, :setip, :i8 addop_macrotttn('j', [0x70], nil, :setip, :i8) { |o| o.name << '.i8' } addop_macrotttn 'j', [0x0F, 0x80], nil, :setip, :i addop_macrotttn('j', [0x0F, 0x80], nil, :setip, :i) { |o| o.name << '.i' } addop 'jmp', [0xE9], nil, {:s => [0, 1]}, :setip, :i, :stopexec addop 'jmp', [0xFF], 4, :setip, :stopexec addop 'lea', [0x8D], :mrmA addop 'leave', [0xC9] addop_macrostr 'lods', [0xAC], :strop addop 'loop', [0xE2], nil, :setip, :i8 addop 'loopz', [0xE1], nil, :setip, :i8 addop 'loope', [0xE1], nil, :setip, :i8 addop 'loopnz',[0xE0], nil, :setip, :i8 addop 'loopne',[0xE0], nil, :setip, :i8 addop 'mov', [0xA0], nil, {:w => [0, 0], :d => [0, 1]}, :reg_eax, :mrm_imm addop('mov', [0x88], :mrmw,{:d => [0, 1]}) { |o| o.args.reverse! } addop 'mov', [0xB0], :reg, {:w => [0, 3]}, :i, :unsigned_imm addop 'mov', [0xC6], 0, {:w => [0, 0]}, :i, :unsigned_imm addop_macrostr 'movs', [0xA4], :strop addop 'movsx', [0x0F, 0xBE], :mrmw addop 'movzx', [0x0F, 0xB6], :mrmw addop 'mul', [0xF6], 4, {:w => [0, 0]} addop 'neg', [0xF6], 3, {:w => [0, 0]} addop 'nop', [0x90] addop 'not', [0xF6], 2, {:w => [0, 0]} addop_macro1 'or', 1, :unsigned_imm addop 'pop', [0x58], :reg addop 'pop', [0x8F], 0 addop 'push', [0x50], :reg addop 'push', [0xFF], 6 addop 'push', [0x68], nil, {:s => [0, 1]}, :i, :unsigned_imm addop 'ret', [0xC3], nil, :stopexec, :setip addop 'ret', [0xC2], nil, :stopexec, :u16, :setip addop_macro3 'rol', 0 addop_macro3 'ror', 1 addop_macro3 'sar', 7 addop_macro1 'sbb', 3 addop_macrostr 'scas', [0xAE], :stropz addop_macrotttn('set', [0x0F, 0x90], 0) { |o| o.props[:argsz] = 8 } addop_macrotttn('set', [0x0F, 0x90], :mrm) { |o| o.props[:argsz] = 8 ; o.args.reverse! } # :reg field is unused addop_macro3 'shl', 4 addop_macro3 'sal', 6 addop 'shld', [0x0F, 0xA4], :mrm, :u8 addop 'shld', [0x0F, 0xA5], :mrm, :reg_cl addop_macro3 'shr', 5 addop 'shrd', [0x0F, 0xAC], :mrm, :u8 addop 'shrd', [0x0F, 0xAD], :mrm, :reg_cl addop_macrostr 'stos', [0xAA], :strop addop_macro1 'sub', 5 addop 'test', [0x84], :mrmw addop 'test', [0xA8], nil, {:w => [0, 0]}, :reg_eax, :i, :unsigned_imm addop 'test', [0xF6], 0, {:w => [0, 0]}, :i, :unsigned_imm addop 'xchg', [0x90], :reg, :reg_eax addop('xchg', [0x90], :reg, :reg_eax) { |o| o.args.reverse! } # xchg eax, ebx == xchg ebx, eax) addop 'xchg', [0x86], :mrmw addop('xchg', [0x86], :mrmw) { |o| o.args.reverse! } addop_macro1 'xor', 6, :unsigned_imm end
only most common instructions from the 386 instruction set inexhaustive list : no aaa, arpl, mov crX, call/jmp/ret far, in/out, bts, xchg...
init_386_common_only
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/opcodes.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/opcodes.rb
BSD-3-Clause
def parse_parser_instruction(lexer, instr) case instr.raw.downcase when '.mode', '.bits' lexer.skip_space if tok = lexer.readtok and tok.type == :string and (tok.raw == '16' or tok.raw == '32') @size = tok.raw.to_i lexer.skip_space raise instr, 'syntax error' if ntok = lexer.nexttok and ntok.type != :eol else raise instr, 'invalid cpu mode' end else super(lexer, instr) end end
handles cpu-specific parser instruction, falls back to Ancestor's version if unknown keyword XXX changing the cpu size in the middle of the code may have baaad effects...
parse_parser_instruction
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/parse.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/parse.rb
BSD-3-Clause
def parse_arg_valid?(o, spec, arg) if o.name == 'movsx' or o.name == 'movzx' if not arg.kind_of?(Reg) and not arg.kind_of?(ModRM) return elsif not arg.sz puts "ambiguous arg size for indirection in #{o.name}" if $VERBOSE return elsif spec == :reg # reg=dst, modrm=src (smaller) return (arg.kind_of?(Reg) and arg.sz >= 16) elsif o.props[:argsz] return arg.sz == o.props[:argsz] else return arg.sz == 16 end elsif o.name == 'crc32' if not arg.kind_of?(Reg) and not arg.kind_of?(ModRM) return elsif not arg.sz puts "ambiguous arg size for indirection in #{o.name}" if $VERBOSE return elsif spec == :reg return (arg.kind_of?(Reg) and arg.sz >= 32) elsif o.props[:argsz] return arg.sz == o.props[:argsz] else return arg.sz >= 16 end end return false if arg.kind_of? ModRM and arg.adsz and o.props[:adsz] and arg.adsz != o.props[:adsz] cond = true if s = o.props[:argsz] and (arg.kind_of? Reg or arg.kind_of? ModRM) cond = (!arg.sz or arg.sz == s or spec == :reg_dx) end cond and case spec when :reg; arg.kind_of? Reg and (arg.sz >= 16 or o.props[:argsz]) when :modrm; (arg.kind_of? ModRM or arg.kind_of? Reg) and (!arg.sz or arg.sz >= 16 or o.props[:argsz]) and (!o.props[:modrmA] or arg.kind_of? ModRM) and (!o.props[:modrmR] or arg.kind_of? Reg) when :i; arg.kind_of? Expression when :imm_val1; arg.kind_of? Expression and arg.reduce == 1 when :imm_val3; arg.kind_of? Expression and arg.reduce == 3 when :reg_eax; arg.kind_of? Reg and arg.val == 0 when :reg_cl; arg.kind_of? Reg and arg.val == 1 and arg.sz == 8 when :reg_dx; arg.kind_of? Reg and arg.val == 2 and arg.sz == 16 when :seg3; arg.kind_of? SegReg when :seg3A; arg.kind_of? SegReg and arg.val > 3 when :seg2; arg.kind_of? SegReg and arg.val < 4 when :seg2A; arg.kind_of? SegReg and arg.val < 4 and arg.val != 1 when :eeec; arg.kind_of? CtrlReg when :eeed; arg.kind_of? DbgReg when :eeet; arg.kind_of? TstReg when :mrm_imm; arg.kind_of? ModRM and not arg.s and not arg.i and not arg.b when :farptr; arg.kind_of? Farptr when :regfp; arg.kind_of? FpReg when :regfp0; arg.kind_of? FpReg and (arg.val == nil or arg.val == 0) when :modrmmmx; arg.kind_of? ModRM or (arg.kind_of? SimdReg and (arg.sz == 64 or (arg.sz == 128 and o.props[:xmmx]))) and (!o.props[:modrmA] or arg.kind_of? ModRM) and (!o.props[:modrmR] or arg.kind_of? SimdReg) when :regmmx; arg.kind_of? SimdReg and (arg.sz == 64 or (arg.sz == 128 and o.props[:xmmx])) when :modrmxmm; arg.kind_of? ModRM or (arg.kind_of? SimdReg and arg.sz == 128) and (!o.props[:modrmA] or arg.kind_of? ModRM) and (!o.props[:modrmR] or arg.kind_of? SimdReg) when :regxmm; arg.kind_of? SimdReg and arg.sz == 128 when :modrmymm; arg.kind_of? ModRM or (arg.kind_of? SimdReg and arg.sz == 256) and (!o.props[:modrmA] or arg.kind_of? ModRM) and (!o.props[:modrmR] or arg.kind_of? SimdReg) when :regymm; arg.kind_of? SimdReg and arg.sz == 256 when :vexvreg; arg.kind_of? Reg and arg.sz == @size when :vexvxmm, :i4xmm; arg.kind_of? SimdReg and arg.sz == 128 when :vexvymm, :i4ymm; arg.kind_of? SimdReg and arg.sz == 256 when :i8, :u8, :u16 arg.kind_of? Expression and (o.props[:setip] or Expression.in_range?(arg, spec) != false) # true or nil allowed # jz 0x28282828 may fit in :i8 depending on instr addr else raise EncodeError, "Internal error: unknown argument specification #{spec.inspect}" end end
check if the argument matches the opcode's argument spec
parse_arg_valid?
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/parse.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/parse.rb
BSD-3-Clause
def parse_instruction_fixup(i) if m = i.args.grep(ModRM).first and not m.sz if i.opname == 'movzx' or i.opname == 'movsx' m.sz = 8 else if r = i.args.grep(Reg).first m.sz = r.sz elsif l = opcode_list_byname[i.opname].map { |o| o.props[:argsz] }.uniq and l.length == 1 and l.first m.sz = l.first else # this is also the size of ctrlreg/dbgreg etc # XXX fpu/simd ? m.sz = i.prefix[:sz] || @size end end end if m and not m.adsz if opcode_list_byname[i.opname].all? { |o| o.props[:adsz] } m.adsz = opcode_list_byname[i.opname].first.props[:adsz] else m.adsz = i.prefix[:sz] || @size end end end
fixup the sz of a modrm argument, defaults to other argument size or current cpu mode
parse_instruction_fixup
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/parse.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/parse.rb
BSD-3-Clause
def decode_instr_interpret(di, addr) if di.opcode.props[:setip] and di.instruction.args.last.kind_of? Expression and di.opcode.name[0] != ?t delta = Expression[di.instruction.args.last, :<<, 2].reduce if di.opcode.args.include? :i26 # absolute jump in the 0x3ff_ffff region surrounding next_pc if delta.kind_of? Expression and delta.op == :& and delta.rexpr == 0x3ff_fffc # relocated arg: assume the linker mapped so that instr&target are in the same region arg = Expression[delta.lexpr].reduce else arg = Expression[[[addr, :+, di.bin_length], :&, 0xfc00_0000], :+, delta].reduce end else arg = Expression[[addr, :+, di.bin_length], :+, delta].reduce end di.instruction.args[-1] = Expression[arg] end di end
converts relative branch offsets to absolute addresses else just add the offset +off+ of the instruction + its length (off may be an Expression) assumes edata.ptr points just after the instruction (as decode_instr_op left it) do not call twice on the same di !
decode_instr_interpret
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/mips/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/mips/decode.rb
BSD-3-Clause
def backtrace_found_result(dasm, di, expr, type, len) if di.opcode.name == 'jalr' and di.instruction.args == [:$t9] expr = dasm.normalize(expr) (dasm.address_binding[expr] ||= {})[:$t9] ||= expr end end
make the target of the call know the value of $t9 (specified by the ABI) XXX hackish
backtrace_found_result
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/mips/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/mips/decode.rb
BSD-3-Clause
def decode_instr_interpret(di, addr) if di.opcode.props[:setip] and di.instruction.args.last.kind_of? Expression and di.opcode.name[0] != ?t and di.opcode.name[-1] != ?a arg = Expression[addr, :+, di.instruction.args.last].reduce di.instruction.args[-1] = Expression[arg] end di end
converts relative branch offsets to absolute addresses else just add the offset +off+ of the instruction + its length (off may be an Expression) assumes edata.ptr points just after the instruction (as decode_instr_op left it) do not call twice on the same di !
decode_instr_interpret
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ppc/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ppc/decode.rb
BSD-3-Clause
def decompile_makestackvars(dasm, funcstart, blocks) oldfuncbd = dasm.address_binding[funcstart] dasm.address_binding[funcstart] = { :sp => :frameptr } # this would suffice, the rest here is just optimisation blocks.each { |block| yield block } dasm.address_binding[funcstart] = oldfuncbd if oldfuncbd end
temporarily setup dasm.address_binding so that backtracking stack-related offsets resolve in :frameptr (relative to func start)
decompile_makestackvars
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ppc/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ppc/decompile.rb
BSD-3-Clause
def decompile_func_finddeps(dcmp, blocks, func) deps_r = {} ; deps_w = {} ; deps_to = {} deps_subfunc = {} # things read/written by subfuncs # find read/writes by each block blocks.each { |b, to| deps_r[b] = [] ; deps_w[b] = [] ; deps_to[b] = to deps_subfunc[b] = [] blk = dcmp.dasm.decoded[b].block blk.list.each { |di| a = di.backtrace_binding.values w = [] di.backtrace_binding.keys.each { |k| case k when ::Symbol; w |= [k] else a |= Expression[k].externals # if dword [eax] <- 42, eax is read end } #a << :eax if di.opcode.name == 'ret' # standard ABI deps_r[b] |= a.map { |ee| Expression[ee].externals.grep(::Symbol) }.flatten - [:unknown] - deps_w[b] deps_w[b] |= w.map { |ee| Expression[ee].externals.grep(::Symbol) }.flatten - [:unknown] } stackoff = nil blk.each_to_normal { |t| t = dcmp.backtrace_target(t, blk.list.last.address) next if not t = dcmp.c_parser.toplevel.symbol[t] t.type = C::Function.new(C::BaseType.new(:int)) if not t.type.kind_of? C::Function # XXX this may seem a bit extreme, and yes, it is. stackoff ||= Expression[dcmp.dasm.backtrace(:sp, blk.list.last.address, :snapshot_addr => blocks.first[0]).first, :-, :sp].reduce } if stackoff # last block instr == subfunction call deps_r[b] |= deps_subfunc[b] - deps_w[b] #deps_w[b] |= [:eax, :ecx, :edx] # standard ABI end } # find regs read and never written (must have been set by caller and are part of the func ABI) uninitialized = lambda { |b, r, done| from = deps_to.keys.find_all { |f| deps_to[f].include? b } - done from.empty? or from.find { |f| !deps_w[f].include?(r) and uninitialized[f, r, done + [b]] } } # remove writes from a block if no following block read the value dw = {} deps_w.each { |b, deps| dw[b] = deps.reject { |dep| ret = true done = [] todo = deps_to[b].dup while a = todo.pop next if done.include? a done << a if not deps_r[a] or deps_r[a].include? dep ret = false break elsif not deps_w[a].include? dep todo.concat deps_to[a] end end ret } } dw end
list variable dependency for each block, remove useless writes returns { blockaddr => [list of vars that are needed by a following block] }
decompile_func_finddeps
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ppc/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ppc/decompile.rb
BSD-3-Clause
def addop_branch(nbase, bin, *argprops) nbase += 'ctr' if argprops.delete :ctr nbase += 'lr' if argprops.delete :lr addop(nbase, bin, :setip, *argprops) addop(nbase+'l', bin|1, :setip, :saveip, *argprops) return if nbase[-2, 2] == 'lr' or nbase[-3, 3] == 'ctr' addop(nbase+'a', bin|2, :setip, *argprops) addop(nbase+'la', bin|3, :setip, :saveip, *argprops) end
generate l/a variations, add :setip/:saveip, include lr/ctr in opname
addop_branch
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ppc/opcodes.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ppc/opcodes.rb
BSD-3-Clause
def transfer_size_mode(list) return list if list.find { |op| not op.name.include? 'mov' } @transfersz == 0 ? list.find_all { |op| op.name.include? 'fmov.s' } : list.reject { |op| op.name.include? 'fmov.s' } end
depending on transfert size mode (sz flag), fmov instructions manipulate single ou double precision values instruction aliasing appears when sz is not handled
transfer_size_mode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/sh4/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/sh4/decode.rb
BSD-3-Clause
def precision_mode(list) @fpprecision == 0 ? list.reject { |op| op.args.include? :drn } : list.find_all { |op| op.args.include? :frn } end
when pr flag is set, floating point instructions are executed as double-precision operations thus register pair is used (DRn registers)
precision_mode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/sh4/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/sh4/decode.rb
BSD-3-Clause
def decode_cmp_expr(di, a0, a1) case di.opcode.name when 'cmp/eq'; Expression[a0, :'==', a1] when 'cmp/ge'; Expression[a0, :'>=', a1] # signed when 'cmp/gt'; Expression[a0, :'>', a1] # signed when 'cmp/hi'; Expression[a0, :'>', a1] # unsigned when 'cmp/hs'; Expression[a0, :'>=', a1] # unsigned end end
interprets a condition code (in an opcode name) as an expression
decode_cmp_expr
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/sh4/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/sh4/decode.rb
BSD-3-Clause
def instr(name, *args) # XXX parse_postfix ? @source << Instruction.new(@exeformat.cpu, name, args) end
shortcut to add an instruction to the source
instr
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
BSD-3-Clause
def findreg(sz = @cpusz) caching = @state.cache.keys.grep(Reg).map { |r| r.val } if not regval = (@state.abi_trashregs - @state.used - caching).first || ([*0..@regnummax] - @state.used).first raise 'need more registers! (or a better compiler?)' end getreg(regval, sz) end
returns an available register, tries to find one not in @state.cache do not use with sz==8 (aliasing ah=>esp) does not put it in @state.inuse
findreg
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
BSD-3-Clause
def getreg(regval, sz=@cpusz) flushcachereg(regval) @state.dirty |= [regval] Reg.new(regval, sz) end
returns a Reg from a regval, mark it as dirty, flush old cache dependencies
getreg
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
BSD-3-Clause
def flushcachereg(regval) @state.cache.delete_if { |e, val| case e when Reg; e.val == regval when Address; e = e.modrm ; redo when ModRM; e.b && (e.b.val == regval) or e.i && (e.i.val == regval) end } end
remove the cache keys that depends on the register
flushcachereg
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
BSD-3-Clause
def unuse(*vals) vals.each { |val| val = val.modrm if val.kind_of? Address @state.inuse.delete val } # XXX cache exempt exempt = @state.bound.values.map { |r| r.val } exempt << 4 exempt << 5 if @state.saved_rbp @state.used.delete_if { |regval| next if exempt.include? regval not @state.inuse.find { |val| case val when Reg; val.val == regval when ModRM; (val.b and val.b.val == regval) or (val.i and val.i.val == regval) else raise 'internal error - inuse ' + val.inspect end } } end
removes elements from @state.inuse, free @state.used if unreferenced must be the exact object present in inuse
unuse
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
BSD-3-Clause
def inuse(v) case v when Reg; @state.used |= [v.val] when ModRM @state.used |= [v.i.val] if v.i @state.used |= [v.b.val] if v.b when Address; inuse v.modrm ; return v else return v end @state.inuse |= [v] v end
marks an arg as in use, returns the arg
inuse
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
BSD-3-Clause
def findvar(var) if ret = @state.bound[var] return ret end if ret = @state.cache.index(var) ret = ret.dup inuse ret return ret end sz = 8*sizeof(var) rescue nil # extern char foo[]; case off = @state.offset[var] when C::CExpression # stack, dynamic address # TODO # no need to update state.cache here, never recursive v = raise "find dynamic addr of #{var.name}" when ::Integer # stack # TODO -fomit-frame-pointer ( => state.cache dependant on stack_offset... ) v = ModRM.new(@cpusz, sz, nil, nil, @state.saved_rbp, Expression[-off]) when nil # global if @exeformat.cpu.generate_PIC v = ModRM.new(@cpusz, sz, nil, nil, Reg.from_str('rip'), Expression[var.name, :-, '$_']) else v = ModRM.new(@cpusz, sz, nil, nil, nil, Expression[var.name]) end end case var.type when C::Array; inuse Address.new(v) else inuse v end end
returns a variable storage (ModRM for stack/global, Reg/Composite for register-bound)
findvar
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
BSD-3-Clause
def resolve_address(e) r = e.modrm unuse e if r.imm and not r.b and not r.i reg = r.imm elsif not r.imm and ((not r.b and r.s == 1) or not r.i) reg = r.b || r.i elsif reg = @state.cache.index(e) reg = reg.dup else reg = findreg r.sz = reg.sz instr 'lea', reg, r end inuse reg @state.cache[reg] = e reg end
resolves the Address to Reg/Expr (may encode an 'lea')
resolve_address
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
BSD-3-Clause
def make_volatile(e, type, rsz=@cpusz) if e.kind_of? ModRM or @state.bound.index(e) if type.integral? or type.pointer? oldval = @state.cache[e] unuse e sz = typesize[type.pointer? ? :ptr : type.name]*8 if sz < @cpusz or sz < rsz or e.sz < rsz e2 = inuse findreg(rsz) op = ((type.specifier == :unsigned) ? 'movzx' : 'movsx') op = 'mov' if e.sz == e2.sz if e2.sz == 64 and e.sz == 32 if op == 'movsx' instr 'movsxd', e2, e else instr 'mov', Reg.new(e2.val, 32), e end else instr op, e2, e end else e2 = inuse findreg(sz) instr 'mov', e2, e end @state.cache[e2] = oldval if oldval and e.kind_of? ModRM e2 elsif type.float? raise 'float unhandled' else raise "cannot cast #{e} to #{type}" end elsif e.kind_of? Address make_volatile resolve_address(e), type, rsz elsif e.kind_of? Expression if type.integral? or type.pointer? e2 = inuse findreg instr 'mov', e2, e e2 elsif type.float? raise 'float unhandled' else raise "cannot cast #{e} to #{type}" end else e end end
copies the arg e to a volatile location (register/composite) if it is not already unuses the old storage may return a register bigger than the type size (eg __int8 are stored in full reg size)
make_volatile
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
BSD-3-Clause
def i_to_i32(v) if v.kind_of? Expression and i = v.reduce and i.kind_of?(Integer) i &= 0xffff_ffff_ffff_ffff if i <= 0x7fff_ffff elsif i >= (1<<64)-0x8000_0000 v = Expression[Expression.make_signed(i, 64)] else v = make_volatile(v, C::BaseType.new(:int)) unuse v end end v end
takes an argument, if the argument is an integer that does not fit in an i32, moves it to a temp reg the reg is unused, so use this only right when generating the offending instr (eg cmp, add..)
i_to_i32
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
BSD-3-Clause
def getcc(op, type) case op when :'=='; 'z' when :'!='; 'nz' when :'<' ; 'b' when :'>' ; 'a' when :'<='; 'be' when :'>='; 'ae' else raise "bad comparison op #{op}" end.tr((type.specifier == :unsigned ? '' : 'ab'), 'gl') end
returns the instruction suffix for a comparison operator
getcc
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
BSD-3-Clause
def c_cexpr_inner(expr) case expr when ::Integer; Expression[expr] when C::Variable; findvar(expr) when C::CExpression if not expr.lexpr or not expr.rexpr inuse c_cexpr_inner_nol(expr) else inuse c_cexpr_inner_l(expr) end when C::Label; findvar(C::Variable.new(expr.name, C::Array.new(C::BaseType.new(:void), 1))) else puts "c_ce_i: unsupported #{expr}" if $VERBOSE end end
compiles a c expression, returns an X64 instruction argument
c_cexpr_inner
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
BSD-3-Clause
def c_cexpr_inner_l(expr) case expr.op when :funcall c_cexpr_inner_funcall(expr) when :'+=', :'-=', :'*=', :'/=', :'%=', :'^=', :'&=', :'|=', :'<<=', :'>>=' l = c_cexpr_inner(expr.lexpr) raise 'bad lvalue' if not l.kind_of? ModRM and not @state.bound.index(l) r = c_cexpr_inner(expr.rexpr) op = expr.op.to_s.chop.to_sym c_cexpr_inner_arith(l, op, r, expr.type) l when :'+', :'-', :'*', :'/', :'%', :'^', :'&', :'|', :'<<', :'>>' # both sides are already cast to the same type by the precompiler # XXX fptrs are not #integral? ... if expr.type.integral? and expr.type.name == :ptr and expr.lexpr.type.kind_of? C::BaseType and typesize[expr.lexpr.type.name] == typesize[:ptr] expr.lexpr.type.name = :ptr end l = c_cexpr_inner(expr.lexpr) l = make_volatile(l, expr.type) if not l.kind_of? Address if expr.type.integral? and expr.type.name == :ptr and l.kind_of? Reg unuse l l = Address.new ModRM.new(l.sz, @cpusz, nil, nil, l, nil) inuse l end if l.kind_of? Address and expr.type.integral? l.modrm.imm = nil if l.modrm.imm and not l.modrm.imm.op and l.modrm.imm.rexpr == 0 if l.modrm.b and l.modrm.i and l.modrm.s == 1 and l.modrm.b.val == l.modrm.i.val unuse l.modrm.b if l.modrm.b != l.modrm.i l.modrm.b = nil l.modrm.s = 2 end case expr.op when :+ rexpr = expr.rexpr rexpr = rexpr.rexpr while rexpr.kind_of? C::CExpression and not rexpr.op and rexpr.type.integral? and rexpr.rexpr.kind_of? C::CExpression and rexpr.rexpr.type.integral? and typesize[rexpr.type.name] == typesize[rexpr.rexpr.type.name] if rexpr.kind_of? C::CExpression and rexpr.op == :* and rexpr.lexpr r1 = c_cexpr_inner(rexpr.lexpr) r2 = c_cexpr_inner(rexpr.rexpr) r1, r2 = r2, r1 if r1.kind_of? Expression if r2.kind_of? Expression and [1, 2, 4, 8].include?(rr2 = r2.reduce) case r1 when ModRM, Address, Reg r1 = make_volatile(r1, rexpr.type) if not r1.kind_of? Reg if not l.modrm.i or (l.modrm.i.val == r1.val and l.modrm.s == 1 and rr2 == 1) unuse l, r1, r2 l = Address.new(l.modrm.dup) inuse l l.modrm.i = r1 l.modrm.s = (l.modrm.s || 0) + rr2 return l end end end r = make_volatile(r1, rexpr.type) c_cexpr_inner_arith(r, :*, r2, rexpr.type) else r = c_cexpr_inner(rexpr) end r = resolve_address r if r.kind_of? Address r = make_volatile(r, rexpr.type) if r.kind_of? ModRM case r when Reg unuse l l = Address.new(l.modrm.dup) inuse l if l.modrm.b if not l.modrm.i or (l.modrm.i.val == r.val and l.modrm.s == 1) l.modrm.i = r l.modrm.s = (l.modrm.s || 0) + 1 unuse r return l end else l.modrm.b = r unuse r return l end when Expression unuse l, r l = Address.new(l.modrm.dup) inuse l l.modrm.imm = Expression[l.modrm.imm, :+, r] return l end when :- r = c_cexpr_inner(expr.rexpr) r = resolve_address r if r.kind_of? Address if r.kind_of? Expression unuse l, r l = Address.new(l.modrm.dup) inuse l l.modrm.imm = Expression[l.modrm.imm, :-, r] return l end when :* r = c_cexpr_inner(expr.rexpr) if r.kind_of? Expression and [1, 2, 4, 8].includre?(rr = r.reduce) if l.modrm.b and not l.modrm.i if rr != 1 l.modrm.i = l.modrm.b l.modrm.s = rr l.modrm.imm = Expression[l.modrm.imm, :*, rr] if l.modrm.imm end unuse r return l elsif l.modrm.i and not l.modrm.b and l.modrm.s*rr <= 8 l.modrm.s *= rr l.modrm.imm = Expression[l.modrm.imm, :*, rr] if l.modrm.imm and rr != 1 unuse r return l end end end end l = make_volatile(l, expr.type) if l.kind_of? Address r ||= c_cexpr_inner(expr.rexpr) c_cexpr_inner_arith(l, expr.op, r, expr.type) l when :'=' r = c_cexpr_inner(expr.rexpr) l = c_cexpr_inner(expr.lexpr) raise 'bad lvalue ' + l.inspect if not l.kind_of? ModRM and not @state.bound.index(l) r = resolve_address r if r.kind_of? Address r = make_volatile(r, expr.type) if l.kind_of? ModRM and r.kind_of? ModRM unuse r if expr.type.integral? or expr.type.pointer? if r.kind_of? Address m = r.modrm.dup m.sz = l.sz instr 'lea', l, m else if l.kind_of? ModRM and r.kind_of? Reg and l.sz != r.sz raise if l.sz > r.sz if l.sz == 8 and r.val >= 4 reg = ([0, 1, 2, 3] - @state.used).first if not reg rax = Reg.new(0, r.sz) instr 'push', rax instr 'mov', rax, r instr 'mov', l, Reg.new(rax.val, 8) instr 'pop', rax else flushcachereg(reg) instr 'mov', Reg.new(reg, r.sz), r instr 'mov', l, Reg.new(reg, 8) end else instr 'mov', l, Reg.new(r.val, l.sz) end elsif l.kind_of? ModRM and r.kind_of? Expression and l.sz == 64 rval = r.reduce if !rval.kind_of?(Integer) or rval > 0xffff_ffff or rval < -0x8000_0000 r = make_volatile(r, expr.type) unuse r end instr 'mov', l, r else instr 'mov', l, r end end elsif expr.type.float? raise 'float unhandled' end l when :>, :<, :>=, :<=, :==, :'!=' l = c_cexpr_inner(expr.lexpr) l = make_volatile(l, expr.type) r = c_cexpr_inner(expr.rexpr) unuse r if expr.lexpr.type.integral? or expr.lexpr.type.pointer? instr 'cmp', l, i_to_i32(r) elsif expr.lexpr.type.float? raise 'float unhandled' else raise 'bad comparison ' + expr.to_s end opcc = getcc(expr.op, expr.type) instr 'set'+opcc, Reg.new(l.val, 8) instr 'and', l, 1 l else raise 'unhandled cexpr ' + expr.to_s end end
compiles a CExpression, not arithmetic (assignment, comparison etc)
c_cexpr_inner_l
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
BSD-3-Clause
def c_cexpr_inner_arith_int(l, op, r, type) op = case op when :+; 'add' when :-; 'sub' when :&; 'and' when :|; 'or' when :^; 'xor' when :>>; type.specifier == :unsigned ? 'shr' : 'sar' when :<<; 'shl' when :*; 'mul' when :/; 'div' when :%; 'mod' end case op when 'add', 'sub', 'and', 'or', 'xor' r = make_volatile(r, type) if l.kind_of?(ModRM) and r.kind_of?(ModRM) r = make_volatile(r, type) if r.kind_of?(ModRM) and r.sz != l.sz # add rax, word [moo] unuse r r = Reg.new(r.val, l.sz) if r.kind_of?(Reg) and l.kind_of?(ModRM) and l.sz and l.sz != r.sz # add byte ptr [rax], bl instr op, l, i_to_i32(r) when 'shr', 'sar', 'shl' if r.kind_of? Expression instr op, l, r else # XXX bouh r = make_volatile(r, C::BaseType.new(:__int8, :unsigned)) unuse r if r.val != 1 rcx = Reg.new(1, 64) instr 'xchg', rcx, Reg.new(r.val, 64) l = Reg.new(r.val, l.sz) if l.kind_of? Reg and l.val == 1 end instr op, l, Reg.new(1, 8) instr 'xchg', rcx, Reg.new(r.val, 64) if r.val != 1 end when 'mul' if l.kind_of? ModRM if r.kind_of? Expression ll = findreg instr 'imul', ll, l, r else ll = make_volatile(l, type) unuse ll instr 'imul', ll, r end instr 'mov', l, ll else instr 'imul', l, r end unuse r when 'div', 'mod' lv = l.val if l.kind_of? Reg rax = Reg.from_str 'rax' rdx = Reg.from_str 'rdx' if @state.used.include? rax.val and lv != rax.val instr 'push', rax saved_rax = true end if @state.used.include? rdx.val and lv != rdx.val instr 'push', rdx saved_rdx = true end instr 'mov', rax, l if lv != rax.val if r.kind_of? Expression instr 'push', r rsp = Reg.from_str 'rsp' r = ModRM.new(@cpusz, 64, nil, nil, rsp, nil) need_pop = true end if type.specifier == :unsigned instr 'mov', rdx, Expression[0] instr 'div', r else instr 'cdq' instr 'idiv', r end unuse r instr 'add', rsp, 8 if need_pop if op == 'div' instr 'mov', l, rax if lv != rax.val else instr 'mov', l, rdx if lv != rdx.val end instr 'pop', rdx if saved_rdx instr 'pop', rax if saved_rax end end
compile an integral arithmetic expression, reg-sized
c_cexpr_inner_arith_int
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
BSD-3-Clause
def decode_c_function_prototype(cp, sym, orig=nil) sym = cp.toplevel.symbol[sym] if sym.kind_of?(::String) df = DecodedFunction.new orig ||= Expression[sym.name] new_bt = lambda { |expr, rlen| df.backtracked_for << BacktraceTrace.new(expr, orig, expr, rlen ? :r : :x, rlen) } # return instr emulation if sym.has_attribute 'noreturn' or sym.has_attribute '__noreturn__' df.noreturn = true else new_bt[Indirection[:rsp, @size/8, orig], nil] end # register dirty (MS standard ABI) [:rax, :rcx, :rdx, :r8, :r9, :r10, :r11].each { |r| df.backtrace_binding.update r => Expression::Unknown } if cp.lexer.definition['__MS_X86_64_ABI__'] reg_args = [:rcx, :rdx, :r8, :r9] else reg_args = [:rdi, :rsi, :rdx, :rcx, :r8, :r9] end al = cp.typesize[:ptr] df.backtrace_binding[:rsp] = Expression[:rsp, :+, al] # scan args for function pointers # TODO walk structs/unions.. stackoff = al sym.type.args.to_a.zip(reg_args).each { |a, r| if not r r = Indirection[[:rsp, :+, stackoff], al, orig] stackoff += (cp.sizeof(a) + al - 1) / al * al end if a.type.untypedef.kind_of? C::Pointer pt = a.type.untypedef.type.untypedef if pt.kind_of? C::Function new_bt[r, nil] df.backtracked_for.last.detached = true elsif pt.kind_of? C::Struct new_bt[r, al] else new_bt[r, cp.sizeof(nil, pt)] end end } df end
returns a DecodedFunction from a parsed C function prototype
decode_c_function_prototype
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/decode.rb
BSD-3-Clause
def encode_instr_op(program, i, op) base = op.bin.dup oi = op.args.zip(i.args) set_field = lambda { |f, v| fld = op.fields[f] base[fld[0]] |= v << fld[1] } # # handle prefixes and bit fields # pfx = i.prefix.map { |k, v| case k when :jmp; {:jmp => 0x3e, :nojmp => 0x2e}[v] when :lock; 0xf0 when :rep; {'repnz' => 0xf2, 'repz' => 0xf3, 'rep' => 0xf2}[v] when :jmphint; {'hintjmp' => 0x3e, 'hintnojmp' => 0x2e}[v] when :seg; [0x26, 0x2E, 0x36, 0x3E, 0x64, 0x65][v.val] end }.compact.pack 'C*' rex_w = rex_r = rex_x = rex_b = 0 if op.name == 'movsx' or op.name == 'movzx' or op.name == 'movsxd' case i.args[0].sz when 64; rex_w = 1 when 32 when 16; pfx << 0x66 end elsif op.name == 'crc32' case i.args[1].sz when 64; rex_w = 1 when 32; when 16; pfx << 0x66 end else opsz = op.props[:argsz] || i.prefix[:sz] oi.each { |oa, ia| case oa when :reg, :reg_eax, :modrm, :mrm_imm raise EncodeError, "Incompatible arg size in #{i}" if ia.sz and opsz and opsz != ia.sz opsz = ia.sz end } opsz ||= 64 if op.props[:auto64] opsz = op.props[:opsz] if op.props[:opsz] # XXX ? case opsz when 64; rex_w = 1 if not op.props[:auto64] and (not op.props[:argsz] or op.props[:opsz] == 64) when 32; raise EncodeError, "Incompatible arg size in #{i}" if op.props[:auto64] when 16; pfx << 0x66 end end opsz ||= @size # addrsize override / segment override / rex_bx if mrm = i.args.grep(ModRM).first mrm.encode(0, @endianness) if mrm.b or mrm.i # may reorder b/i, which must be correct for rex rex_b = 1 if mrm.b and mrm.b.val_rex.to_i > 0 rex_x = 1 if mrm.i and mrm.i.val_rex.to_i > 0 pfx << 0x67 if (mrm.b and mrm.b.sz == 32) or (mrm.i and mrm.i.sz == 32) or op.props[:adsz] == 32 pfx << [0x26, 0x2E, 0x36, 0x3E, 0x64, 0x65][mrm.seg.val] if mrm.seg elsif op.props[:adsz] == 32 pfx << 0x67 end # # encode embedded arguments # postponed = [] oi.each { |oa, ia| case oa when :reg set_field[oa, ia.val_enc] if op.fields[:reg][1] == 3 rex_r = ia.val_rex || 0 else rex_b = ia.val_rex || 0 end when :seg3, :seg3A, :seg2, :seg2A, :eeec, :eeed, :eeet, :regfp, :regmmx, :regxmm, :regymm set_field[oa, ia.val & 7] rex_r = 1 if ia.val > 7 pfx << 0x66 if oa == :regmmx and op.props[:xmmx] and ia.sz == 128 when :vexvreg, :vexvxmm, :vexvymm set_field[:vex_vvvv, ia.val ^ 0xf] when :imm_val1, :imm_val3, :reg_cl, :reg_eax, :reg_dx, :regfp0 # implicit when :modrm, :modrmmmx, :modrmxmm, :modrmymm # postpone, but we must set rex now case ia when ModRM ia.encode(0, @endianness) # could swap b/i rex_x = ia.i.val_rex || 0 if ia.i rex_b = ia.b.val_rex || 0 if ia.b when Reg rex_b = ia.val_rex || 0 else rex_b = ia.val >> 3 end postponed << [oa, ia] else postponed << [oa, ia] end } if !(op.args & [:modrm, :modrmmmx, :modrmxmm, :modrmymm]).empty? # reg field of modrm regval = (base[-1] >> 3) & 7 base.pop end # convert label name for jmp/call/loop to relative offset if op.props[:setip] and op.name[0, 3] != 'ret' and i.args.first.kind_of? Expression postlabel = program.new_label('post'+op.name) target = postponed.first[1] target = target.rexpr if target.kind_of? Expression and target.op == :+ and not target.lexpr postponed.first[1] = Expression[target, :-, postlabel] end pfx << op.props[:needpfx] if op.props[:needpfx] if op.fields[:vex_r] set_field[:vex_r, rex_r ^ 1] set_field[:vex_x, rex_x ^ 1] if op.fields[:vex_x] set_field[:vex_b, rex_b ^ 1] if op.fields[:vex_b] set_field[:vex_w, rex_w] if op.fields[:vex_w] elsif rex_r + rex_x + rex_b + rex_w >= 1 or i.args.grep(Reg).find { |r| r.sz == 8 and r.val >= 4 and r.val < 8 } rex = 0x40 rex |= 1 if rex_b == 1 rex |= 2 if rex_x == 1 rex |= 4 if rex_r == 1 rex |= 8 if rex_w == 1 pfx << rex end ret = EncodedData.new(pfx + base.pack('C*')) postponed.each { |oa, ia| case oa when :modrm, :modrmmmx, :modrmxmm, :modrmymm if ia.kind_of? ModRM ed = ia.encode(regval, @endianness) if ed.kind_of?(::Array) if ed.length > 1 # we know that no opcode can have more than 1 modrm ary = [] ed.each { |m| ary << (ret.dup << m) } ret = ary next else ed = ed.first end end else ed = ModRM.encode_reg(ia, regval) end when :mrm_imm; ed = ia.imm.encode("a#{op.props[:adsz] || 64}".to_sym, @endianness) when :i8, :u8, :i16, :u16, :i32, :u32, :i64, :u64; ed = ia.encode(oa, @endianness) when :i type = if opsz == 64 if op.props[:imm64] :a64 else if _ia = ia.reduce and _ia.kind_of?(Integer) and _ia > 0 and (_ia >> 63) == 1 # handle 0xffffffff_ffffffff -> -1, which should fit in i32 ia = Expression[_ia - (1 << 64)] end :i32 end else "a#{opsz}".to_sym end ed = ia.encode(type, @endianness) when :i4xmm, :i4ymm ed = ia.val << 4 # u8 else raise SyntaxError, "Internal error: want to encode field #{oa.inspect} as arg in #{i}" end if ret.kind_of?(::Array) ret.each { |e| e << ed } else ret << ed end } # we know that no opcode with setip accept both modrm and immediate arg, so ret is not an ::Array ret.add_export(postlabel, ret.virtsize) if postlabel ret end
returns all forms of the encoding of instruction i using opcode op program may be used to create a new label for relative jump/call
encode_instr_op
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/encode.rb
BSD-3-Clause
def symbolic(di=nil) s = Sym[@val] s = di.next_addr if s == :rip and di if @sz == 8 and to_s[-1] == ?h Expression[[Sym[@val-16], :>>, 8], :&, 0xff] elsif @sz == 8 Expression[s, :&, 0xff] elsif @sz == 16 Expression[s, :&, 0xffff] elsif @sz == 32 Expression[s, :&, 0xffffffff] else s end end
returns a symbolic representation of the register: cx => :rcx & 0xffff ah => (:rax >> 8) & 0xff XXX in x64, 32bits operations are zero-extended to 64bits (eg mov rax, 0x1234_ffff_ffff ; add eax, 1 => rax == 0
symbolic
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/main.rb
BSD-3-Clause
def share?(other) raise 'TODO' # XXX TODO wtf does formula this do ? other.val % (other.sz >> 1) == @val % (@sz >> 1) and (other.sz != @sz or @sz != 8 or other.val == @val) end
checks if two registers have bits in common
share?
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/main.rb
BSD-3-Clause
def val_enc if @sz == 8 and @val >= 16; @val-12 # ah, bh, ch, dh elsif @val >= 16 # rip else @val & 7 # others end end
returns the part of @val to encode in an instruction field
val_enc
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/main.rb
BSD-3-Clause
def val_rex if @sz == 8 and @val >= 16 # ah, bh, ch, dh: rex forbidden elsif @val >= 16 # rip else @val >> 3 # others end end
returns the part of @val to encode in an instruction's rex prefix
val_rex
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/main.rb
BSD-3-Clause
def initialize(*a) super(:latest) @size = 64 a.delete @size @endianness = (a & [:big, :little]).first || :little a.delete @endianness @family = a.pop || :latest raise "Invalid arguments #{a.inspect}" if not a.empty? raise "Invalid X86_64 family #{@family.inspect}" if not respond_to?("init_#@family") end
Create a new instance of an X86 cpu arguments (any order) - instruction set (386, 486, sse2...) [latest] - endianness [:little]
initialize
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/main.rb
BSD-3-Clause
def tune_prepro(pp) super(pp, :itsmeX64) # ask Ia32's to just call super() pp.define_weak('_M_AMD64') pp.define_weak('_M_X64') pp.define_weak('__amd64__') pp.define_weak('__x86_64__') end
defines some preprocessor macros to say who we are: TODO
tune_prepro
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/main.rb
BSD-3-Clause
def parse_argregclasslist [Reg, SimdReg, SegReg, DbgReg, TstReg, CtrlReg, FpReg] end
needed due to how ruby inheritance works wrt constants
parse_argregclasslist
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/parse.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/parse.rb
BSD-3-Clause
def parse_arg_valid?(o, spec, arg) return if arg.kind_of? ModRM and ((arg.b and arg.b.val == 16 and arg.i) or (arg.i and arg.i.val == 16 and (arg.b or arg.s != 1))) return if arg.kind_of? Reg and arg.sz >= 32 and arg.val == 16 # eip/rip only in modrm return if o.props[:auto64] and arg.respond_to? :sz and arg.sz == 32 # vex c4/c5 return if o.fields[:vex_r] and not o.fields[:vex_b] and (spec == :modrm or spec == :modrmxmm or spec == :modrmymm) and (((arg.kind_of?(SimdReg) or arg.kind_of?(Reg)) and arg.val >= 8) or (arg.kind_of?(ModRM) and ((arg.b and arg.b.val >= 8) or (arg.i and arg.i.val >= 8)))) if o.name == 'movsxd' return if not arg.kind_of? Reg and not arg.kind_of? ModRM arg.sz ||= 32 if spec == :reg return if not arg.kind_of? Reg return arg.sz >= 32 else return arg.sz == 32 end end return if o.name == 'xchg' and spec == :reg and o.args.include?(:reg_eax) and arg.kind_of?(Reg) and arg.sz == 32 and arg.val == 0 super(o, spec, arg) end
check if the argument matches the opcode's argument spec
parse_arg_valid?
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/parse.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/parse.rb
BSD-3-Clause
def decode_findopcode(edata) di = DecodedInstruction.new self while edata.ptr < edata.data.length byte = edata.data[edata.ptr] byte = byte.unpack('C').first if byte.kind_of?(::String) return di if di.opcode = @bin_lookaside[byte].find { |op| # fetch the relevant bytes from edata bseq = edata.data[edata.ptr, op.bin.length].unpack('C*') # check against full opcode mask op.bin.zip(bseq, op.bin_mask).all? { |b1, b2, m| b2 and ((b1 & m) == (b2 & m)) } } if decode_prefix(di.instruction, edata.get_byte) nb = edata.data[edata.ptr] nb = nb.unpack('C').first if nb.kind_of?(::String) case nb when 0xCB # DD CB <disp8> <opcode_pfxCB> [<args>] di.instruction.prefix |= edata.get_byte << 8 di.bin_length += 2 opc = edata.data[edata.ptr+1] opc = opc.unpack('C').first if opc.kind_of?(::String) bseq = [0xCB, opc] # XXX in decode_instr_op, byte[0] is the immediate displacement instead of cb return di if di.opcode = @bin_lookaside[nb].find { |op| op.bin.zip(bseq, op.bin_mask).all? { |b1, b2, m| b2 and ((b1 & m) == (b2 & m)) } } when 0xED di.instruction.prefix = nil end else di.opcode = @unknown_opcode return di end di.bin_length += 1 end end
tries to find the opcode encoded at edata.ptr if no match, tries to match a prefix (update di.instruction.prefix) on match, edata.ptr points to the first byte of the opcode (after prefixes)
decode_findopcode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/z80/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/z80/decode.rb
BSD-3-Clause
def init_backtrace_binding @backtrace_binding ||= {} mask = 0xffff opcode_list.map { |ol| ol.basename }.uniq.sort.each { |op| binding = case op when 'ld'; lambda { |di, a0, a1, *aa| a2 = aa[0] ; a2 ? { a0 => Expression[a1, :+, a2] } : { a0 => Expression[a1] } } when 'ldi'; lambda { |di, a0, a1| hl = (a0 == :a ? a1 : a0) ; { a0 => Expression[a1], hl => Expression[hl, :+, 1] } } when 'ldd'; lambda { |di, a0, a1| hl = (a0 == :a ? a1 : a0) ; { a0 => Expression[a1], hl => Expression[hl, :-, 1] } } when 'add', 'adc', 'sub', 'sbc', 'and', 'xor', 'or' lambda { |di, a0, a1| e_op = { 'add' => :+, 'adc' => :+, 'sub' => :-, 'sbc' => :-, 'and' => :&, 'xor' => :^, 'or' => :| }[op] ret = Expression[a0, e_op, a1] ret = Expression[ret, e_op, :flag_c] if op == 'adc' or op == 'sbc' ret = Expression[ret.reduce] if not a0.kind_of? Indirection { a0 => ret } } when 'cp', 'cmp'; lambda { |di, *a| {} } when 'inc'; lambda { |di, a0| { a0 => Expression[a0, :+, 1] } } when 'dec'; lambda { |di, a0| { a0 => Expression[a0, :-, 1] } } when 'not'; lambda { |di, a0| { a0 => Expression[a0, :^, mask] } } when 'push' lambda { |di, a0| { :sp => Expression[:sp, :-, 2], Indirection[:sp, 2, di.address] => Expression[a0] } } when 'pop' lambda { |di, a0| { :sp => Expression[:sp, :+, 2], a0 => Indirection[:sp, 2, di.address] } } when 'call' lambda { |di, a0| { :sp => Expression[:sp, :-, 2], Indirection[:sp, 2, di.address] => Expression[di.next_addr] } } when 'ret', 'reti'; lambda { |di, *a| { :sp => Expression[:sp, :+, 2] } } # TODO callCC, retCC ... when 'bswap' lambda { |di, a0| { a0 => Expression[ [[a0, :&, 0xff00], :>>, 8], :|, [[a0, :&, 0x00ff], :<<, 8]] } } when 'nop', /^j/; lambda { |di, *a| {} } end # TODO flags ? @backtrace_binding[op] ||= binding if binding } @backtrace_binding end
populate the @backtrace_binding hash with default values
init_backtrace_binding
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/z80/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/z80/decode.rb
BSD-3-Clause
def fix_fwdemu_binding(di, fbd) case di.opcode.name when 'push', 'call'; fbd[Indirection[[:sp, :-, 2], 2]] = fbd.delete(Indirection[:sp, 2]) end fbd end
patch a forward binding from the backtrace binding
fix_fwdemu_binding
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/z80/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/z80/decode.rb
BSD-3-Clause
def backtrace_is_function_return(expr, di=nil) expr = Expression[expr].reduce_rec expr.kind_of?(Indirection) and expr.len == 2 and expr.target == Expression[:sp] end
checks if expr is a valid return expression matching the :saveip instruction
backtrace_is_function_return
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/z80/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/z80/decode.rb
BSD-3-Clause
def backtrace_update_function_binding(dasm, faddr, f, retaddrlist, *wantregs) b = f.backtrace_binding bt_val = lambda { |r| next if not retaddrlist b[r] = Expression::Unknown bt = [] retaddrlist.each { |retaddr| bt |= dasm.backtrace(Expression[r], retaddr, :include_start => true, :snapshot_addr => faddr, :origin => retaddr) } if bt.length != 1 b[r] = Expression::Unknown else b[r] = bt.first end } if not wantregs.empty? wantregs.each(&bt_val) else bt_val[:sp] end b end
updates the function backtrace_binding if the function is big and no specific register is given, do nothing (the binding will be lazily updated later, on demand)
backtrace_update_function_binding
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/z80/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/z80/decode.rb
BSD-3-Clause
def replace_instr_arg_immediate(i, old, new) i.args.map! { |a| case a when Expression; a == old ? new : Expression[a.bind(old => new).reduce] when Memref a.offset = (a.offset == old ? new : Expression[a.offset.bind(old => new).reduce]) if a.offset a else a end } end
updates an instruction's argument replacing an expression with another (eg label renamed)
replace_instr_arg_immediate
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/z80/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/z80/decode.rb
BSD-3-Clause
def init_z80_common @opcode_list = [] @valid_args.update [:i8, :u8, :i16, :u16, :m16, :r_a, :r_af, :r_hl, :r_de, :r_sp, :r_i, :m_bc, :m_de, :m_sp, :m_hl, :mf8, :mfc ].inject({}) { |h, v| h.update v => true } @fields_mask.update :rz => 7, :ry => 7, :rp => 3, :rp2 => 3, :iy => 7, :iy8 => 7 @fields_shift.update :rz => 0, :ry => 3, :rp => 4, :rp2 => 4, :iy => 3, :iy8 => 3 # some opcodes are in init_z80 when they are not part of the GB ABI addop 'nop', [0b00_000_000] addop 'jr', [0b00_011_000], :setip, :stopexec, :i8 %w[nz z nc c].each_with_index { |cc, i| addop 'jr' + cc, [0b00_100_000 | (i << 3)], :setip, :i8 } addop 'ld', [0b00_000_001], :rp, :i16 addop 'add', [0b00_001_001], :r_hl, :rp addop 'ld', [0b00_000_010], :m_bc, :r_a addop 'ld', [0b00_001_010], :r_a, :m_bc addop 'ld', [0b00_010_010], :m_de, :r_a addop 'ld', [0b00_011_010], :r_a, :m_de addop 'inc', [0b00_000_011], :rp addop 'dec', [0b00_001_011], :rp addop 'inc', [0b00_000_100], :ry addop 'dec', [0b00_000_101], :ry addop 'ld', [0b00_000_110], :ry, :i8 addop 'rlca', [0b00_000_111] # rotate addop 'rrca', [0b00_001_111] addop 'rla', [0b00_010_111] addop 'rra', [0b00_011_111] addop 'daa', [0b00_100_111] addop 'cpl', [0b00_101_111] addop 'scf', [0b00_110_111] addop 'ccf', [0b00_111_111] addop 'halt', [0b01_110_110] # ld (HL), (HL) addop 'ld', [0b01_000_000], :ry, :rz addop 'add', [0b10_000_000], :r_a, :rz addop 'adc', [0b10_001_000], :r_a, :rz addop 'sub', [0b10_010_000], :r_a, :rz addop 'sbc', [0b10_011_000], :r_a, :rz addop 'and', [0b10_100_000], :r_a, :rz addop 'xor', [0b10_101_000], :r_a, :rz addop 'or', [0b10_110_000], :r_a, :rz addop 'cmp', [0b10_111_000], :r_a, :rz # alias cp addop 'cp', [0b10_111_000], :r_a, :rz # compare addop_macrocc 'ret', [0b11_000_000], :setip addop 'pop', [0b11_000_001], :rp2 addop 'ret', [0b11_001_001], :stopexec, :setip addop 'jmp', [0b11_101_001], :r_hl, :setip, :stopexec # alias jp addop 'jp', [0b11_101_001], :r_hl, :setip, :stopexec addop 'ld', [0b11_111_001], :r_sp, :r_hl addop_macrocc 'j', [0b11_000_010], :setip, :u16 # alias jp addop_macrocc 'jp', [0b11_000_010], :setip, :u16 addop 'jmp', [0b11_000_011], :setip, :stopexec, :u16 # alias jp addop 'jp', [0b11_000_011], :setip, :stopexec, :u16 addop 'di', [0b11_110_011] # disable interrupts addop 'ei', [0b11_111_011] addop_macrocc 'call', [0b11_000_100], :u16, :setip, :saveip addop 'push', [0b11_000_101], :rp2 addop 'call', [0b11_001_101], :u16, :setip, :saveip, :stopexec addop 'add', [0b11_000_110], :r_a, :i8 addop 'adc', [0b11_001_110], :r_a, :i8 addop 'sub', [0b11_010_110], :r_a, :i8 addop 'sbc', [0b11_011_110], :r_a, :i8 addop 'and', [0b11_100_110], :r_a, :i8 addop 'xor', [0b11_101_110], :r_a, :i8 addop 'or', [0b11_110_110], :r_a, :i8 addop 'cp', [0b11_111_110], :r_a, :i8 addop 'rst', [0b11_000_111], :iy8 # call off in page 0 addop 'rlc', [0xCB, 0b00_000_000], :rz # rotate addop 'rrc', [0xCB, 0b00_001_000], :rz addop 'rl', [0xCB, 0b00_010_000], :rz addop 'rr', [0xCB, 0b00_011_000], :rz addop 'sla', [0xCB, 0b00_100_000], :rz # shift addop 'sra', [0xCB, 0b00_101_000], :rz addop 'srl', [0xCB, 0b00_111_000], :rz addop 'bit', [0xCB, 0b01_000_000], :iy, :rz # bit test addop 'res', [0xCB, 0b10_000_000], :iy, :rz # bit reset addop 'set', [0xCB, 0b11_000_000], :iy, :rz # bit set end
data from http://www.z80.info/decoding.htm
init_z80_common
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/z80/opcodes.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/z80/opcodes.rb
BSD-3-Clause
def init_gb init_z80_common addop 'ld', [0x08], :m16, :r_sp addop 'stop', [0x10] addop 'ldi', [0x22], :m_hl, :r_a # (hl++) <- a addop 'ldi', [0x2A], :r_a, :m_hl addop 'ldd', [0x32], :m_hl, :r_a # (hl--) <- a addop 'ldd', [0x3A], :r_a, :m_hl addop 'reti', [0xD9], :setip, :stopexec # override retpo/jpo @opcode_list.delete_if { |op| op.bin[0] & 0xE5 == 0xE0 } # rm E0 E2 E8 EA F0 F2 F8 FA addop 'ld', [0xE0], :mf8, :r_a # (0xff00 + :i8) addop 'ld', [0xE2], :mfc, :r_a # (0xff00 + :r_c) addop 'add', [0xE8], :r_sp, :i8 addop 'ld', [0xEA], :m16, :r_a addop 'ld', [0xF0], :r_a, :mf8 addop 'ld', [0xF2], :r_a, :mfc addop 'ld', [0xF8], :r_hl, :r_sp, :i8 # hl <- sp+:i8 addop 'ld', [0xFA], :r_a, :m16 addop 'swap', [0xCB, 0x30], :rz addop 'inv_dd', [0xDD], :stopexec # invalid prefixes addop 'inv_ed', [0xED], :stopexec addop 'inv_fd', [0xFD], :stopexec addop 'unk_nop', [], :i8 # undefined opcode = nop @unknown_opcode = @opcode_list.last end
gameboy processor from http://nocash.emubase.de/pandocs.htm#cpucomparisionwithz80
init_gb
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/z80/opcodes.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/z80/opcodes.rb
BSD-3-Clause
def member(name) @members.find { |m| m.name == name } end
return the 1st member whose name is name
member
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff.rb
BSD-3-Clause
def decode(coff) return set_default_values(coff) if coff.header.size_opthdr == 0 and not coff.header.characteristics.include?('EXECUTABLE_IMAGE') off = coff.curencoded.ptr super(coff) nrva = (coff.header.size_opthdr - (coff.curencoded.ptr - off)) / 8 nrva = @numrva if nrva < 0 if nrva > DIRECTORIES.length or nrva != @numrva puts "W: COFF: Weird directories count #{@numrva}" if $VERBOSE nrva = DIRECTORIES.length if nrva > DIRECTORIES.length end coff.directory = {} DIRECTORIES[0, nrva].each { |dir| rva = coff.decode_word sz = coff.decode_word if rva != 0 or sz != 0 coff.directory[dir] = [rva, sz] end } end
decodes a COFF optional header from coff.cursection also decodes directories in coff.directory
decode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def decode(coff) super(coff) if coff.sect_at_rva(@libname_p) @libname = coff.decode_strz end if coff.sect_at_rva(@func_p) @exports = [] addrs = [] @num_exports.times { addrs << coff.decode_word } @num_exports.times { |i| e = Export.new e.ordinal = i + @ordinal_base addr = addrs[i] if addr >= coff.directory['export_table'][0] and addr < coff.directory['export_table'][0] + coff.directory['export_table'][1] and coff.sect_at_rva(addr) name = coff.decode_strz e.forwarder_lib, name = name.split('.', 2) if name[0] == ?# e.forwarder_ordinal = name[1..-1].to_i else e.forwarder_name = name end else e.target = e.target_rva = addr end @exports << e } end if coff.sect_at_rva(@names_p) namep = [] num_names.times { namep << coff.decode_word } end if coff.sect_at_rva(@ord_p) ords = [] num_names.times { ords << coff.decode_half } end if namep and ords namep.zip(ords).each { |np, oi| @exports[oi].name_p = np if coff.sect_at_rva(np) @exports[oi].name = coff.decode_strz end } end end
decodes a COFF export table from coff.cursection
decode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def decode(coff) super(coff) len = coff.decode_word len -= 8 if len < 0 or len % 2 != 0 puts "W: COFF: Invalid relocation table length #{len+8}" if $VERBOSE coff.curencoded.read(len) if len > 0 @relocs = [] return end @relocs = coff.curencoded.read(len).unpack(coff.endianness == :big ? 'n*' : 'v*').map { |r| Relocation.new(r&0xfff, r>>12) } #(len/2).times { @relocs << Relocation.decode(coff) } # tables may be big, this is too slow end
decodes a relocation table from coff.encoded.ptr
decode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def sect_at_rva(rva) return if not rva or rva <= 0 if sections and not @sections.empty? if s = @sections.find { |s_| s_.virtaddr <= rva and s_.virtaddr + EncodedData.align_size((s_.virtsize == 0 ? s_.rawsize : s_.virtsize), @optheader.sect_align) > rva } s.encoded.ptr = rva - s.virtaddr @cursection = s elsif rva < @sections.map { |s_| s_.virtaddr }.min @encoded.ptr = rva @cursection = self end elsif rva <= @encoded.length @encoded.ptr = rva @cursection = self end end
converts an RVA (offset from base address of file when loaded in memory) to the section containing it using the section table updates @cursection and @cursection.encoded.ptr to point to the specified address may return self when rva points to the coff header returns nil if none match, 0 never matches
sect_at_rva
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def fileoff_to_addr(foff) if s = @sections.find { |s_| s_.rawaddr <= foff and s_.rawaddr + s_.rawsize > foff } s.virtaddr + foff - s.rawaddr + (@load_address ||= @optheader.image_base) elsif foff >= 0 and foff < @optheader.headers_size foff + (@load_address ||= @optheader.image_base) end end
file offset -> memory address handles LoadedPE
fileoff_to_addr
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def decode_header @cursection ||= self @encoded.ptr ||= 0 @sections = [] @header.decode(self) optoff = @encoded.ptr @optheader.decode(self) decode_symbols if @header.num_sym != 0 and not @header.characteristics.include? 'DEBUG_STRIPPED' curencoded.ptr = optoff + @header.size_opthdr decode_sections if sect_at_rva(@optheader.entrypoint) curencoded.add_export new_label('entrypoint') end (DIRECTORIES - ['certificate_table']).each { |d| if @directory[d] and sect_at_rva(@directory[d][0]) curencoded.add_export new_label(d) end } end
decodes the COFF header, optional header, section headers marks entrypoint and directories as edata.expord
decode_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def decode_symbols endptr = @encoded.ptr = @header.ptr_sym + 18*@header.num_sym strlen = decode_word @encoded.ptr = endptr strtab = @encoded.read(strlen) @encoded.ptr = @header.ptr_sym @symbols = [] @header.num_sym.times { break if @encoded.ptr >= endptr or @encoded.ptr >= @encoded.length @symbols << Symbol.decode(self, strtab) # keep the reloc.sym_idx accurate @symbols.last.nr_aux.times { @symbols << nil } } end
decode the COFF symbol table (obj only)
decode_symbols
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def decode_section_body(s) raw = EncodedData.align_size(s.rawsize, @optheader.file_align) virt = s.virtsize virt = raw = s.rawsize if @header.size_opthdr == 0 virt = raw if virt == 0 virt = EncodedData.align_size(virt, @optheader.sect_align) s.encoded = @encoded[s.rawaddr, [raw, virt].min] || EncodedData.new s.encoded.virtsize = virt end
decodes a section content (allows simpler LoadedPE override)
decode_section_body
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def decode_exports if @directory['export_table'] and sect_at_rva(@directory['export_table'][0]) @export = ExportDirectory.decode(self) @export.exports.to_a.each { |e| if e.name and sect_at_rva(e.target) name = e.name elsif e.ordinal and sect_at_rva(e.target) name = "ord_#{@export.libname}_#{e.ordinal}" end e.target = curencoded.add_export new_label(name) if name } end end
decodes COFF export table from directory mark exported names as encoded.export
decode_exports
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def decode_imports if @directory['import_table'] and sect_at_rva(@directory['import_table'][0]) @imports = ImportDirectory.decode_all(self) iatlen = @bitsize/8 @imports.each { |id| if sect_at_rva(id.iat_p) ptr = curencoded.ptr id.imports.each { |i| if i.name name = new_label i.name elsif i.ordinal name = new_label "ord_#{id.libname}_#{i.ordinal}" end if name i.target ||= name r = Metasm::Relocation.new(Expression[name], "u#@bitsize".to_sym, @endianness) curencoded.reloc[ptr] = r curencoded.add_export new_label('iat_'+name), ptr, true end ptr += iatlen } end } end end
decodes COFF import tables from directory mark iat entries as encoded.export
decode_imports
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def decode_relocs if @directory['base_relocation_table'] and sect_at_rva(@directory['base_relocation_table'][0]) end_ptr = curencoded.ptr + @directory['base_relocation_table'][1] @relocations = [] while curencoded.ptr < end_ptr @relocations << RelocationTable.decode(self) end # interpret as EncodedData relocations relocfunc = ('decode_reloc_' << @header.machine.downcase).to_sym if not respond_to? relocfunc puts "W: COFF: unsupported relocs for architecture #{@header.machine}" if $VERBOSE return end @relocations.each { |rt| rt.relocs.each { |r| if s = sect_at_rva(rt.base_addr + r.offset) e, p = s.encoded, s.encoded.ptr rel = send(relocfunc, r) e.reloc[p] = rel if rel end } } end end
decode COFF relocation tables from directory
decode_relocs
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def decode_reloc_i386(r) case r.type when 'ABSOLUTE' when 'HIGHLOW' addr = decode_word if s = sect_at_va(addr) label = label_at(s.encoded, s.encoded.ptr, "xref_#{Expression[addr]}") Metasm::Relocation.new(Expression[label], :u32, @endianness) end when 'DIR64' addr = decode_xword if s = sect_at_va(addr) label = label_at(s.encoded, s.encoded.ptr, "xref_#{Expression[addr]}") Metasm::Relocation.new(Expression[label], :u64, @endianness) end else puts "W: COFF: Unsupported i386 relocation #{r.inspect}" if $VERBOSE end end
decodes an I386 COFF relocation pointing to encoded.ptr
decode_reloc_i386
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def decode_tls if @directory['tls_table'] and sect_at_rva(@directory['tls_table'][0]) @tls = TLSDirectory.decode(self) if s = sect_at_va(@tls.callback_p) s.encoded.add_export 'tls_callback_table' @tls.callbacks.each_with_index { |cb, i| @tls.callbacks[i] = curencoded.add_export "tls_callback_#{i}" if sect_at_rva(cb) } end end end
decode TLS directory, including tls callback table
decode_tls
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def decode decode_header decode_exports decode_imports decode_resources decode_certificates decode_debug decode_tls decode_loadconfig decode_delayimports decode_com decode_relocs unless nodecode_relocs or ENV['METASM_NODECODE_RELOCS'] # decode relocs last end
decodes a COFF file (headers/exports/imports/relocs/sections) starts at encoded.ptr
decode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def cpu_from_headers case @header.machine when 'I386'; Ia32.new when 'AMD64'; X86_64.new when 'R4000'; MIPS.new(:little) else raise "unknown cpu #{@header.machine}" end end
returns a metasm CPU object corresponding to +header.machine+
cpu_from_headers
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def get_default_entrypoints ep = [] ep.concat @tls.callbacks.to_a if tls ep << (@optheader.image_base + label_rva(@optheader.entrypoint)) @export.exports.to_a.each { |e| next if e.forwarder_lib or not e.target ep << (@optheader.image_base + label_rva(e.target)) } if export ep end
returns an array including the PE entrypoint and the exported functions entrypoints TODO filter out exported data, include safeseh ?
get_default_entrypoints
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def section_info [['header', @optheader.image_base, @optheader.headers_size, nil]] + @sections.map { |s| [s.name, @optheader.image_base + s.virtaddr, s.virtsize, s.characteristics.join(',')] } end
returns an array of [name, addr, length, info]
section_info
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def fixup_names @members.each { |m| case m.name when '/' when '//' when /^\/(\d+)/ @longnames.ptr = $1.to_i m.name = decode_strz(@longnames).chomp("/") else m.name.chomp! "/" end } end
set real name to archive members look it up in the name table member if needed, or just remove the trailing /
fixup_names
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause