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 set_flag(f) @cpu.dbg_set_flag(self, f) end
set the value of the flag to true
set_flag
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def unset_flag(f) @cpu.dbg_unset_flag(self, f) end
set the value of the flag to false
unset_flag
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def addr2module(addr) @modulemap.keys.find { |k| @modulemap[k][0] <= addr and @modulemap[k][1] > addr } end
returns the name of the module containing addr or nil
addr2module
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def addrname(addr) (addr2module(addr) || '???') + '!' + if s = @symbols[addr] ? addr : @symbols_len.keys.find { |s_| s_ < addr and s_ + @symbols_len[s_] > addr } @symbols[s] + (addr == s ? '' : ('+%x' % (addr-s))) else '%08x' % addr end end
returns a string describing addr in term of symbol (eg 'libc.so.6!printf+2f')
addrname
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def addrname!(addr) (addr2module(addr) || '???') + '!' + if s = @symbols[addr] ? addr : @symbols_len.keys.find { |s_| s_ < addr and s_ + @symbols_len[s_] > addr } || @symbols.keys.sort.find_all { |s_| s_ < addr and s_ + 0x10000 > addr }.max @symbols[s] + (addr == s ? '' : ('+%x' % (addr-s))) else '%08x' % addr end end
same as addrname, but scan preceding addresses if no symbol matches
addrname!
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def loadsyms(addr, name='%08x'%addr.to_i) if addr.kind_of? String modules.each { |m| if m.path =~ /#{addr}/i addr = m.addr name = File.basename m.path break end } return if not addr.kind_of? Integer end return if not peek = @memory.get_page(addr, 4) if peek == "\x7fELF" cls = LoadedELF elsif peek[0, 2] == "MZ" and @memory[addr+@memory[addr+0x3c,4].unpack('V').first, 4] == "PE\0\0" cls = LoadedPE else return end begin e = cls.load @memory[addr, 0x1000_0000] e.load_address = addr e.decode_header e.decode_exports rescue # cache the error so that we dont hit it every time @modulemap[addr.to_s(16)] ||= [addr, addr+0x1000] return end if n = e.module_name and n != name name = n end @modulemap[name] ||= [addr, addr+e.module_size] cnt = 0 e.module_symbols.each { |n_, a, l| cnt += 1 a += addr @disassembler.set_label_at(a, n_, false) @symbols[a] = n_ # XXX store "lib!sym" ? if l and l > 1; @symbols_len[a] = l else @symbols_len.delete a # we may overwrite an existing symbol, keep len in sync end } log "loaded #{cnt} symbols from #{name}" true end
loads the symbols from a mapped module
loadsyms
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def scansyms(addr=0, [email protected]) while addr <= max loadsyms(addr) addr += 0x1000 end end
scan the target memory for loaded libraries, load their symbols
scansyms
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def loadallsyms(&b) modules.each { |m| b.call(m.addr) if b loadsyms(m.addr, m.path) } end
load symbols from all libraries found by the OS module
loadallsyms
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def parse_expr!(arg, &b) return if not e = IndExpression.parse_string!(arg) { |s| # handle 400000 -> 0x400000 # XXX no way to override and force decimal interpretation.. if s.length > 4 and not @disassembler.get_section_at(s.to_i) and @disassembler.get_section_at(s.to_i(16)) s.to_i(16) else s.to_i end } # resolve ambiguous symbol names/hex values bd = {} e.externals.grep(::String).each { |ex| if not v = register_list.find { |r| ex.downcase == r.to_s.downcase } || (b && b.call(ex)) || symbols.index(ex) lst = symbols.values.find_all { |s| s.downcase.include? ex.downcase } case lst.length when 0 if ex =~ /^[0-9a-f]+$/i and @disassembler.get_section_at(ex.to_i(16)) v = ex.to_i(16) else raise "unknown symbol name #{ex}" end when 1 v = symbols.index(lst.first) log "using #{lst.first} for #{ex}" else suggest = lst[0, 50].join(', ') suggest = suggest[0, 125] + '...' if suggest.length > 128 raise "ambiguous symbol name #{ex}: #{suggest} ?" end end bd[ex] = v } e = e.bind(bd) e end
parses the expression contained in arg, updates arg to point after the expr
parse_expr!
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def resolve_expr(e) e = parse_expr(e) if e.kind_of? ::String bd = { :tid => @tid, :pid => @pid } Expression[e].externals.each { |ex| next if bd[ex] case ex when ::Symbol; bd[ex] = get_reg_value(ex) when ::String; bd[ex] = @symbols.index(ex) || @disassembler.prog_binding[ex] || 0 end } Expression[e].bind(bd).reduce { |i| if i.kind_of? Indirection and p = i.pointer.reduce and p.kind_of? ::Integer i.len ||= @cpu.size/8 p &= (1 << @cpu.size) - 1 if p < 0 Expression.decode_imm(@memory, i.len, @cpu, p) end } end
resolves an expression involving register values and/or memory indirection using the current context uses #register_list, #get_reg_value, @mem, @cpu :tid/:pid resolve to current thread
resolve_expr
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def stacktrace(maxdepth=500, &b) @cpu.dbg_stacktrace(self, maxdepth, &b) end
return/yield an array of [addr, addr symbolic name] corresponding to the current stack trace
stacktrace
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def memory_read_int(addr, [email protected]/8) addr = resolve_expr(addr) if not addr.kind_of? ::Integer Expression.decode_imm(@memory, sz, @cpu, addr) end
read an int from the target memory, int of sz bytes (defaults to cpu.size)
memory_read_int
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def memory_write_int(addr, val, [email protected]/8) addr = resolve_expr(addr) if not addr.kind_of? ::Integer val = resolve_expr(val) if not val.kind_of? ::Integer @memory[addr, sz] = Expression.encode_imm(val, sz, @cpu) end
write an int in the target memory
memory_write_int
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def func_arg(nr) @cpu.dbg_func_arg(self, nr) end
retrieve an argument (call at a function entrypoint)
func_arg
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def mappings [[0, @memory.length]] end
return the list of memory mappings of the current process array of [start, len, perms, infos]
mappings
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def list_processes list_debug_pids.map { |p| OS::Process.new(p) } end
return a list of OS::Process listing all alive processes (incl not debugged) default version only includes current debugged pids
list_processes
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def pattern_scan(pat, start=0, [email protected], &b) ret = [] mappings.each { |maddr, mlen, perm, *o_| next if perm !~ /r/i mlen -= start-maddr if maddr < start maddr = start if maddr < start mlen = start+len-maddr if maddr+mlen > start+len next if mlen <= 0 EncodedData.new(read_mapped_range(maddr, mlen)).pattern_scan(pat) { |off| off += maddr ret << off if not b or b.call(off) } } ret end
see EData#pattern_scan scans only mapped areas of @memory, using os_process.mappings
pattern_scan
ruby
stephenfewer/grinder
node/lib/metasm/metasm/debug.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/debug.rb
BSD-3-Clause
def complexity case @lexpr when ExpressionType; @lexpr.complexity when nil, ::Numeric; 0 else 1 end + case @rexpr when ExpressionType; @rexpr.complexity when nil, ::Numeric; 0 else 1 end end
returns the complexity of the expression (number of externals +1 per indirection)
complexity
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decode.rb
BSD-3-Clause
def get_byte @ptr += 1 if @ptr <= @data.length b = @data[ptr-1] b = b.unpack('C').first if b.kind_of? ::String # 1.9 b elsif @ptr <= @virtsize 0 end end
returns an ::Integer from self.ptr, advances ptr bytes from rawsize to virtsize = 0 ignores self.relocations
get_byte
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decode.rb
BSD-3-Clause
def read(len=@virtsize-@ptr) vlen = len vlen = @virtsize-@ptr if len > @virtsize-@ptr str = (@ptr < @data.length) ? @data[@ptr, vlen] : '' str = str.to_str.ljust(vlen, "\0") if str.length < vlen @ptr += len str end
reads len bytes from self.data, advances ptr bytes from rawsize to virtsize are returned as zeroes ignores self.relocations
read
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decode.rb
BSD-3-Clause
def decode_imm(type, endianness) raise "invalid imm type #{type.inspect}" if not isz = Expression::INT_SIZE[type] if rel = @reloc[@ptr] if Expression::INT_SIZE[rel.type] == isz and rel.endianness == endianness @ptr += rel.length return rel.target end puts "W: Immediate type/endianness mismatch, ignoring relocation #{rel.target.inspect} (wanted #{type.inspect})" if $DEBUG end Expression.decode_imm(read(isz/8), type, endianness) end
decodes an immediate value from self.ptr, advances ptr returns an Expression on relocation, or an ::Integer if ptr has a relocation but the type/endianness does not match, the reloc is ignored and a warning is issued TODO arg type => sign+len
decode_imm
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decode.rb
BSD-3-Clause
def decode_instruction(edata, addr) @bin_lookaside ||= build_bin_lookaside di = decode_findopcode edata if edata.ptr <= edata.length di.address = addr if di di = decode_instr_op(edata, di) if di decode_instr_interpret(di, addr) if di end
decodes the instruction at edata.ptr, mapped at virtual address off returns a DecodedInstruction or nil
decode_instruction
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decode.rb
BSD-3-Clause
def decode_findopcode(edata) DecodedInstruction.new self end
matches the binary opcode at edata.ptr returns di or nil
decode_findopcode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decode.rb
BSD-3-Clause
def get_fwdemu_binding(di, pc_reg=nil) fdi = di.backtrace_binding ||= get_backtrace_binding(di) fdi = fix_fwdemu_binding(di, fdi) if pc_reg if di.opcode.props[:setip] xr = get_xrefs_x(nil, di) if xr and xr.length == 1 fdi[pc_reg] = xr[0] else fdi[:incomplete_binding] = Expression[1] end else fdi[pc_reg] = Expression[pc_reg, :+, di.bin_length] end end fdi end
return something like backtrace_binding in the forward direction set pc_reg to some reg name (eg :pc) to include effects on the instruction pointer
get_fwdemu_binding
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decode.rb
BSD-3-Clause
def decompile(*entry) entry.each { |f| decompile_func(f) } finalize @c_parser end
decompile recursively function from an entrypoint, then perform global optimisation (static vars, ...) should be called once after everything is decompiled (global optimizations may bring bad results otherwise) use decompile_func for incremental decompilation returns the c_parser
decompile
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decompile.rb
BSD-3-Clause
def decompile_func(entry) return if @recurse < 0 entry = @dasm.normalize entry return if not @dasm.decoded[entry] # create a new toplevel function to hold our code func = C::Variable.new func.name = @dasm.auto_label_at(entry, 'func') if f = @dasm.function[entry] and f.decompdata and f.decompdata[:return_type] rettype = f.decompdata[:return_type] else rettype = C::BaseType.new(:int) end func.type = C::Function.new rettype, [] if @c_parser.toplevel.symbol[func.name] return if @recurse == 0 if not @c_parser.toplevel.statements.grep(C::Declaration).find { |decl| decl.var.name == func.name } # recursive dependency: declare prototype puts "function #{func.name} is recursive: predecompiling for prototype" if $VERBOSE pre_recurse = @recurse @recurse = 0 @c_parser.toplevel.symbol.delete func.name decompile_func(entry) @recurse = pre_recurse if not @c_parser.toplevel.statements.grep(C::Declaration).find { |decl| decl.var.name == func.name } @c_parser.toplevel.statements << C::Declaration.new(func) end end return end @c_parser.toplevel.symbol[func.name] = func puts "decompiling #{func.name}" if $VERBOSE while catch(:restart) { do_decompile_func(entry, func) } == :restart retval = :restart end @c_parser.toplevel.symbol[func.name] = func # recursive func prototype could have overwritten us @c_parser.toplevel.statements << C::Declaration.new(func) puts " decompiled #{func.name}" if $VERBOSE retval end
decompile a function, decompiling subfunctions as needed may return :restart, which means that the decompilation should restart from the entrypoint (and bubble up) (eg a new codepath is found which may changes dependency in blocks etc)
decompile_func
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decompile.rb
BSD-3-Clause
def redecompile(name) @c_parser.toplevel.statements.delete_if { |st| st.kind_of? C::Declaration and st.var.name == name } oldvar = @c_parser.toplevel.symbol.delete name decompile_func(name) if oldvar and newvar = @c_parser.toplevel.symbol[name] and oldvar.type.kind_of? C::Function and newvar.type.kind_of? C::Function o, n = oldvar.type, newvar.type if o.type != n.type or o.args.to_a.length != n.args.to_a.length or o.args.to_a.zip(n.args.to_a).find { |oa, na| oa.type != na.type } # XXX a may depend on b and c, and b may depend on c -> redecompile c twice # XXX if the dcmp is unstable, may also infinite loop on mutually recursive funcs.. @c_parser.toplevel.statements.dup.each { |st| next if not st.kind_of? C::Declaration next if not st.var.initializer next if st.var.name == name next if not walk_ce(st) { |ce| break true if ce.op == :funcall and ce.lexpr.kind_of? C::Variable and ce.lexpr.name == name } redecompile(st.var.name) } end end end
redecompile a function, redecompiles functions calling it if its prototype changed
redecompile
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decompile.rb
BSD-3-Clause
def listblocks_func(entry) @autofuncs ||= [] blocks = [] entry = dasm.normalize entry todo = [entry] while a = todo.pop next if blocks.find { |aa, at| aa == a } next if not di = @dasm.di_at(a) blocks << [a, []] di.block.each_to { |ta, type| next if type == :indirect ta = dasm.normalize ta if type != :subfuncret and not @dasm.function[ta] and (not @dasm.function[entry] or @autofuncs.include? entry) and di.block.list.last.opcode.props[:saveip] # possible noreturn function # XXX call $+5; pop eax @autofuncs << ta @dasm.function[ta] = DecodedFunction.new puts "autofunc #{Expression[ta]}" if $VERBOSE end if @dasm.function[ta] and type != :subfuncret f = dasm.auto_label_at(ta, 'func') ta = dasm.normalize($1) if f =~ /^thunk_(.*)/ ret = decompile_func_rec(ta) if (ta != entry or di.block.to_subfuncret) throw :restart, :restart if ret == :restart else @dasm.auto_label_at(ta, 'label') if blocks.find { |aa, at| aa == ta } blocks.last[1] |= [ta] todo << ta end } end blocks end
return an array of [address of block start, list of block to]] decompile subfunctions
listblocks_func
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decompile.rb
BSD-3-Clause
def backtrace_target(expr, addr) if n = @dasm.backtrace(expr, addr).first return expr if n == Expression::Unknown n = Expression[n].reduce_rec n = @dasm.get_label_at(n) || n n = $1 if n.kind_of? ::String and n =~ /^thunk_(.*)/ n else expr end end
backtraces an expression from addr returns an integer, a label name, or an Expression XXX '(GetProcAddr("foo"))()' should not decompile to 'foo()'
backtrace_target
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decompile.rb
BSD-3-Clause
def makestackvars(funcstart, blocks) blockstart = nil cache_di = nil cache = {} # [i_s, e, type] => backtrace tovar = lambda { |di, e, i_s| case e when Expression; Expression[tovar[di, e.lexpr, i_s], e.op, tovar[di, e.rexpr, i_s]].reduce when Indirection; Indirection[tovar[di, e.target, i_s], e.len, e.origin] when :frameptr; e when ::Symbol cache.clear if cache_di != di ; cache_di = di vals = cache[[e, i_s, 0]] ||= @dasm.backtrace(e, di.address, :snapshot_addr => blockstart, :include_start => i_s, :no_check => true, :terminals => [:frameptr]) # backtrace only to blockstart first if vals.length == 1 and ee = vals.first and ee.kind_of? Expression and (ee == Expression[:frameptr] or (ee.lexpr == :frameptr and ee.op == :+ and ee.rexpr.kind_of? ::Integer) or (not ee.lexpr and ee.op == :+ and ee.rexpr.kind_of? Indirection and eep = ee.rexpr.pointer and (eep == Expression[:frameptr] or (eep.lexpr == :frameptr and eep.op == :+ and eep.rexpr.kind_of? ::Integer)))) ee else # fallback on full run (could restart from blockstart with ee, but may reevaluate addr_binding.. vals = cache[[e, i_s, 1]] ||= @dasm.backtrace(e, di.address, :snapshot_addr => funcstart, :include_start => i_s, :no_check => true, :terminals => [:frameptr]) if vals.length == 1 and ee = vals.first and (ee.kind_of? Expression and (ee == Expression[:frameptr] or (ee.lexpr == :frameptr and ee.op == :+ and ee.rexpr.kind_of? ::Integer))) ee else e end end else e end } # must not change bt_bindings until everything is backtracked repl_bind = {} # di => bt_bd @dasm.cpu.decompile_makestackvars(@dasm, funcstart, blocks) { |block| block.list.each { |di| bd = di.backtrace_binding ||= @dasm.cpu.get_backtrace_binding(di) newbd = repl_bind[di] = {} bd.each { |k, v| k = tovar[di, k, true] if k.kind_of? Indirection next if k == Expression[:frameptr] or (k.kind_of? Expression and k.lexpr == :frameptr and k.op == :+ and k.rexpr.kind_of? ::Integer) newbd[k] = tovar[di, v, false] } } } repl_bind.each { |di, bd| di.backtrace_binding = bd } end
patches instruction's backtrace_binding to replace things referring to a static stack offset from func start by :frameptr+off
makestackvars
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decompile.rb
BSD-3-Clause
def stackoff_to_varname(off) if off >= @c_parser.typesize[:ptr]; 'arg_%X' % ( off-@c_parser.typesize[:ptr]) # 4 => arg_0, 8 => arg_4.. elsif off > 0; 'arg_0%X' % off elsif off == 0; 'retaddr' elsif off <= [email protected]/8; 'var_%X' % ([email protected]/8) # -4 => var_0, -8 => var_4.. else 'var_0%X' % -off end end
give a name to a stackoffset (relative to start of func) 4 => :arg_0, -8 => :var_4 etc
stackoff_to_varname
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decompile.rb
BSD-3-Clause
def decompile_cexpr(e, scope, itype=nil) case e when Expression if e.op == :'=' and e.lexpr.kind_of? ::String and e.lexpr =~ /^dummy_metasm_/ decompile_cexpr(e.rexpr, scope, itype) elsif e.op == :+ and e.rexpr.kind_of? ::Integer and e.rexpr < 0 decompile_cexpr(Expression[e.lexpr, :-, -e.rexpr], scope, itype) elsif e.lexpr a = decompile_cexpr(e.lexpr, scope, itype) C::CExpression[a, e.op, decompile_cexpr(e.rexpr, scope, itype)] elsif e.op == :+ decompile_cexpr(e.rexpr, scope, itype) else a = decompile_cexpr(e.rexpr, scope, itype) C::CExpression[e.op, a] end when Indirection case e.len when 1, 2, 4, 8 bt = C::BaseType.new("__int#{e.len*8}".to_sym) else bt = C::Struct.new bt.members = [C::Variable.new('data', C::Array.new(C::BaseType.new(:__int8), e.len))] end itype = C::Pointer.new(bt) p = decompile_cexpr(e.target, scope, itype) p = C::CExpression[[p], itype] if not p.type.kind_of? C::Pointer C::CExpression[:*, p] when ::Integer C::CExpression[e] when C::CExpression e else name = e.to_s if not s = scope.symbol_ancestors[name] s = C::Variable.new s.type = C::BaseType.new(:__int32) case e when ::String # edata relocation (rel.length = size of pointer) return @c_parser.toplevel.symbol[e] || new_global_var(e, itype || C::BaseType.new(:int), scope) when ::Symbol; s.storage = :register ; s.add_attribute("register(#{name})") else s.type.qualifier = [:volatile] puts "decompile_cexpr unhandled #{e.inspect}, using #{e.to_s.inspect}" if $VERBOSE end s.name = name scope.symbol[s.name] = s scope.statements << C::Declaration.new(s) end s end end
turns an Expression to a CExpression, create+declares needed variables in scope
decompile_cexpr
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decompile.rb
BSD-3-Clause
def decompile_controlseq(scope) # TODO replace all this crap by a method using the graph representation scope.statements = decompile_cseq_if(scope.statements, scope) remove_labels(scope) scope.statements = decompile_cseq_if(scope.statements, scope) remove_labels(scope) # TODO harmonize _if/_while api (if returns a replacement, while patches) decompile_cseq_while(scope.statements, scope) decompile_cseq_switch(scope) end
changes ifgoto, goto to while/ifelse..
decompile_controlseq
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decompile.rb
BSD-3-Clause
def decompile_cseq_if(ary, scope) return ary if forbid_decompile_ifwhile # the array of decompiled statements to use as replacement ret = [] # list of labels appearing in ary inner_labels = ary.grep(C::Label).map { |l| l.name } while s = ary.shift # recurse if it's not the first run if s.kind_of? C::If s.bthen.statements = decompile_cseq_if(s.bthen.statements, s.bthen) if s.bthen.kind_of? C::Block s.belse.statements = decompile_cseq_if(s.belse.statements, s.belse) if s.belse.kind_of? C::Block end # if (a) goto x; if (b) goto x; => if (a || b) goto x; while s.kind_of? C::If and s.bthen.kind_of? C::Goto and not s.belse and ary.first.kind_of? C::If and ary.first.bthen.kind_of? C::Goto and not ary.first.belse and s.bthen.target == ary.first.bthen.target s.test = C::CExpression[s.test, :'||', ary.shift.test] end # if (a) goto x; b; x: => if (!a) { b; } if s.kind_of? C::If and s.bthen.kind_of? C::Goto and l = ary.grep(C::Label).find { |l_| l_.name == s.bthen.target } # if {goto l;} a; l: => if (!) {a;} s.test = C::CExpression.negate s.test s.bthen = C::Block.new(scope) s.bthen.statements = decompile_cseq_if(ary[0..ary.index(l)], s.bthen) s.bthen.statements.pop # remove l: from bthen, it is in ary (was needed in bthen for inner ifs) ary[0...ary.index(l)] = [] end if s.kind_of? C::If and (s.bthen.kind_of? C::Block or s.bthen.kind_of? C::Goto) s.bthen = C::Block.new(scope, [s.bthen]) if s.bthen.kind_of? C::Goto bts = s.bthen.statements # if (a) if (b) { c; } => if (a && b) { c; } if bts.length == 1 and bts.first.kind_of? C::If and not bts.first.belse s.test = C::CExpression[s.test, :'&&', bts.first.test] bts = bts.first.bthen bts = s.bthen.statements = bts.kind_of?(C::Block) ? bts.statements : [bts] end # if (a) { if (b) goto c; d; } c: => if (a && !b) { d; } if bts.first.kind_of? C::If and l = bts.first.bthen and (l = l.kind_of?(C::Block) ? l.statements.first : l) and l.kind_of? C::Goto and ary[0].kind_of? C::Label and l.target == ary[0].name s.test = C::CExpression[s.test, :'&&', C::CExpression.negate(bts.first.test)] if e = bts.shift.belse bts.unshift e end end # if () { goto a; } a: if bts.last.kind_of? C::Goto and ary[0].kind_of? C::Label and bts.last.target == ary[0].name bts.pop end # if { a; goto outer; } b; return; => if (!) { b; return; } a; goto outer; if bts.last.kind_of? C::Goto and not inner_labels.include? bts.last.target and g = ary.find { |ss| ss.kind_of? C::Goto or ss.kind_of? C::Return } and g.kind_of? C::Return s.test = C::CExpression.negate s.test ary[0..ary.index(g)], bts[0..-1] = bts, ary[0..ary.index(g)] end # if { a; goto l; } b; l: => if {a;} else {b;} if bts.last.kind_of? C::Goto and l = ary.grep(C::Label).find { |l_| l_.name == bts.last.target } s.belse = C::Block.new(scope) s.belse.statements = decompile_cseq_if(ary[0...ary.index(l)], s.belse) ary[0...ary.index(l)] = [] bts.pop end # if { a; l: b; goto any;} c; goto l; => if { a; } else { c; } b; goto any; if not s.belse and (bts.last.kind_of? C::Goto or bts.last.kind_of? C::Return) and g = ary.grep(C::Goto).first and l = bts.grep(C::Label).find { |l_| l_.name == g.target } s.belse = C::Block.new(scope) s.belse.statements = decompile_cseq_if(ary[0...ary.index(g)], s.belse) ary[0..ary.index(g)], bts[bts.index(l)..-1] = bts[bts.index(l)..-1], [] end # if { a; b; c; } else { d; b; c; } => if {a;} else {d;} b; c; if s.belse bes = s.belse.statements while not bts.empty? if bts.last.kind_of? C::Label; ary.unshift bts.pop elsif bes.last.kind_of? C::Label; ary.unshift bes.pop elsif bts.last.to_s == bes.last.to_s; ary.unshift bes.pop ; bts.pop else break end end # if () { a; } else { b; } => if () { a; } else b; # if () { a; } else {} => if () { a; } case bes.length when 0; s.belse = nil #when 1; s.belse = bes.first end end # if () {} else { a; } => if (!) { a; } # if () { a; } => if () a; case bts.length when 0; s.test, s.bthen, s.belse = C::CExpression.negate(s.test), s.belse, nil if s.belse #when 1; s.bthen = bts.first # later (allows simpler handling in _while) end end # l1: l2: if () goto l1; goto l2; => if(!) goto l2; goto l1; if s.kind_of? C::If ls = s.bthen ls = ls.statements.last if ls.kind_of? C::Block if ls.kind_of? C::Goto if li = inner_labels.index(ls.target) table = inner_labels else table = ary.map { |st| st.name if st.kind_of? C::Label }.compact.reverse li = table.index(ls.target) || table.length end g = ary.find { |ss| break if ss.kind_of? C::Return next if not ss.kind_of? C::Goto table.index(ss.target).to_i > li } if g s.test = C::CExpression.negate s.test if not s.bthen.kind_of? C::Block ls = C::Block.new(scope) ls.statements << s.bthen s.bthen = ls end ary[0..ary.index(g)], s.bthen.statements = s.bthen.statements, decompile_cseq_if(ary[0..ary.index(g)], scope) end end end ret << s end ret end
ifgoto => ifthen ary is an array of statements where we try to find if () {} [else {}] recurses to then/else content
decompile_cseq_if
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decompile.rb
BSD-3-Clause
def isvar(ce, var) if var.stackoff and ce.kind_of? C::CExpression return unless ce.op == :* and not ce.lexpr ce = ce.rexpr ce = ce.rexpr while ce.kind_of? C::CExpression and not ce.op return unless ce.kind_of? C::CExpression and ce.op == :& and not ce.lexpr ce = ce.rexpr end ce == var end
checks if expr is a var (var or *&var)
isvar
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decompile.rb
BSD-3-Clause
def ce_patch(exprs, oldce, newce) walk_ce(exprs) { |ce| case ce.op when :funcall ce.lexpr = newce if ce.lexpr == oldce ce.rexpr.each_with_index { |a, i| ce.rexpr[i] = newce if a == oldce } else ce.lexpr = newce if ce.lexpr == oldce ce.rexpr = newce if ce.rexpr == oldce end } end
patches a set of exprs, replacing oldce by newce
ce_patch
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decompile.rb
BSD-3-Clause
def unalias_vars(scope, func) g = c_to_graph(scope) # unalias func args first, they may include __attr__((out)) needed by the others funcalls = [] walk_ce(scope) { |ce| funcalls << ce if ce.op == :funcall } vars = scope.symbol.values.sort_by { |v| walk_ce(funcalls) { |ce| break true if ce.rexpr == v } ? 0 : 1 } # find the domains of var aliases vars.each { |var| unalias_var(var, scope, g) } end
duplicate vars per domain value eg eax = 1; foo(eax); eax = 2; bar(eax); => eax = 1; foo(eax) eax_1 = 2; bar(eax_1); eax = 1; if (bla) eax = 2; foo(eax); => no change
unalias_vars
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decompile.rb
BSD-3-Clause
def simplify_varname_noalias(scope) names = scope.symbol.keys names.delete_if { |k| next if not b = k[/^(.*)_a\d+$/, 1] next if scope.symbol[k].stackoff.to_i > 0 if not names.find { |n| n != k and (n == b or n[/^(.*)_a\d+$/, 1] == b) } scope.symbol[b] = scope.symbol.delete(k) scope.symbol[b].name = b end } end
revert the unaliasing namechange of vars where no alias subsists
simplify_varname_noalias
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decompile.rb
BSD-3-Clause
def namestackvars(scope) off2var = {} newvar = lambda { |o, n| if not v = off2var[o] v = off2var[o] = C::Variable.new v.type = C::BaseType.new(:void) v.name = n v.stackoff = o scope.symbol[v.name] = v scope.statements << C::Declaration.new(v) end v } scope.decompdata[:stackoff_name].each { |o, n| newvar[o, n] } scope.decompdata[:stackoff_type].each { |o, t| newvar[o, stackoff_to_varname(o)] } walk_ce(scope) { |e| next if e.op != :+ and e.op != :- next if not e.lexpr.kind_of? C::Variable or e.lexpr.name != 'frameptr' next if not e.rexpr.kind_of? C::CExpression or e.rexpr.op or not e.rexpr.rexpr.kind_of? ::Integer off = e.rexpr.rexpr off = -off if e.op == :- v = newvar[off, stackoff_to_varname(off)] e.replace C::CExpression[:&, v] } end
patch scope to transform :frameoff-x into &var_x
namestackvars
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decompile.rb
BSD-3-Clause
def decompile_c_types(scope) return if forbid_decompile_types # TODO *(int8*)(ptr+8); *(int32*)(ptr+12) => automatic struct # name => type types = {} pscopevar = lambda { |e| e = e.rexpr while e.kind_of? C::CExpression and not e.op and e.rexpr.kind_of? C::CExpression if e.kind_of? C::CExpression and e.op == :& and not e.lexpr and e.rexpr.kind_of? C::Variable e.rexpr.name if scope.symbol[e.rexpr.name] end } scopevar = lambda { |e| e = e.rexpr if e.kind_of? C::CExpression and not e.op if e.kind_of? C::Variable and scope.symbol[e.name] e.name elsif e.kind_of? C::CExpression and e.op == :* and not e.lexpr pscopevar[e.rexpr] end } globalvar = lambda { |e| e = e.rexpr if e.kind_of? C::CExpression and not e.op if e.kind_of? ::Integer and @dasm.get_section_at(e) e elsif e.kind_of? C::Variable and not scope.symbol[e.name] and @c_parser.toplevel.symbol[e.name] and @dasm.get_section_at(e.name) e.name end } # check if a newly found type for o is better than current type # order: foo* > void* > foo better_type = lambda { |t0, t1| t1 == C::BaseType.new(:void) or (t0.pointer? and t1.kind_of? C::BaseType) or t0.untypedef.kind_of? C::Union or (t0.kind_of? C::BaseType and t1.kind_of? C::BaseType and (@c_parser.typesize[t0.name] > @c_parser.typesize[t1.name] or (t0.name == t1.name and t0.qualifier))) or (t0.pointer? and t1.pointer? and better_type[t0.pointed, t1.pointed]) } update_global_type = lambda { |e, t| if ne = new_global_var(e, t, scope) ne.type = t if better_type[t, ne.type] # TODO patch existing scopes using ne # TODO rename (dword_xx -> byte_xx etc) e = scope.symbol_ancestors[e] || e if e.kind_of? String # exe reloc walk_ce(scope) { |ce| ce.lexpr = ne if ce.lexpr == e ce.rexpr = ne if ce.rexpr == e if ce.op == :* and not ce.lexpr and ce.rexpr == ne and ne.type.pointer? and ne.type.pointed.untypedef.kind_of? C::Union # *struct -> struct->bla ce.rexpr = structoffset(ne.type.pointed.untypedef, ce.rexpr, 0, sizeof(ce.type)) elsif ce.lexpr == ne or ce.rexpr == ne # set ce type according to l/r # TODO set ce.parent type etc ce.type = C::CExpression[ce.lexpr, ce.op, ce.rexpr].type end } end } propagate_type = nil # fwd declaration propagating = [] # recursion guard (x = &x) # check if need to change the type of a var # propagate_type if type is updated update_type = lambda { |n, t| next if propagating.include? n o = scope.symbol[n].stackoff next if not o and t.untypedef.kind_of? C::Union next if o and scope.decompdata[:stackoff_type][o] and t != scope.decompdata[:stackoff_type][o] next if t0 = types[n] and not better_type[t, t0] next if o and (t.integral? or t.pointer?) and o % sizeof(t) != 0 # keep vars aligned types[n] = t next if t == t0 propagating << n propagate_type[n, t] propagating.delete n next if not o t = t.untypedef if t.kind_of? C::Struct t.members.to_a.each { |m| mo = t.offsetof(@c_parser, m.name) next if mo == 0 scope.symbol.each { |vn, vv| update_type[vn, m.type] if vv.stackoff == o+mo } } end } # try to update the type of a var from knowing the type of an expr (through dereferences etc) known_type = lambda { |e, t| loop do e = e.rexpr while e.kind_of? C::CExpression and not e.op and e.type == t if o = scopevar[e] update_type[o, t] elsif o = globalvar[e] update_global_type[o, t] elsif not e.kind_of? C::CExpression elsif o = pscopevar[e] and t.pointer? update_type[o, t.pointed] elsif e.op == :* and not e.lexpr e = e.rexpr t = C::Pointer.new(t) next elsif t.pointer? and e.op == :+ and e.lexpr.kind_of? C::CExpression and e.lexpr.type.integral? and e.rexpr.kind_of? C::Variable e.lexpr, e.rexpr = e.rexpr, e.lexpr next elsif e.op == :+ and e.lexpr and e.rexpr.kind_of? C::CExpression if not e.rexpr.op and e.rexpr.rexpr.kind_of? ::Integer if t.pointer? and e.rexpr.rexpr < 0x1000 and (e.rexpr.rexpr % sizeof(t.pointed)) == 0 # XXX relocatable + base=0.. e = e.lexpr # (int)*(x+2) === (int) *x next elsif globalvar[e.rexpr.rexpr] known_type[e.lexpr, C::BaseType.new(:int)] e = e.rexpr next end elsif t.pointer? and (e.lexpr.kind_of? C::CExpression and e.lexpr.lexpr and [:<<, :>>, :*, :&].include? e.lexpr.op) or (o = scopevar[e.lexpr] and types[o] and types[o].integral? and !(o = scopevar[e.rexpr] and types[o] and types[o].integral?)) e.lexpr, e.rexpr = e.rexpr, e.lexpr # swap e = e.lexpr next elsif t.pointer? and ((e.rexpr.kind_of? C::CExpression and e.rexpr.lexpr and [:<<, :>>, :*, :&].include? e.rexpr.op) or (o = scopevar[e.rexpr] and types[o] and types[o].integral? and !(o = scopevar[e.lexpr] and types[o] and types[o].integral?))) e = e.lexpr next end end break end } # we found a type for a var, propagate it through affectations propagate_type = lambda { |var, type| walk_ce(scope) { |ce| next if ce.op != :'=' if ce.lexpr.kind_of? C::Variable and ce.lexpr.name == var known_type[ce.rexpr, type] next end if ce.rexpr.kind_of? C::Variable and ce.rexpr.name == var known_type[ce.lexpr, type] next end # int **x; y = **x => int y t = type l = ce.lexpr while l.kind_of? C::CExpression and l.op == :* and not l.lexpr if var == pscopevar[l.rexpr] known_type[ce.rexpr, t] break elsif t.pointer? l = l.rexpr t = t.pointed else break end end # int **x; **x = y => int y t = type r = ce.rexpr while r.kind_of? C::CExpression and r.op == :* and not r.lexpr if var == pscopevar[r.rexpr] known_type[ce.lexpr, t] break elsif t.pointer? r = r.rexpr t = t.pointed else break end end # TODO int *x; *x = *y; ? } } # put all those macros in use # use user-defined types first scope.symbol.each_value { |v| next if not v.kind_of? C::Variable or not v.stackoff or not t = scope.decompdata[:stackoff_type][v.stackoff] known_type[v, t] } # try to infer types from C semantics later = [] walk_ce(scope) { |ce| if ce.op == :'=' and ce.rexpr.kind_of? C::CExpression and (ce.rexpr.op == :funcall or (ce.rexpr.op == nil and ce.rexpr.rexpr.kind_of? ::Integer and ce.rexpr.rexpr.abs < 0x10000 and (not ce.lexpr.kind_of? C::CExpression or ce.lexpr.op != :'*' or ce.lexpr.lexpr))) # var = int known_type[ce.lexpr, ce.rexpr.type] elsif ce.op == :funcall f = ce.lexpr.type f = f.pointed if f.pointer? next if not f.kind_of? C::Function # cast func args to arg prototypes f.args.to_a.zip(ce.rexpr).each_with_index { |(proto, arg), i| ce.rexpr[i] = C::CExpression[arg, proto.type] ; known_type[arg, proto.type] } elsif ce.op == :* and not ce.lexpr if e = ce.rexpr and e.kind_of? C::CExpression and not e.op and e = e.rexpr and e.kind_of? C::CExpression and e.op == :& and not e.lexpr and e.rexpr.kind_of? C::Variable and e.rexpr.stackoff # skip *(__int32*)&var_12 for now, avoid saying var12 is an int if it may be a ptr or anything later << [ce.rexpr, C::Pointer.new(ce.type)] next end known_type[ce.rexpr, C::Pointer.new(ce.type)] elsif not ce.op and ce.type.pointer? and ce.type.pointed.kind_of? C::Function # cast to fptr: must be a fptr known_type[ce.rexpr, ce.type] end } later.each { |ce, t| known_type[ce, t] } # offsets have types now types.each { |v, t| # keep var type qualifiers q = scope.symbol[v].type.qualifier scope.symbol[v].type = t t.qualifier = q if q } # remove offsets to struct members # XXX this defeats antialiasing # off => [structoff, membername, membertype] memb = {} types.dup.each { |n, t| v = scope.symbol[n] next if not o = v.stackoff t = t.untypedef if t.kind_of? C::Struct t.members.to_a.each { |tm| moff = t.offsetof(@c_parser, tm.name) next if moff == 0 types.delete_if { |vv, tt| scope.symbol[vv].stackoff == o+moff } memb[o+moff] = [v, tm.name, tm.type] } end } # patch local variables into the CExprs, incl unknown offsets varat = lambda { |n| v = scope.symbol[n] if s = memb[v.stackoff] v = C::CExpression[s[0], :'.', s[1], s[2]] else v.type = types[n] || C::BaseType.new(:int) end v } maycast = lambda { |v, e| if sizeof(v) != sizeof(e) v = C::CExpression[:*, [[:&, v], C::Pointer.new(e.type)]] end v } maycast_p = lambda { |v, e| if not e.type.pointer? or sizeof(v) != sizeof(nil, e.type.pointed) C::CExpression[[:&, v], e.type] else C::CExpression[:&, v] end } walk_ce(scope, true) { |ce| case when ce.op == :funcall ce.rexpr.map! { |re| if o = scopevar[re]; C::CExpression[maycast[varat[o], re]] elsif o = pscopevar[re]; C::CExpression[maycast_p[varat[o], re]] else re end } when o = scopevar[ce.lexpr]; ce.lexpr = maycast[varat[o], ce.lexpr] when o = scopevar[ce.rexpr]; ce.rexpr = maycast[varat[o], ce.rexpr] ce.rexpr = C::CExpression[ce.rexpr] if not ce.op and ce.rexpr.kind_of? C::Variable when o = pscopevar[ce.lexpr]; ce.lexpr = maycast_p[varat[o], ce.lexpr] when o = pscopevar[ce.rexpr]; ce.rexpr = maycast_p[varat[o], ce.rexpr] when o = scopevar[ce]; ce.replace C::CExpression[maycast[varat[o], ce]] when o = pscopevar[ce]; ce.replace C::CExpression[maycast_p[varat[o], ce]] end } fix_type_overlap(scope) fix_pointer_arithmetic(scope) # if int32 var_4 is always var_4 & 255, change type to int8 varuse = Hash.new(0) varandff = Hash.new(0) varandffff = Hash.new(0) walk_ce(scope) { |ce| if ce.op == :& and ce.lexpr.kind_of? C::Variable and ce.lexpr.type.integral? and ce.rexpr.kind_of? C::CExpression and not ce.rexpr.op and ce.rexpr.rexpr.kind_of? ::Integer case ce.rexpr.rexpr when 0xff; varandff[ce.lexpr.name] += 1 when 0xffff; varandffff[ce.lexpr.name] += 1 end end varuse[ce.lexpr.name] += 1 if ce.lexpr.kind_of? C::Variable varuse[ce.rexpr.name] += 1 if ce.rexpr.kind_of? C::Variable } varandff.each { |k, v| scope.symbol[k].type = C::BaseType.new(:__int8, :unsigned) if varuse[k] == v } varandffff.each { |k, v| scope.symbol[k].type = C::BaseType.new(:__int16, :unsigned) if varuse[k] == v } # propagate types to cexprs walk_ce(scope, true) { |ce| if ce.op ce.type = C::CExpression[ce.lexpr, ce.op, ce.rexpr].type rescue next if ce.op == :'=' and ce.rexpr.kind_of? C::Typed and ce.rexpr.type != ce.type and (not ce.rexpr.type.integral? or not ce.type.integral?) known_type[ce.rexpr, ce.type] if ce.type.pointer? and ce.type.pointed.untypedef.kind_of? C::Function # localvar = &struct with fptr ce.rexpr = C::CExpression[[ce.rexpr], ce.type] end elsif ce.type.pointer? and ce.rexpr.kind_of? C::CExpression and ce.rexpr.op == :& and not ce.rexpr.lexpr and sizeof(ce.rexpr.rexpr.type) == sizeof(ce.type.pointed) ce.type = ce.rexpr.type end } end
assign type to vars (regs, stack & global) types are found by subfunction argument types & indirections, and propagated through assignments etc TODO when updating the type of a var, update the type of all cexprs where it appears
decompile_c_types
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decompile.rb
BSD-3-Clause
def structoffset(st, ptr, off, msz) tabidx = off / sizeof(st) off -= tabidx * sizeof(st) ptr = C::CExpression[:&, [ptr, :'[]', [tabidx]]] if tabidx != 0 or ptr.type.untypedef.kind_of? C::Array return ptr if off == 0 and (not msz or # avoid infinite recursion with eg chained list (ptr.kind_of? C::CExpression and ((ptr.op == :& and not ptr.lexpr and s=ptr.rexpr) or (ptr.op == :'.' and s=ptr)) and not s.type.untypedef.kind_of? C::Union)) m_ptr = lambda { |m| if ptr.kind_of? C::CExpression and ptr.op == :& and not ptr.lexpr C::CExpression[ptr.rexpr, :'.', m.name] else C::CExpression[ptr, :'->', m.name] end } # recursive proc to list all named members, including in anonymous substructs submemb = lambda { |sm| sm.name ? sm : sm.type.kind_of?(C::Union) ? sm.type.members.to_a.map { |ssm| submemb[ssm] } : nil } mbs = st.members.to_a.map { |m| submemb[m] }.flatten.compact mo = mbs.inject({}) { |h, m| h.update m => st.offsetof(@c_parser, m.name) } if sm = mbs.find { |m| mo[m] == off and (not msz or sizeof(m) == msz) } || mbs.find { |m| mo[m] <= off and mo[m]+sizeof(m) > off } off -= mo[sm] sst = sm.type.untypedef #return ptr if mo[sm] == 0 and sst.pointer? and sst.type.untypedef == st # TODO fix infinite recursion on mutually recursive ptrs ptr = C::CExpression[:&, m_ptr[sm]] if sst.kind_of? C::Union return structoffset(sst, ptr, off, msz) end end if off != 0 C::CExpression[[[ptr], C::Pointer.new(C::BaseType.new(:__int8))], :+, [off]] else ptr end end
struct foo { int i; int j; struct { int k; int l; } m; }; bla+12 => &bla->m.l st is a struct, ptr is an expr pointing to a struct, off is a numeric offset from ptr, msz is the size of the pointed member (nil ignored)
structoffset
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decompile.rb
BSD-3-Clause
def fix_pointer_arithmetic(scope) walk_ce(scope, true) { |ce| if ce.lexpr and ce.lexpr.type.pointer? and [:&, :>>, :<<].include? ce.op ce.lexpr = C::CExpression[[ce.lexpr], C::BaseType.new(:int)] end if ce.op == :+ and ce.lexpr and ((ce.lexpr.type.integral? and ce.rexpr.type.pointer?) or (ce.rexpr.type.pointer? and ce.rexpr.type.pointed.untypedef.kind_of? C::Union)) ce.rexpr, ce.lexpr = ce.lexpr, ce.rexpr end if ce.op == :* and not ce.lexpr and ce.rexpr.type.pointer? and ce.rexpr.type.pointed.untypedef.kind_of? C::Struct s = ce.rexpr.type.pointed.untypedef m = s.members.to_a.find { |m_| s.offsetof(@c_parser, m_.name) == 0 } if sizeof(m) != sizeof(ce) ce.rexpr = C::CExpression[[ce.rexpr, C::Pointer.new(s)], C::Pointer.new(ce.type)] next end # *structptr => structptr->member ce.lexpr = ce.rexpr ce.op = :'->' ce.rexpr = m.name ce.type = m.type next elsif ce.op == :'=' and ce.lexpr.type.untypedef.kind_of? C::Struct s = ce.lexpr.type.untypedef m = s.members.to_a.find { |m_| s.offsetof(@c_parser, m_.name) == 0 } ce.lexpr = C::CExpression.new(ce.lexpr, :'.', m.name, m.type) ce.type = m.type next end if ce.op == :+ and ce.lexpr and ce.lexpr.type.pointer? and not ce.type.pointer? ce.type = ce.lexpr.type end if ce.op == :& and not ce.lexpr and ce.rexpr.kind_of? C::CExpression and ce.rexpr.op == :* and not ce.rexpr.lexpr ce.replace C::CExpression[ce.rexpr.rexpr] end next if not ce.lexpr or not ce.lexpr.type.pointer? if ce.op == :+ and (s = ce.lexpr.type.pointed.untypedef).kind_of? C::Union and ce.rexpr.kind_of? C::CExpression and not ce.rexpr.op and ce.rexpr.rexpr.kind_of? ::Integer and o = ce.rexpr.rexpr # structptr + 4 => &structptr->member ce.replace structoffset(s, ce.lexpr, o, nil) elsif [:+, :-, :'+=', :'-='].include? ce.op and ce.rexpr.kind_of? C::CExpression and ((not ce.rexpr.op and i = ce.rexpr.rexpr) or (ce.rexpr.op == :* and i = ce.rexpr.lexpr and ((i.kind_of? C::CExpression and not i.op and i = i.rexpr) or true))) and i.kind_of? ::Integer and psz = sizeof(nil, ce.lexpr.type.pointed) and i % psz == 0 # ptr += 4 => ptr += 1 if not ce.rexpr.op ce.rexpr.rexpr /= psz else ce.rexpr.lexpr.rexpr /= psz if ce.rexpr.lexpr.rexpr == 1 ce.rexpr = ce.rexpr.rexpr end end ce.type = ce.lexpr.type elsif (ce.op == :+ or ce.op == :-) and sizeof(nil, ce.lexpr.type.pointed) != 1 # ptr+x => (ptrtype*)(((__int8*)ptr)+x) # XXX create struct ? ce.rexpr = C::CExpression[ce.rexpr, C::BaseType.new(:int)] if not ce.rexpr.type.integral? if sizeof(nil, ce.lexpr.type.pointed) != 1 ptype = ce.lexpr.type p = C::CExpression[[ce.lexpr], C::Pointer.new(C::BaseType.new(:__int8))] ce.replace C::CExpression[[p, ce.op, ce.rexpr, p.type], ptype] end end } end
fix pointer arithmetic (eg int foo += 4 => int* foo += 1) use struct member access (eg *(structptr+8) => structptr->bla) must be run only once, right after type setting
fix_pointer_arithmetic
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decompile.rb
BSD-3-Clause
def fix_type_overlap(scope) varinfo = {} scope.symbol.each_value { |var| next if not off = var.stackoff len = sizeof(var) varinfo[var] = [off, len] } varinfo.each { |v1, (o1, l1)| next if not v1.type.integral? varinfo.each { |v2, (o2, l2)| # XXX o1 may overlap o2 AND another (int32 v_10; int32 v_E; int32 v_C;) # TODO should check stuff with aliasing domains next if v1.name == v2.name or o1 >= o2+l2 or o1+l1 <= o2 or l1 > l2 or (l2 == l1 and o2 >= o1) # v1 => *(&v2+delta) p = C::CExpression[:&, v2] p = C::CExpression[p, :+, [o1-o2]] p = C::CExpression[p, C::Pointer.new(v1.type)] if v1.type != p.type.type p = C::CExpression[:*, p] walk_ce(scope) { |ce| ce.lexpr = p if ce.lexpr == v1 ce.rexpr = p if ce.rexpr == v1 } } } end
handling of var overlapping (eg __int32 var_10; __int8 var_F => replace all var_F by *(&var_10 + 1)) must be done before fix_pointer_arithmetic
fix_type_overlap
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decompile.rb
BSD-3-Clause
def optimize(scope) optimize_code(scope) optimize_vars(scope) optimize_vars(scope) # 1st run may transform i = i+1 into i++ which second run may coalesce into if(i) end
to be run with scope = function body with only CExpr/Decl/Label/Goto/IfGoto/Return, with correct variables types will transform += 1 to ++, inline them to prev/next statement ('++x; if (x)..' => 'if (++x)..') remove useless variables ('int i;', i never used or 'i = 1; j = i;', i never read after => 'j = 1;') remove useless casts ('(int)i' with 'int i;' => 'i')
optimize
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decompile.rb
BSD-3-Clause
def optimize_code(scope) return if forbid_optimize_code sametype = lambda { |t1, t2| t1 = t1.untypedef t2 = t2.untypedef t1 = t1.pointed.untypedef if t1.pointer? and t1.pointed.untypedef.kind_of? C::Function t2 = t2.pointed.untypedef if t2.pointer? and t2.pointed.untypedef.kind_of? C::Function t1 == t2 or (t1.kind_of? C::Function and t2.kind_of? C::Function and sametype[t1.type, t2.type] and t1.args.to_a.length == t2.args.to_a.length and t1.args.to_a.zip(t2.args.to_a).all? { |st1, st2| sametype[st1.type, st2.type] }) or (t1.kind_of? C::BaseType and t1.integral? and t2.kind_of? C::BaseType and t2.integral? and sizeof(nil, t1) == sizeof(nil, t2)) or (t1.pointer? and t2.pointer? and sametype[t1.type, t2.type]) } # most of this is a CExpr#reduce future_array = [] walk_ce(scope, true) { |ce| # (whatever)0 => 0 if not ce.op and ce.rexpr.kind_of? C::CExpression and not ce.rexpr.op and ce.rexpr.rexpr == 0 ce.replace ce.rexpr end # *&bla => bla if types ok if ce.op == :* and not ce.lexpr and ce.rexpr.kind_of? C::CExpression and ce.rexpr.op == :& and not ce.rexpr.lexpr and sametype[ce.rexpr.type.pointed, ce.rexpr.rexpr.type] ce.replace C::CExpression[ce.rexpr.rexpr] end # int x + 0xffffffff -> x-1 if ce.lexpr and ce.rexpr.kind_of? C::CExpression and not ce.rexpr.op and [:+, :-, :'+=', :'-=', :'!=', :==, :>, :<, :>=, :<=].include? ce.op and ce.rexpr.rexpr == (1 << (8*sizeof(ce.lexpr)))-1 ce.op = {:+ => :-, :- => :+, :'+=' => :'-=', :'-=' => :'+='}[ce.op] ce.rexpr.rexpr = 1 end # int *ptr; *(ptr + 4) => ptr[4] if ce.op == :* and not ce.lexpr and ce.rexpr.kind_of? C::CExpression and ce.rexpr.op == :+ and var = ce.rexpr.lexpr and var.kind_of? C::Variable and var.type.pointer? ce.lexpr, ce.op, ce.rexpr = ce.rexpr.lexpr, :'[]', ce.rexpr.rexpr future_array << var.name end # char x; x & 255 => x if ce.op == :& and ce.lexpr and (ce.lexpr.type.integral? or ce.lexpr.type.pointer?) and ce.rexpr.kind_of? C::CExpression and not ce.rexpr.op and ce.rexpr.rexpr.kind_of? ::Integer and m = (1 << (8*sizeof(ce.lexpr))) - 1 and ce.rexpr.rexpr & m == m ce.replace C::CExpression[ce.lexpr] end # a + -b => a - b if ce.op == :+ and ce.lexpr and ce.rexpr.kind_of? C::CExpression and ce.rexpr.op == :- and not ce.rexpr.lexpr ce.op, ce.rexpr = :-, ce.rexpr.rexpr end # (((int) i >> 31) & 1) => i < 0 if ce.op == :& and ce.rexpr.kind_of? C::CExpression and not ce.rexpr.op and ce.rexpr.rexpr == 1 and ce.lexpr.kind_of? C::CExpression and ce.lexpr.op == :>> and ce.lexpr.rexpr.kind_of? C::CExpression and not ce.lexpr.rexpr.op and ce.lexpr.rexpr.rexpr == sizeof(ce.lexpr.lexpr) * 8 - 1 ce.replace C::CExpression[ce.lexpr.lexpr, :<, [0]] end # a-b == 0 => a == b if ce.rexpr.kind_of? C::CExpression and not ce.rexpr.op and ce.rexpr.rexpr == 0 and [:==, :'!=', :<, :>, :<=, :>=].include? ce.op and ce.lexpr.kind_of? C::CExpression and ce.lexpr.op == :- and ce.lexpr.lexpr ce.lexpr, ce.rexpr = ce.lexpr.lexpr, ce.lexpr.rexpr end # (a > 0) != 0 if ce.op == :'!=' and ce.rexpr.kind_of? C::CExpression and not ce.rexpr.op and ce.rexpr.rexpr == 0 and ce.lexpr.kind_of? C::CExpression and [:<, :<=, :>, :>=, :'==', :'!=', :'!'].include? ce.lexpr.op ce.replace ce.lexpr end # (a < b) != ( [(a < 0) == !(b < 0)] && [(a < 0) != (a < b)] ) => jl # a<b => true if !r => a<0 == b<0 or a>=0 => a>=0 or b>=0 # a>=b => true if r => a<0 == b>=0 and a<0 => a<0 and b>=0 # x != (a && (b != x)) => [x && (!a || b)] || [!x && !(!a || b)] if ce.op == :'!=' and ce.lexpr.kind_of? C::CExpression and ce.lexpr.op == :< and ce.rexpr.kind_of? C::CExpression and ce.rexpr.op == :'&&' and ce.rexpr.rexpr.kind_of? C::CExpression and ce.rexpr.rexpr.op == :'!=' and ce.rexpr.rexpr.rexpr == ce.lexpr and not walk_ce(ce) { |ce_| break true if ce_.op == :funcall } x, a, b = ce.lexpr, ce.rexpr.lexpr, ce.rexpr.rexpr.lexpr ce.replace C::CExpression[ [x, :'&&', [[:'!',a],:'||',b]] , :'||', [[:'!', x], :'&&', [:'!', [[:'!',a],:'||',b]]] ] optimize_code(ce) end # (a != b) || a => a || b if ce.op == :'||' and ce.lexpr.kind_of? C::CExpression and ce.lexpr.op == :'!=' and ce.lexpr.lexpr == ce.rexpr and not walk_ce(ce) { |ce_| break true if ce_.op == :funcall } ce.lexpr, ce.rexpr = ce.rexpr, ce.lexpr.rexpr optimize_code(ce) end # (a<b) && !(a>=0 && b<0) || (a>=b) && (a>=0 && b<0) => (signed)a < (signed)b if ce.op == :'||' and ce.lexpr.kind_of? C::CExpression and ce.rexpr.kind_of? C::CExpression and ce.lexpr.op == :'&&' and ce.rexpr.op == :'&&' and ce.lexpr.lexpr.kind_of? C::CExpression and ce.lexpr.lexpr.op == :< a, b = ce.lexpr.lexpr.lexpr, ce.lexpr.lexpr.rexpr if ce.lexpr.rexpr === C::CExpression[[a, :'>=', [0]], :'&&', [b, :'<', [0]]].negate and ce.rexpr.lexpr === ce.lexpr.lexpr.negate and ce.rexpr.rexpr === ce.lexpr.rexpr.negate ce.replace C::CExpression[a, :'<', b] end end # a && 1 if (ce.op == :'||' or ce.op == :'&&') and ce.rexpr.kind_of? C::CExpression and not ce.rexpr.op and ce.rexpr.rexpr.kind_of? ::Integer if ((ce.op == :'||' and ce.rexpr.rexpr == 0) or (ce.op == :'&&' and ce.rexpr.rexpr != 0)) ce.replace C::CExpression[ce.lexpr] elsif not walk_ce(ce) { |ce_| break true if ce.op == :funcall } # cannot wipe if sideeffect ce.replace C::CExpression[[ce.op == :'||' ? 1 : 0]] end end # (b < c || b >= c) if (ce.op == :'||' or ce.op == :'&&') and C::CExpression.negate(ce.lexpr) == C::CExpression[ce.rexpr] ce.replace C::CExpression[[(ce.op == :'||') ? 1 : 0]] end # (a < b) | (a == b) => a <= b if ce.op == :| and ce.rexpr.kind_of? C::CExpression and ce.rexpr.op == :== and ce.lexpr.kind_of? C::CExpression and (ce.lexpr.op == :< or ce.lexpr.op == :>) and ce.lexpr.lexpr == ce.rexpr.lexpr and ce.lexpr.rexpr == ce.rexpr.rexpr ce.op = {:< => :<=, :> => :>=}[ce.lexpr.op] ce.lexpr, ce.rexpr = ce.lexpr.lexpr, ce.lexpr.rexpr end # a == 0 => !a if ce.op == :== and ce.rexpr.kind_of? C::CExpression and not ce.rexpr.op and ce.rexpr.rexpr == 0 ce.lexpr, ce.op, ce.rexpr = nil, :'!', ce.lexpr end if ce.op == :'!' and ce.rexpr.kind_of? C::CExpression and not ce.rexpr.op and ce.rexpr.rexpr.kind_of? ::Integer ce.replace C::CExpression[[ce.rexpr.rexpr == 0 ? 1 : 0]] end # !(bool) => bool if ce.op == :'!' and ce.rexpr.kind_of? C::CExpression and [:'==', :'!=', :<, :>, :<=, :>=, :'||', :'&&', :'!'].include? ce.rexpr.op ce.replace ce.rexpr.negate end # (foo)(bar)x => (foo)x if not ce.op and ce.rexpr.kind_of? C::CExpression and not ce.rexpr.op and ce.rexpr.rexpr.kind_of? C::CExpression ce.rexpr = ce.rexpr.rexpr end # &struct.1stmember => &struct if ce.op == :& and not ce.lexpr and ce.rexpr.kind_of? C::CExpression and ce.rexpr.op == :'.' and s = ce.rexpr.lexpr.type and s.kind_of? C::Union and s.offsetof(@c_parser, ce.rexpr.rexpr) == 0 ce.rexpr = ce.rexpr.lexpr ce.type = C::Pointer.new(ce.rexpr.type) end # (1stmember*)structptr => &structptr->1stmember if not ce.op and ce.type.pointer? and not ce.type.pointed.void? and ce.rexpr.kind_of? C::Typed and ce.rexpr.type.pointer? and s = ce.rexpr.type.pointed.untypedef and s.kind_of? C::Union and ce.type.pointed.untypedef != s ce.rexpr = C::CExpression[structoffset(s, ce.rexpr, 0, sizeof(ce.type.pointed))] #ce.replace ce.rexpr if not ce.type.pointed.untypedef.kind_of? C::Function or (ce.rexpr.type.pointer? and #ce.rexpr.type.pointed.untypedef.kind_of? C::Function) # XXX ugly # int32* v1 = (int32*)pstruct; # z = v1+4 if v1 is not cast, the + is invalid (sizeof pointed changes) # TODO when finding type of pstruct, set type of v1 accordingly end # (&foo)->bar => foo.bar if ce.op == :'->' and ce.lexpr.kind_of? C::CExpression and ce.lexpr.op == :& and not ce.lexpr.lexpr ce.lexpr = ce.lexpr.rexpr ce.op = :'.' end # (foo)bla => bla if bla of type foo if not ce.op and ce.rexpr.kind_of? C::Typed and sametype[ce.type, ce.rexpr.type] ce.replace C::CExpression[ce.rexpr] end if ce.lexpr.kind_of? C::CExpression and not ce.lexpr.op and ce.lexpr.rexpr.kind_of? C::Variable and ce.lexpr.type == ce.lexpr.rexpr.type ce.lexpr = ce.lexpr.rexpr end if ce.op == :'=' and ce.lexpr.kind_of? C::CExpression and ce.lexpr.op == :* and not ce.lexpr.lexpr and ce.lexpr.rexpr.kind_of? C::CExpression and not ce.lexpr.rexpr.op and ce.lexpr.rexpr.type.pointer? and ce.lexpr.rexpr.type.pointed != ce.rexpr.type ce.lexpr.rexpr.type = C::Pointer.new(ce.rexpr.type) optimize_code(ce.lexpr) end } # if there is a ptr[4], change all *ptr to ptr[0] for consistency # do this after the first pass, which may change &*ptr to ptr walk_ce(scope) { |ce| if ce.op == :* and not ce.lexpr and ce.rexpr.kind_of? C::Variable and future_array.include? ce.rexpr.name ce.lexpr, ce.op, ce.rexpr = ce.rexpr, :'[]', C::CExpression[0] end } if not future_array.empty? # if (x != 0) => if (x) walk(scope) { |st| if st.kind_of? C::If and st.test.kind_of? C::CExpression and st.test.op == :'!=' and st.test.rexpr.kind_of? C::CExpression and not st.test.rexpr.op and st.test.rexpr.rexpr == 0 st.test = C::CExpression[st.test.lexpr] end } end
simplify cexpressions (char & 255, redundant casts, etc)
optimize_code
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decompile.rb
BSD-3-Clause
def sideeffect(exp, scope=nil) case exp when nil, ::Numeric, ::String; false when ::Array; exp.any? { |_e| sideeffect _e, scope } when C::Variable; (scope and not scope.symbol[exp.name]) or exp.type.qualifier.to_a.include? :volatile when C::CExpression; (exp.op == :* and not exp.lexpr) or exp.op == :funcall or AssignOp.include?(exp.op) or sideeffect(exp.lexpr, scope) or sideeffect(exp.rexpr, scope) else true # failsafe end end
checks if an expr has sideeffects (funcall, var assignment, mem dereference, use var out of scope if specified)
sideeffect
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decompile.rb
BSD-3-Clause
def optimize_vars(scope) return if forbid_optimize_dataflow g = c_to_graph(scope) # walks a cexpr in evaluation order (not strictly, but this is not strictly defined anyway..) # returns the first subexpr to read var in ce # returns :write if var is rewritten # returns nil if var not read # may return a cexpr var += 2 find_next_read_ce = lambda { |ce_, var| walk_ce(ce_, true) { |ce| case ce.op when :funcall break ce if ce.lexpr == var or ce.rexpr.find { |a| a == var } when :'=' # a=a / a=a+1 => yield a, not :write break ce if ce.rexpr == var break :write if ce.lexpr == var else break ce if ce.lexpr == var or ce.rexpr == var end } } # badlabels is a list of labels that may be reached without passing through the first invocation block find_next_read_rec = lambda { |label, idx, var, done, badlabels| next if done.include? label done << label if idx == 0 idx += 1 while ce = g.exprs[label].to_a[idx] and not ret = find_next_read_ce[ce, var] next ret if ret to = g.to_optim[label].to_a.map { |t| break [:split] if badlabels.include? t find_next_read_rec[t, 0, var, done, badlabels] }.compact tw = to - [:write] if to.include? :split or tw.length > 1 :split elsif tw.length == 1 tw.first elsif to.include? :write :write end } # return the previous subexpr reading var with no fwd path to another reading (otherwise split), see loop comment for reason find_next_read = nil find_prev_read_rec = lambda { |label, idx, var, done| next if done.include? label done << label if idx == g.exprs[label].length-1 idx -= 1 while idx >= 0 and ce = g.exprs[label].to_a[idx] and not ret = find_next_read_ce[ce, var] if ret.kind_of? C::CExpression fwchk = find_next_read[label, idx+1, var] ret = fwchk if not fwchk.kind_of? C::CExpression end next ret if ret from = g.from_optim[label].to_a.map { |f| find_prev_read_rec[f, g.exprs[f].to_a.length-1, var, done] }.compact next :split if from.include? :split fw = from - [:write] if fw.length == 1 fw.first elsif fw.length > 1 :split elsif from.include? :write :write end } # list of labels reachable without using a label badlab = {} build_badlabel = lambda { |label| next if badlab[label] badlab[label] = [] todo = [g.start] while l = todo.pop next if l == label or badlab[label].include? l badlab[label] << l todo.concat g.to_optim[l].to_a end } # returns the next subexpr where var is read # returns :write if var is written before being read # returns :split if the codepath splits with both subpath reading or codepath merges with another # returns nil if var is never read # idx is the index of the first cexpr at g.exprs[label] to look at find_next_read = lambda { |label, idx, var| find_next_read_rec[label, idx, var, [], []] } find_prev_read = lambda { |label, idx, var| find_prev_read_rec[label, idx, var, []] } # same as find_next_read, but returns :split if there exist a path from g.start to the read without passing through label find_next_read_bl = lambda { |label, idx, var| build_badlabel[label] find_next_read_rec[label, idx, var, [], badlab[label]] } # walk each node, optimize data accesses there # replace no longer useful exprs with CExpr[nil, nil, nil], those are wiped later. g.exprs.each { |label, exprs| next if not g.block[label] i = 0 while i < exprs.length e = exprs[i] i += 1 # TODO x = x + 1 => x += 1 => ++x here, move all other optimizations after (in optim_code) # needs also int & 0xffffffff -> int, *&var etc (decomp_type? optim_type?) if (e.op == :'++' or e.op == :'--') and v = (e.lexpr || e.rexpr) and v.kind_of? C::Variable and scope.symbol[v.name] and not v.type.qualifier.to_a.include? :volatile next if !((pos = :post.to_sym) and (oe = find_next_read_bl[label, i, v]) and oe.kind_of? C::CExpression) and !((pos = :prev.to_sym) and (oe = find_prev_read[label, i-2, v]) and oe.kind_of? C::CExpression) next if oe.op == :& and not oe.lexpr # no &(++eax) # merge pre/postincrement into next/prev var usage # find_prev_read must fwd check when it finds something, to avoid # while(x) x++; return x; to be converted to while(x++); return x; (return wrong value) case oe.op when e.op # bla(i--); --i bla(--i); --i ++i; bla(i++) => ignore next if pos == :pre or oe.lexpr # ++i; bla(++i) => bla(i += 2) oe.lexpr = oe.rexpr oe.op = ((oe.op == :'++') ? :'+=' : :'-=') oe.rexpr = C::CExpression[2] when :'++', :'--' # opposite of e.op if (pos == :post and not oe.lexpr) or (pos == :pre and not oe.rexpr) # ++i; bla(--i) => bla(i) # bla(i--); ++i => bla(i) oe.op = nil elsif pos == :post # ++i; bla(i--) => bla(i+1) oe.op = ((oe.op == :'++') ? :- : :+) oe.rexpr = C::CExpression[1] elsif pos == :pre # bla(--i); ++i => bla(i-1) oe.lexpr = oe.rexpr oe.op = ((oe.op == :'++') ? :+ : :-) oe.rexpr = C::CExpression[1] end when :'+=', :'-=' # TODO i++; i += 4 => i += 5 next when *AssignOp next # ++i; i |= 4 => ignore else if pos == :post and v == oe.lexpr; oe.lexpr = C::CExpression[e.op, v] elsif pos == :post and v == oe.rexpr; oe.rexpr = C::CExpression[e.op, v] elsif pos == :prev and v == oe.rexpr; oe.rexpr = C::CExpression[v, e.op] elsif pos == :prev and v == oe.lexpr; oe.lexpr = C::CExpression[v, e.op] else raise 'foobar' # find_dir_read failed end end i -= 1 exprs.delete_at(i) e.lexpr = e.op = e.rexpr = nil elsif e.op == :'=' and v = e.lexpr and v.kind_of? C::Variable and scope.symbol[v.name] and not v.type.qualifier.to_a.include? :volatile and not find_next_read_ce[e.rexpr, v] # reduce trivial static assignments if (e.rexpr.kind_of? C::CExpression and iv = e.rexpr.reduce(@c_parser) and iv.kind_of? ::Integer) or (e.rexpr.kind_of? C::CExpression and e.rexpr.op == :& and not e.rexpr.lexpr and e.rexpr.lexpr.kind_of? C::Variable) or (e.rexpr.kind_of? C::Variable and e.rexpr.type.kind_of? C::Array) rewritten = false readers = [] discard = [e] g.exprs.each { |l, el| el.each_with_index { |ce, ci| if ce_write(ce, v) and [label, i-1] != [l, ci] if ce == e discard << ce else rewritten = true break end elsif ce_read(ce, v) if walk_ce(ce) { |_ce| break true if _ce.op == :& and not _ce.lexpr and _ce.rexpr == v } # i = 2 ; j = &i =!> j = &2 rewritten = true break end readers << ce end } if not rewritten } if not rewritten ce_patch(readers, v, C::CExpression[iv || e.rexpr]) discard.each { |d| d.lexpr = d.op = d.rexpr = nil } next end end case nr = find_next_read[label, i, v] when C::CExpression # read in one place only, try to patch rexpr in there r = e.rexpr # must check for conflicts (x = y; y += 1; foo(x) =!> foo(y)) # XXX x = a[1]; *(a+1) = 28; foo(x)... isfunc = false depend_vars = [] walk_ce(C::CExpression[r]) { |ce| isfunc = true if ce.op == :func and (not ce.lexpr.kind_of? C::Variable or not ce.lexpr.has_attribute('pure')) # XXX is there a C attr for func depending only on staticvars+param ? depend_vars << ce.lexpr if ce.lexpr.kind_of? C::Variable depend_vars << ce.rexpr if ce.rexpr.kind_of? C::Variable and (ce.lexpr or ce.op != :&) # a = &v; v = 12; func(a) => func(&v) depend_vars << ce if ce.lvalue? depend_vars.concat(ce.rexpr.grep(C::Variable)) if ce.rexpr.kind_of? ::Array } depend_vars.uniq! # XXX x = 1; if () { x = 2; } foo(x) =!> foo(1) (find_next_read will return this) # we'll just redo a find_next_read like # XXX b = &a; a = 1; *b = 2; foo(a) unhandled & generate bad C l_l = label l_i = i while g.exprs[l_l].to_a.each_with_index { |ce_, n_i| next if n_i < l_i # count occurences of read v in ce_ cnt = 0 bad = false walk_ce(ce_) { |ce| case ce.op when :funcall bad = true if isfunc ce.rexpr.each { |a| cnt += 1 if a == v } cnt += 1 if ce.lexpr == v when :'=' bad = true if depend_vars.include? ce.lexpr cnt += 1 if ce.rexpr == v else bad = true if (ce.op == :'++' or ce.op == :'--') and depend_vars.include? ce.rexpr bad = true if AssignOp.include? ce.op and depend_vars.include? ce.lexpr cnt += 1 if ce.lexpr == v cnt += 1 if ce.rexpr == v end } case cnt when 0 break if bad next when 1 # good break if e.complexity > 10 and ce_.complexity > 3 # try to keep the C readable # x = 1; y = x; z = x; => cannot suppress x nr = find_next_read[l_l, n_i+1, v] break if (nr.kind_of? C::CExpression or nr == :split) and not walk_ce(ce_) { |ce| break true if ce.op == :'=' and ce.lexpr == v } else break # a = 1; b = a + a => fail end # TODO XXX x = 1; y = x; z = x; res = walk_ce(ce_, true) { |ce| case ce.op when :funcall if ce.rexpr.to_a.each_with_index { |a,i_| next if a != v ce.rexpr[i_] = r break :done } == :done break :done elsif ce.lexpr == v ce.lexpr = r break :done elsif isfunc break :fail end when *AssignOp break :fail if not ce.lexpr and depend_vars.include? ce.rexpr # ++depend if ce.rexpr == v ce.rexpr = r break :done elsif ce.lexpr == v or depend_vars.include? ce.lexpr break :fail end else break :fail if ce.op == :& and not ce.lexpr and ce.rexpr == v if ce.lexpr == v ce.lexpr = r break :done elsif ce.rexpr == v ce_.type = r.type if not ce_.op and ce_.rexpr == v # return (int32)eax ce.rexpr = r break :done end end } case res when :done i -= 1 exprs.delete_at(i) e.lexpr = e.op = e.rexpr = nil break when :fail break end } # ignore branches that will never reuse v may_to = g.to_optim[l_l].find_all { |to| find_next_read[to, 0, v].kind_of? C::CExpression } if may_to.length == 1 and to = may_to.first and to != l_l and g.from_optim[to] == [l_l] l_i = 0 l_l = to else break end end when nil, :write # useless assignment (value never read later) # XXX foo = &bar; bar = 12; baz(*foo) e.replace(C::CExpression[e.rexpr]) # remove sideeffectless subexprs loop do case e.op when :funcall, *AssignOp else l = (e.lexpr.kind_of? C::CExpression and sideeffect(e.lexpr)) r = (e.rexpr.kind_of? C::CExpression and sideeffect(e.rexpr)) if l and r # could split... elsif l e.replace(e.lexpr) next elsif r e.replace(e.rexpr) next else # remove the assignment altogether i -= 1 exprs.delete_at(i) e.lexpr = e.op = e.rexpr = nil end end break end end end end } # wipe cexprs marked in the previous step walk(scope) { |st| next if not st.kind_of? C::Block st.statements.delete_if { |e| e.kind_of? C::CExpression and not e.lexpr and not e.op and not e.rexpr } } # reoptimize cexprs walk_ce(scope, true) { |ce| # redo some simplification that may become available after variable propagation # int8 & 255 => int8 if ce.op == :& and ce.lexpr and ce.lexpr.type.integral? and ce.rexpr.kind_of? C::CExpression and not ce.rexpr.op and ce.rexpr.rexpr == (1 << (8*sizeof(ce.lexpr))) - 1 ce.replace C::CExpression[ce.lexpr] end # int *ptr; *(ptr + 4) => ptr[4] if ce.op == :* and not ce.lexpr and ce.rexpr.kind_of? C::CExpression and ce.rexpr.op == :+ and var = ce.rexpr.lexpr and var.kind_of? C::Variable and var.type.pointer? ce.lexpr, ce.op, ce.rexpr = ce.rexpr.lexpr, :'[]', ce.rexpr.rexpr end # useless casts if not ce.op and ce.rexpr.kind_of? C::CExpression and not ce.rexpr.op and (ce.rexpr.rexpr.kind_of? C::CExpression or (ce.type.pointer? and ce.rexpr.rexpr == 0 and not ce.type.pointed.untypedef.kind_of? C::Union)) # keep ((struct*)0)->memb ce.rexpr = ce.rexpr.rexpr end if not ce.op and ce.rexpr.kind_of? C::CExpression and (ce.type == ce.rexpr.type or (ce.type.integral? and ce.rexpr.type.integral?)) ce.replace ce.rexpr end # useless casts (type)*((oeua)Ptype) if not ce.op and ce.rexpr.kind_of? C::CExpression and ce.rexpr.op == :* and not ce.rexpr.lexpr and ce.rexpr.rexpr.kind_of? C::CExpression and not ce.rexpr.rexpr.op and p = ce.rexpr.rexpr.rexpr and p.kind_of? C::Typed and p.type.pointer? and ce.type == p.type.pointed ce.op = ce.rexpr.op ce.rexpr = ce.rexpr.rexpr.rexpr end # (a > 0) != 0 if ce.op == :'!=' and ce.rexpr.kind_of? C::CExpression and not ce.rexpr.op and ce.rexpr.rexpr == 0 and ce.lexpr.kind_of? C::CExpression and [:<, :<=, :>, :>=, :'==', :'!=', :'!'].include? ce.lexpr.op ce.replace ce.lexpr end # a == 0 => !a if ce.op == :== and ce.rexpr.kind_of? C::CExpression and not ce.rexpr.op and ce.rexpr.rexpr == 0 ce.replace C::CExpression[:'!', ce.lexpr] end # !(int)a => !a if ce.op == :'!' and ce.rexpr.kind_of? C::CExpression and not ce.rexpr.op and ce.rexpr.rexpr.kind_of? C::CExpression ce.rexpr = ce.rexpr.rexpr end # (int)a < (int)b => a < b TODO uint <-> int if [:<, :<=, :>, :>=].include? ce.op and ce.rexpr.kind_of? C::CExpression and ce.lexpr.kind_of? C::CExpression and not ce.rexpr.op and not ce.lexpr.op and ce.rexpr.rexpr.kind_of? C::CExpression and ce.rexpr.rexpr.type.pointer? and ce.lexpr.rexpr.kind_of? C::CExpression and ce.lexpr.rexpr.type.pointer? ce.rexpr = ce.rexpr.rexpr ce.lexpr = ce.lexpr.rexpr end # a & 3 & 1 while (ce.op == :& or ce.op == :|) and ce.rexpr.kind_of? C::CExpression and not ce.rexpr.op and ce.rexpr.rexpr.kind_of? ::Integer and ce.lexpr.kind_of? C::CExpression and ce.lexpr.op == ce.op and ce.lexpr.lexpr and ce.lexpr.rexpr.kind_of? C::CExpression and ce.lexpr.rexpr.rexpr.kind_of? ::Integer ce.lexpr, ce.rexpr.rexpr = ce.lexpr.lexpr, ce.lexpr.rexpr.rexpr.send(ce.op, ce.rexpr.rexpr) end # x = x | 4 => x |= 4 if ce.op == :'=' and ce.rexpr.kind_of? C::CExpression and [:+, :-, :*, :/, :|, :&, :^, :>>, :<<].include? ce.rexpr.op and ce.rexpr.lexpr == ce.lexpr ce.op = (ce.rexpr.op.to_s + '=').to_sym ce.rexpr = ce.rexpr.rexpr end # x += 1 => ++x if (ce.op == :'+=' or ce.op == :'-=') and ce.rexpr.kind_of? C::CExpression and not ce.rexpr.op and ce.rexpr.rexpr == 1 ce.lexpr, ce.op, ce.rexpr = nil, {:'+=' => :'++', :'-=' => :'--'}[ce.op], ce.lexpr end # --x+1 => x-- if (ce.op == :+ or ce.op == :-) and ce.lexpr.kind_of? C::CExpression and ce.lexpr.op == {:+ => :'--', :- => :'++'}[ce.op] and ce.lexpr.rexpr and ce.rexpr.kind_of? C::CExpression and not ce.rexpr.op and ce.rexpr.rexpr == 1 ce.lexpr, ce.op, ce.rexpr = ce.lexpr.rexpr, ce.lexpr.op, nil end } end
dataflow optimization condenses expressions (++x; if (x) => if (++x)) remove local var assignment (x = 1; f(x); x = 2; g(x); => f(1); g(2); etc)
optimize_vars
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decompile.rb
BSD-3-Clause
def cleanup_var_decl(scope, func) scope.symbol.each_value { |v| v.type = C::BaseType.new(:int) if v.type.void? } args = func.type.args decl = [] scope.statements.delete_if { |sm| next if not sm.kind_of? C::Declaration if sm.var.stackoff.to_i > 0 and sm.var.name !~ /_a(\d+)$/ # aliased vars: use 1st domain only args << sm.var else decl << sm end true } # move trivial affectations to initialiser # XXX a = 1 ; b = a ; a = 2 go = true # break from delete_if does not delete.. scope.statements.delete_if { |st| if go and st.kind_of? C::CExpression and st.op == :'=' and st.rexpr.kind_of? C::CExpression and not st.rexpr.op and st.rexpr.rexpr.kind_of? ::Integer and st.lexpr.kind_of? C::Variable and scope.symbol[st.lexpr.name] st.lexpr.initializer = st.rexpr else go = false end } # reorder declarations scope.statements[0, 0] = decl.sort_by { |sm| [-sm.var.stackoff.to_i, sm.var.name] } # ensure arglist has no hole (create&add unreferenced args) func.type.args = [] argoff = @c_parser.typesize[:ptr] args.sort_by { |sm| sm.stackoff.to_i }.each { |a| # XXX misalignment ? if not curoff = a.stackoff func.type.args << a # __fastcall next end while curoff > argoff wantarg = C::Variable.new wantarg.name = scope.decompdata[:stackoff_name][argoff] || stackoff_to_varname(argoff) wantarg.type = C::BaseType.new(:int) wantarg.attributes = ['unused'] func.type.args << wantarg scope.symbol[wantarg.name] = wantarg argoff += @c_parser.typesize[:ptr] end func.type.args << a argoff += @c_parser.typesize[:ptr] } end
reorder statements to put decl first, move assignments to decl, move args to func prototype
cleanup_var_decl
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decompile.rb
BSD-3-Clause
def rename_variables(scope) funcs = [] cntrs = [] cmpi = [] walk_ce(scope) { |ce| funcs << ce if ce.op == :funcall cntrs << (ce.lexpr || ce.rexpr) if ce.op == :'++' cmpi << ce.lexpr if [:<, :>, :<=, :>=, :==, :'!='].include? ce.op and ce.rexpr.kind_of? C::CExpression and ce.rexpr.rexpr.kind_of? ::Integer } rename = lambda { |var, name| var = var.rexpr if var.kind_of? C::CExpression and not var.op next if not var.kind_of? C::Variable or not scope.symbol[var.name] or not name next if (var.name !~ /^(var|arg)_/ and not var.storage == :register) or not scope.symbol[var.name] or name =~ /^(var|arg)_/ s = scope.symbol_ancestors n = name i = 0 n = name + "#{i+=1}" while s[n] scope.symbol[n] = scope.symbol.delete(var.name) var.name = n } funcs.each { |ce| next if not ce.lexpr.kind_of? C::Variable or not ce.lexpr.type.kind_of? C::Function ce.rexpr.to_a.zip(ce.lexpr.type.args.to_a).each { |a, fa| rename[a, fa.name] if fa } } funcs.each { |ce| next if not ce.lexpr.kind_of? C::Variable or not ce.lexpr.type.kind_of? C::Function ce.rexpr.to_a.zip(ce.lexpr.type.args.to_a).each { |a, fa| next if not a.kind_of? C::CExpression or a.op != :& or a.lexpr next if not fa or not fa.name rename[a.rexpr, fa.name.sub(/^l?p/, '')] } } (cntrs & cmpi).each { |v| rename[v, 'cntr'] } end
rename local variables from subfunc arg names
rename_variables
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decompile.rb
BSD-3-Clause
def walk_ce(ce, post=false, &b) case ce when C::CExpression yield ce if not post walk_ce(ce.lexpr, post, &b) walk_ce(ce.rexpr, post, &b) yield ce if post when ::Array ce.each { |ce_| walk_ce(ce_, post, &b) } when C::Statement case ce when C::Block; walk_ce(ce.statements, post, &b) when C::If walk_ce(ce.test, post, &b) walk_ce(ce.bthen, post, &b) walk_ce(ce.belse, post, &b) if ce.belse when C::While, C::DoWhile walk_ce(ce.test, post, &b) walk_ce(ce.body, post, &b) when C::Return walk_ce(ce.value, post, &b) if ce.value end when C::Declaration walk_ce(ce.var.initializer, post, &b) if ce.var.initializer end nil end
yield each CExpr member (recursive, allows arrays, order: self(!post), lexpr, rexpr, self(post)) if given a non-CExpr, walks it until it finds a CExpr to yield
walk_ce
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decompile.rb
BSD-3-Clause
def sizeof(var, type=nil) var, type = nil, var if var.kind_of? C::Type and not type type ||= var.type return @c_parser.typesize[:ptr] if type.kind_of? C::Array and not var.kind_of? C::Variable @c_parser.sizeof(var, type) rescue -1 end
forwards to @c_parser, handles cast to Array (these should not happen btw...)
sizeof
ruby
stephenfewer/grinder
node/lib/metasm/metasm/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/decompile.rb
BSD-3-Clause
def initialize(arg, addr=nil) case arg when Instruction @instruction = arg @opcode = @instruction.cpu.opcode_list.find { |op| op.name == @instruction.opname } if @instruction.cpu else @instruction = Instruction.new(arg) end @bin_length = 0 @address = addr if addr end
create a new DecodedInstruction with an Instruction whose cpu is the argument can take an existing Instruction as argument
initialize
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def dup new = super() new.instruction = @instruction.dup new end
returns a copy of the DecInstr, with duplicated #instruction ("deep_copy")
dup
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def initialize(type, origin, len=nil) @origin, @type = origin, type @len = len if len end
XXX list of instructions intervening in the backtrace ?
initialize
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def initialize(arg0, edata=nil, edata_ptr=nil) @list = [] case arg0 when DecodedInstruction @address = arg0.address add_di(arg0) when Array @address = arg0.first.address if not arg0.empty? arg0.each { |di| add_di(di) } else @address = arg0 end edata_ptr ||= edata ? edata.ptr : 0 @edata, @edata_ptr = edata, edata_ptr @backtracked_for = [] end
create a new InstructionBlock based at address also accepts a DecodedInstruction or an Array of them to initialize from
initialize
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def split(addr) raise "invalid split @#{Expression[addr]}" if not idx = @list.index(@list.find { |di| di.address == addr }) or idx == 0 off = @list[idx].block_offset new_b = self.class.new(addr, @edata, @edata_ptr + off) new_b.add_di @list.delete_at(idx) while @list[idx] new_b.to_normal, @to_normal = to_normal, new_b.to_normal new_b.to_subfuncret, @to_subfuncret = to_subfuncret, new_b.to_subfuncret new_b.add_from @list.last.address add_to new_b.address @backtracked_for.delete_if { |btt| if btt.address and new_b.list.find { |di| di.address == btt.address } new_b.backtracked_for << btt true end } new_b end
splits the current block into a new one with all di from address addr to end caller is responsible for rebacktracing new.bt_for to regenerate correct old.btt/new.btt
split
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def add_di(di) di.block = self di.block_offset = bin_length di.address ||= @address + di.block_offset @list << di end
adds a decodedinstruction to the block list, updates di.block and di.block_offset
add_di
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def get_backtrace_binding(dasm, funcaddr, calladdr, expr, origin, maxdepth) if btbind_callback @btbind_callback[dasm, @backtrace_binding, funcaddr, calladdr, expr, origin, maxdepth] elsif backtrace_binding and dest = @backtrace_binding[:thunk] and target = dasm.function[dest] target.get_backtrace_binding(dasm, funcaddr, calladdr, expr, origin, maxdepth) else unk_regs = expr.externals.grep(Symbol).uniq - @backtrace_binding.keys - [:unknown] dasm.cpu.backtrace_update_function_binding(dasm, funcaddr, self, return_address, *unk_regs) if not unk_regs.empty? @backtrace_binding end end
if btbind_callback is defined, calls it with args [dasm, binding, funcaddr, calladdr, expr, origin, maxdepth] else update lazily the binding from expr.externals, and return backtrace_binding
get_backtrace_binding
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def get_backtracked_for(dasm, funcaddr, calladdr) if btfor_callback @btfor_callback[dasm, @backtracked_for, funcaddr, calladdr] elsif backtrace_binding and dest = @backtrace_binding[:thunk] and target = dasm.function[dest] target.get_backtracked_for(dasm, funcaddr, calladdr) else @backtracked_for end end
if btfor_callback is defined, calls it with args [dasm, bt_for, funcaddr, calladdr] else return backtracked_for
get_backtracked_for
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def backtrace_emu(di, value) Expression[Expression[value].bind(di.backtrace_binding ||= get_backtrace_binding(di)).reduce] end
return the thing to backtrace to find +value+ before the execution of this instruction eg backtrace_emu('inc eax', Expression[:eax]) => Expression[:eax + 1] (the value of :eax after 'inc eax' is the value of :eax before plus 1) may return Expression::Unknown
backtrace_emu
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def get_xrefs_rw(dasm, di) get_xrefs_r(dasm, di).map { |addr, len| [:r, addr, len] } + get_xrefs_w(dasm, di).map { |addr, len| [:w, addr, len] } end
returns a list of [type, address, len]
get_xrefs_rw
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def replace_instr_arg_immediate(i, old, new) i.args.map! { |a| case a when Expression; Expression[a.bind(old => new).reduce] else a end } end
updates the instruction arguments: replace an expression with another (eg when a label is renamed)
replace_instr_arg_immediate
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def dump_section_header(addr, edata) "\n// section at #{Expression[addr]}" end
returns a string containing asm-style section declaration
dump_section_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def add_section(encoded, base) encoded, base = base, encoded if base.kind_of? EncodedData case base when ::Integer when ::String raise "invalid section base #{base.inspect} - not at section start" if encoded.export[base] and encoded.export[base] != 0 if ed = get_edata_at(base) ed.del_export(base) end encoded.add_export base, 0 else raise "invalid section base #{base.inspect} - expected string or integer" end @sections[base] = encoded @label_alias_cache = nil encoded.binding(base).each { |k, v| @old_prog_binding[k] = @prog_binding[k] = v.reduce } # update section_edata.reloc # label -> list of relocs that refers to it @inv_section_reloc ||= {} @sections.each { |b, e| e.reloc.each { |o, r| r.target.externals.grep(::String).each { |ext| (@inv_section_reloc[ext] ||= []) << [b, e, o, r] } } } self end
adds a section, updates prog_binding base addr is an Integer or a String (label name for offset 0)
add_section
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def each_xref(addr, type=nil) addr = normalize addr x = @xrefs[addr] x = case x when nil; [] when ::Array; x.dup else [x] end x.delete_if { |x_| x_.type != type } if type # add pseudo-xrefs for exe relocs if (not type or type == :reloc) and l = get_label_at(addr) and a = @inv_section_reloc[l] a.each { |b, e, o, r| addr = Expression[b]+o # ignore relocs embedded in an already-listed instr x << Xref.new(:reloc, addr) if not x.find { |x_| next if not x_.origin or not di_at(x_.origin) (addr - x_.origin) < @decoded[x_.origin].bin_length rescue false } } end x.each { |x_| yield x_ } end
yields each xref to a given address, optionnaly restricted to a type
each_xref
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def parse_c_file(file) parse_c File.read(file), file end
parses a C header file, from which function prototypes will be converted to DecodedFunction when found in the code flow
parse_c_file
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def c_constants @c_parser_constcache ||= @c_parser.numeric_constants end
list the constants ([name, integer value]) defined in the C code (#define / enums)
c_constants
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def normalize(addr) return addr if not addr or addr == :default addr = Expression[addr].bind(@old_prog_binding).reduce if not addr.kind_of? Integer addr %= 1 << [@cpu.size, 32].max if @cpu and addr.kind_of? Integer addr end
returns the canonical form of addr (absolute address integer or label of start of section + section offset)
normalize
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def get_section_at(addr, memcheck=true) case addr = normalize(addr) when ::Integer if s = @sections.find { |b, e| b.kind_of? ::Integer and addr >= b and addr < b + e.length } || @sections.find { |b, e| b.kind_of? ::Integer and addr == b + e.length } # end label s[1].ptr = addr - s[0] return if memcheck and s[1].data.respond_to?(:page_invalid?) and s[1].data.page_invalid?(s[1].ptr) [s[1], s[0]] end when Expression if addr.op == :+ and addr.rexpr.kind_of? ::Integer and addr.rexpr >= 0 and addr.lexpr.kind_of? ::String and e = @sections[addr.lexpr] e.ptr = addr.rexpr return if memcheck and e.data.respond_to?(:page_invalid?) and e.data.page_invalid?(e.ptr) [e, Expression[addr.lexpr]] elsif addr.op == :+ and addr.rexpr.kind_of? ::String and not addr.lexpr and e = @sections[addr.rexpr] e.ptr = 0 return if memcheck and e.data.respond_to?(:page_invalid?) and e.data.page_invalid?(e.ptr) [e, addr.rexpr] end end end
returns [edata, edata_base] or nil edata.ptr points to addr
get_section_at
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def auto_label_at(addr, base='xref', *rewritepfx) addr = Expression[addr].reduce addrstr = "#{base}_#{Expression[addr]}" return if addrstr !~ /^\w+$/ e, b = get_section_at(addr) if not e l = Expression[addr].reduce_rec if Expression[addr].reduce_rec.kind_of? ::String l ||= addrstr if addr.kind_of? Expression and addr.externals.grep(::Symbol).empty? elsif not l = e.inv_export[e.ptr] l = @program.new_label(addrstr) e.add_export l, e.ptr @label_alias_cache = nil @old_prog_binding[l] = @prog_binding[l] = b + e.ptr elsif rewritepfx.find { |p| base != p and addrstr.sub(base, p) == l } newl = addrstr newl = @program.new_label(newl) unless @old_prog_binding[newl] and @old_prog_binding[newl] == @prog_binding[l] # avoid _uuid when a -> b -> a rename_label l, newl l = newl end l end
returns the label at the specified address, creates it if needed using "prefix_addr" renames the existing label if it is in the form rewritepfx_addr returns nil if the address is not known and is not a string
auto_label_at
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def label_alias if not @label_alias_cache @label_alias_cache = {} @prog_binding.each { |k, v| (@label_alias_cache[v] ||= []) << k } end @label_alias_cache end
returns a hash associating addr => list of labels at this addr label_alias[a] may be nil if a new label is created elsewhere in the edata with the same name
label_alias
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def disassemble(*entrypoints) nil while disassemble_mainiter(entrypoints) self end
decodes instructions from an entrypoint, (tries to) follows code flow
disassemble
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def disassemble_mainiter(entrypoints=[]) @entrypoints ||= [] if @addrs_todo.empty? and entrypoints.empty? post_disassemble puts 'disassembly finished' if $VERBOSE @callback_finished[] if callback_finished return false elsif @addrs_todo.empty? ep = entrypoints.shift l = auto_label_at(normalize(ep), 'entrypoint') puts "start disassemble from #{l} (#{entrypoints.length})" if $VERBOSE and not entrypoints.empty? @entrypoints << l @addrs_todo << [ep] else disassemble_step end true end
do one operation relevant to disassembling returns nil once done
disassemble_mainiter
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def disassemble_step return if not todo = @addrs_todo.pop or @addrs_done.include? todo @addrs_done << todo if todo[1] # from_sfret is true if from is the address of a function call that returns to addr addr, from, from_subfuncret = todo return if from == Expression::Unknown puts "disassemble_step #{Expression[addr]} #{Expression[from] if from} #{from_subfuncret} (/#{@addrs_todo.length})" if $DEBUG addr = normalize(addr) if from and from_subfuncret and di_at(from) @decoded[from].block.each_to_normal { |subfunc| subfunc = normalize(subfunc) next if not f = @function[subfunc] or f.finalized f.finalized = true puts " finalize subfunc #{Expression[subfunc]}" if debug_backtrace backtrace_update_function_binding(subfunc, f) if not f.return_address detect_function_thunk(subfunc) end } end if di = @decoded[addr] if di.kind_of? DecodedInstruction split_block(di.block, di.address, true) if not di.block_head? # this updates di.block di.block.add_from(from, from_subfuncret ? :subfuncret : :normal) if from and from != :default bf = di.block elsif di == true bf = @function[addr] end elsif bf = @function[addr] detect_function_thunk_noreturn(from) if bf.noreturn elsif s = get_section_at(addr) block = InstructionBlock.new(normalize(addr), s[0]) block.add_from(from, from_subfuncret ? :subfuncret : :normal) if from and from != :default disassemble_block(block) elsif from and c_parser and name = Expression[addr].reduce_rec and name.kind_of? ::String and s = c_parser.toplevel.symbol[name] and s.type.untypedef.kind_of? C::Function bf = @function[addr] = @cpu.decode_c_function_prototype(@c_parser, s) detect_function_thunk_noreturn(from) if bf.noreturn elsif from if bf = @function[:default] puts "using default function for #{Expression[addr]} from #{Expression[from]}" if $DEBUG if name = Expression[addr].reduce_rec and name.kind_of? ::String @function[addr] = @function[:default].dup else addr = :default end if @decoded[from] @decoded[from].block.add_to addr end else puts "not disassembling unknown address #{Expression[addr]} from #{Expression[from]}" if $DEBUG end if from != :default add_xref(addr, Xref.new(:x, from)) add_xref(Expression::Unknown, Xref.new(:x, from)) end else puts "not disassembling unknown address #{Expression[addr]}" if $VERBOSE end if bf and from and from != :default if bf.kind_of? DecodedFunction bff = bf.get_backtracked_for(self, addr, from) else bff = bf.backtracked_for end end bff.each { |btt| next if btt.address if @decoded[from].kind_of? DecodedInstruction and @decoded[from].opcode.props[:saveip] and not from_subfuncret and not @function[addr] backtrace_check_found(btt.expr, @decoded[addr], btt.origin, btt.type, btt.len, btt.maxdepth, btt.detached) end next if backtrace_check_funcret(btt, addr, from) backtrace(btt.expr, from, :include_start => true, :from_subfuncret => from_subfuncret, :origin => btt.origin, :orig_expr => btt.orig_expr, :type => btt.type, :len => btt.len, :detached => btt.detached, :maxdepth => btt.maxdepth) } if bff end
disassembles one block from addrs_todo adds next addresses to handle to addrs_todo if @function[:default] exists, jumps to unknows locations are interpreted as to @function[:default]
disassemble_step
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def split_block(block, address=nil, rebacktrace=false) if not address # invoked as split_block(0x401012) return if not @decoded[block].kind_of? DecodedInstruction block, address = @decoded[block].block, block end return block if address == block.address new_b = block.split address if rebacktrace new_b.backtracked_for.dup.each { |btt| backtrace(btt.expr, btt.address, :only_upto => block.list.last.address, :include_start => !btt.exclude_instr, :from_subfuncret => btt.from_subfuncret, :origin => btt.origin, :orig_expr => btt.orig_expr, :type => btt.type, :len => btt.len, :detached => btt.detached, :maxdepth => btt.maxdepth) } end new_b end
splits an InstructionBlock, updates the blocks backtracked_for
split_block
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def disassemble_block(block) raise if not block.list.empty? di_addr = block.address delay_slot = nil di = nil # try not to run for too long # loop usage: break if the block continues to the following instruction, else return @disassemble_maxblocklength.times { # check collision into a known block break if @decoded[di_addr] # check self-modifying code if @check_smc #(-7...di.bin_length).each { |off| # uncomment to check for unaligned rewrites waddr = di_addr #di_addr + off each_xref(waddr, :w) { |x| #next if off + x.len < 0 puts "W: disasm: self-modifying code at #{Expression[waddr]}" if $VERBOSE add_comment(di_addr, "overwritten by #{@decoded[x.origin]}") @callback_selfmodifying[di_addr] if callback_selfmodifying return } #} end # decode instruction block.edata.ptr = di_addr - block.address + block.edata_ptr if not di = @cpu.decode_instruction(block.edata, di_addr) ed = block.edata break if ed.ptr >= ed.length and get_section_at(di_addr) and di = block.list.last puts "#{ed.ptr >= ed.length ? "end of section reached" : "unknown instruction #{ed.data[di_addr-block.address+block.edata_ptr, 4].to_s.unpack('H*')}"} at #{Expression[di_addr]}" if $VERBOSE return end @decoded[di_addr] = di block.add_di di puts di if $DEBUG if callback_newinstr ndi = @callback_newinstr[di] if not ndi or not ndi.block block.list.delete di if ndi block.add_di ndi ndi.bin_length = di.bin_length if ndi.bin_length == 0 @decoded[di_addr] = ndi end end di = ndi end return if not di block = di.block di_addr = di.next_addr backtrace_xrefs_di_rw(di) if not di_addr or di.opcode.props[:stopexec] or not @program.get_xrefs_x(self, di).empty? # do not backtrace until delay slot is finished (eg MIPS: di is a # ret and the delay slot holds stack fixup needed to calc func_binding) # XXX if the delay slot is also xref_x or :stopexec it is ignored delay_slot ||= [di, @cpu.delay_slot(di)] end if delay_slot di, delay = delay_slot if delay == 0 or not di_addr backtrace_xrefs_di_x(di) if di.opcode.props[:stopexec] or not di_addr; return else break end end delay_slot[1] = delay - 1 end } ar = [di_addr] ar = @callback_newaddr[block.list.last.address, ar] || ar if callback_newaddr ar.each { |di_addr_| backtrace(di_addr_, di.address, :origin => di.address, :type => :x) } block end
disassembles a new instruction block at block.address (must be normalized)
disassemble_block
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def get_xrefs_x(di) @program.get_xrefs_x(self, di) end
retrieve the list of execution crossrefs due to the decodedinstruction returns a list of symbolic expressions
get_xrefs_x
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def get_xrefs_rw(di) @program.get_xrefs_rw(self, di) end
retrieve the list of data r/w crossrefs due to the decodedinstruction returns a list of [type, symbolic expression, length]
get_xrefs_rw
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def disassemble_fast_deep(*entrypoints) @entrypoints ||= [] @entrypoints |= entrypoints entrypoints.each { |ep| do_disassemble_fast_deep(normalize(ep)) } @callback_finished[] if callback_finished end
disassembles_fast from a list of entrypoints, also dasm subfunctions
disassemble_fast_deep
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def disassemble_fast(entrypoint, maxdepth=-1, &b) ep = [entrypoint] until ep.empty? disassemble_fast_step(ep, &b) maxdepth -= 1 ep.delete_if { |a| not @decoded[normalize(a[0])] } if maxdepth == 0 end check_noreturn_function(entrypoint) end
disassembles fast from a list of entrypoints see disassemble_fast_step
disassemble_fast
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def disassemble_fast_step(todo, &b) return if not x = todo.pop addr, from, from_subfuncret = x addr = normalize(addr) if di = @decoded[addr] if di.kind_of? DecodedInstruction split_block(di.block, di.address) if not di.block_head? di.block.add_from(from, from_subfuncret ? :subfuncret : :normal) if from and from != :default end elsif s = get_section_at(addr) block = InstructionBlock.new(normalize(addr), s[0]) block.add_from(from, from_subfuncret ? :subfuncret : :normal) if from and from != :default todo.concat disassemble_fast_block(block, &b) elsif name = Expression[addr].reduce_rec and name.kind_of? ::String and not @function[addr] if c_parser and s = c_parser.toplevel.symbol[name] and s.type.untypedef.kind_of? C::Function @function[addr] = @cpu.decode_c_function_prototype(@c_parser, s) detect_function_thunk_noreturn(from) if @function[addr].noreturn elsif @function[:default] @function[addr] = @function[:default].dup end end disassemble_fast_checkfunc(addr) end
disassembles one block from the ary, see disassemble_fast_block
disassemble_fast_step
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def disassemble_fast_checkfunc(addr) if @decoded[addr].kind_of? DecodedInstruction and not @function[addr] func = false each_xref(addr, :x) { |x_| func = true if odi = di_at(x_.origin) and odi.opcode.props[:saveip] } if func auto_label_at(addr, 'sub', 'loc', 'xref') @function[addr] = (@function[:default] || DecodedFunction.new).dup @function[addr].finalized = true detect_function_thunk(addr) puts "found new function #{get_label_at(addr)} at #{Expression[addr]}" if $VERBOSE end end end
check if an addr has an xref :x from a :saveip, if so mark as Function
disassemble_fast_checkfunc
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def disassemble_fast_block(block, &b) block = InstructionBlock.new(normalize(block), get_section_at(block)[0]) if not block.kind_of? InstructionBlock di_addr = block.address delay_slot = nil di = nil ret = [] return ret if @decoded[di_addr] @disassemble_maxblocklength.times { break if @decoded[di_addr] # decode instruction block.edata.ptr = di_addr - block.address + block.edata_ptr if not di = @cpu.decode_instruction(block.edata, di_addr) break if block.edata.ptr >= block.edata.length and get_section_at(di_addr) and di = block.list.last return ret end @decoded[di_addr] = di block.add_di di puts di if $DEBUG if callback_newinstr ndi = @callback_newinstr[di] if not ndi or not ndi.block block.list.delete di if ndi block.add_di ndi ndi.bin_length = di.bin_length if ndi.bin_length == 0 @decoded[di_addr] = ndi end end di = ndi end return ret if not di di_addr = di.next_addr if di.opcode.props[:stopexec] or di.opcode.props[:setip] if di.opcode.props[:setip] @addrs_todo = [] ar = @program.get_xrefs_x(self, di) ar = @callback_newaddr[di.address, ar] || ar if callback_newaddr ar.each { |expr| backtrace(expr, di.address, :origin => di.address, :type => :x, :maxdepth => @backtrace_maxblocks_fast) } end if di.opcode.props[:saveip] @addrs_todo = [] ret.concat disassemble_fast_block_subfunc(di, &b) else ret.concat @addrs_todo @addrs_todo = [] end delay_slot ||= [di, @cpu.delay_slot(di)] end if delay_slot if delay_slot[1] <= 0 return ret if delay_slot[0].opcode.props[:stopexec] break end delay_slot[1] -= 1 end } ar = [di_addr] ar = @callback_newaddr[block.list.last.address, ar] || ar if callback_newaddr ar.each { |a| di.block.add_to_normal(a) ret << [a, di.address] } ret end
disassembles fast a new instruction block at block.address (must be normalized) does not recurse into subfunctions assumes all :saveip returns, except those pointing to a subfunc with noreturn yields subfunction addresses (targets of :saveip) no backtrace for :x (change with backtrace_maxblocks_fast) returns a todo-style ary assumes @addrs_todo is empty
disassemble_fast_block
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def disassemble_fast_block_subfunc(di) funcs = di.block.to_normal.to_a do_ret = funcs.empty? ret = [] na = di.next_addr + di.bin_length * @cpu.delay_slot(di) funcs.each { |fa| fa = normalize(fa) disassemble_fast_checkfunc(fa) yield fa, di if block_given? if f = @function[fa] and bf = f.get_backtracked_for(self, fa, di.address) and not bf.empty? # this includes retaddr unless f is noreturn bf.each { |btt| next if btt.type != :x bt = backtrace(btt.expr, di.address, :include_start => true, :origin => btt.origin, :maxdepth => [@backtrace_maxblocks_fast, 1].max) if btt.detached ret.concat bt # callback argument elsif bt.find { |a| normalize(a) == na } do_ret = true end } elsif not f or not f.noreturn do_ret = true end } if do_ret di.block.add_to_subfuncret(na) ret << [na, di.address, true] di.block.add_to_normal :default if not di.block.to_normal and @function[:default] end ret end
handles when disassemble_fast encounters a call to a subfunction
disassemble_fast_block_subfunc
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def backtrace_xrefs_di_rw(di) get_xrefs_rw(di).each { |type, ptr, len| backtrace(ptr, di.address, :origin => di.address, :type => type, :len => len).each { |xaddr| next if xaddr == Expression::Unknown if @check_smc and type == :w #len.times { |off| # check unaligned ? waddr = xaddr #+ off if wdi = di_at(waddr) puts "W: disasm: #{di} overwrites #{wdi}" if $VERBOSE wdi.add_comment "overwritten by #{di}" end #} end } } end
trace whose xrefs this di is responsible of
backtrace_xrefs_di_rw
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def detect_function_thunk(funcaddr) # check thunk linearity (no conditionnal branch etc) addr = funcaddr count = 0 while b = block_at(addr) count += 1 return if count > 5 or b.list.length > 5 if b.to_subfuncret and not b.to_subfuncret.empty? return if b.to_subfuncret.length != 1 addr = normalize(b.to_subfuncret.first) return if not b.to_normal or b.to_normal.length != 1 # check that the subfunction is simple (eg get_eip) return if not sf = @function[normalize(b.to_normal.first)] return if not btb = sf.backtrace_binding btb = btb.dup btb.delete_if { |k, v| Expression[k] == Expression[v] } return if btb.length > 2 or btb.values.include? Expression::Unknown else return if not bt = b.to_normal if bt.include? :default addr = :default break elsif bt.length != 1 return end addr = normalize(bt.first) end end fname = Expression[addr].reduce_rec if funcaddr != addr and f = @function[funcaddr] # forward get_backtrace_binding to target f.backtrace_binding = { :thunk => addr } f.noreturn = true if @function[addr] and @function[addr].noreturn end return if not fname.kind_of? ::String l = auto_label_at(funcaddr, 'sub', 'loc') return if l[0, 4] != 'sub_' puts "found thunk for #{fname} at #{Expression[funcaddr]}" if $DEBUG rename_label(l, @program.new_label("thunk_#{fname}")) end
checks if the function starting at funcaddr is an external function thunk (eg jmp [SomeExtFunc]) the argument must be the address of a decodedinstruction that is the first of a function, which must not have return_addresses returns the new thunk name if it was changed
detect_function_thunk
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def detect_function_thunk_noreturn(addr) 5.times { return if not di = di_at(addr) if di.opcode.props[:saveip] and not di.block.to_subfuncret if di.block.to_normal.to_a.length == 1 taddr = normalize(di.block.to_normal.first) if di_at(taddr) @function[taddr] ||= DecodedFunction.new return detect_function_thunk(taddr) end end break else from = di.block.from_normal.to_a + di.block.from_subfuncret.to_a if from.length == 1 addr = from.first else break end end } end
this is called when reaching a noreturn function call, with the call address it is responsible for detecting the actual 'call' instruction leading to this noreturn function, and eventually mark the call target as a thunk
detect_function_thunk_noreturn
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def check_noreturn_function(fa) fb = function_blocks(fa, false, false) lasts = fb.keys.find_all { |k| fb[k] == [] } return if lasts.empty? if lasts.all? { |la| b = block_at(la) next if not di = b.list.last (di.opcode.props[:saveip] and b.to_normal.to_a.all? { |tfa| tf = function_at(tfa) and tf.noreturn }) or (di.opcode.props[:stopexec] and not di.opcode.props[:setip]) } # yay @function[fa] ||= DecodedFunction.new @function[fa].noreturn = true end end
given an address, detect if it may be a noreturn fuction it is if all its end blocks are calls to noreturn functions if it is, create a @function[fa] with noreturn = true should only be called with fa = target of a call
check_noreturn_function
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def backtrace_walk(obj, addr, include_start, from_subfuncret, stopaddr, maxdepth) start_addr = normalize(addr) stopaddr = [stopaddr] if stopaddr and not stopaddr.kind_of? ::Array # array of [obj, addr, from_subfuncret, loopdetect] # loopdetect is an array of [obj, addr, from_type] of each end of block encountered todo = [] # array of [obj, blockaddr] # avoids rewalking the same value done = [] # updates todo with the addresses to backtrace next walk_up = lambda { |w_obj, w_addr, w_loopdetect| if w_loopdetect.length > maxdepth yield :maxdepth, w_obj, :addr => w_addr, :loopdetect => w_loopdetect elsif stopaddr and stopaddr.include?(w_addr) yield :stopaddr, w_obj, :addr => w_addr, :loopdetect => w_loopdetect elsif w_di = @decoded[w_addr] and w_di != w_di.block.list.first and w_di.address != w_di.block.address prevdi = w_di.block.list[w_di.block.list.index(w_di)-1] todo << [w_obj, prevdi.address, :normal, w_loopdetect] elsif w_di next if done.include? [w_obj, w_addr] done << [w_obj, w_addr] hadsomething = false w_di.block.each_from { |f_addr, f_type| next if f_type == :indirect hadsomething = true o_f_addr = f_addr f_addr = @decoded[f_addr].block.list.last.address if @decoded[f_addr].kind_of? DecodedInstruction # delay slot if l = w_loopdetect.find { |l_obj, l_addr, l_type| l_addr == f_addr and l_type == f_type } f_obj = yield(:loop, w_obj, :looptrace => w_loopdetect[w_loopdetect.index(l)..-1], :loopdetect => w_loopdetect) if f_obj and f_obj != w_obj # should avoid infinite loops f_loopdetect = w_loopdetect[0...w_loopdetect.index(l)] end else f_obj = yield(:up, w_obj, :from => w_addr, :to => f_addr, :sfret => f_type, :loopdetect => w_loopdetect, :real_to => o_f_addr) end next if f_obj == false f_obj ||= w_obj f_loopdetect ||= w_loopdetect # only count non-trivial paths in loopdetect (ignore linear links) add_detect = [[f_obj, f_addr, f_type]] add_detect = [] if @decoded[f_addr].kind_of? DecodedInstruction and tmp = @decoded[f_addr].block and ((w_di.block.from_subfuncret.to_a == [] and w_di.block.from_normal == [f_addr] and tmp.to_normal == [w_di.address] and tmp.to_subfuncret.to_a == []) or (w_di.block.from_subfuncret == [f_addr] and tmp.to_subfuncret == [w_di.address])) todo << [f_obj, f_addr, f_type, f_loopdetect + add_detect ] } yield :end, w_obj, :addr => w_addr, :loopdetect => w_loopdetect if not hadsomething elsif @function[w_addr] and w_addr != :default and w_addr != Expression::Unknown next if done.include? [w_obj, w_addr] oldlen = todo.length each_xref(w_addr, :x) { |x| f_addr = x.origin o_f_addr = f_addr f_addr = @decoded[f_addr].block.list.last.address if @decoded[f_addr].kind_of? DecodedInstruction # delay slot if l = w_loopdetect.find { |l_obj, l_addr, l_type| l_addr == w_addr } f_obj = yield(:loop, w_obj, :looptrace => w_loopdetect[w_loopdetect.index(l)..-1], :loopdetect => w_loopdetect) if f_obj and f_obj != w_obj f_loopdetect = w_loopdetect[0...w_loopdetect.index(l)] end else f_obj = yield(:up, w_obj, :from => w_addr, :to => f_addr, :sfret => :normal, :loopdetect => w_loopdetect, :real_to => o_f_addr) end next if f_obj == false f_obj ||= w_obj f_loopdetect ||= w_loopdetect todo << [f_obj, f_addr, :normal, f_loopdetect + [[f_obj, f_addr, :normal]] ] } yield :end, w_obj, :addr => w_addr, :loopdetect => w_loopdetect if todo.length == oldlen else yield :unknown_addr, w_obj, :addr => w_addr, :loopdetect => w_loopdetect end } if include_start todo << [obj, start_addr, from_subfuncret ? :subfuncret : :normal, []] else walk_up[obj, start_addr, []] end while not todo.empty? obj, addr, type, loopdetect = todo.pop di = @decoded[addr] if di and type == :subfuncret di.block.each_to_normal { |sf| next if not f = @function[normalize(sf)] s_obj = yield(:func, obj, :func => f, :funcaddr => sf, :addr => addr, :loopdetect => loopdetect) next if s_obj == false s_obj ||= obj if l = loopdetect.find { |l_obj, l_addr, l_type| addr == l_addr and l_type == :normal } l_obj = yield(:loop, s_obj, :looptrace => loopdetect[loopdetect.index(l)..-1], :loopdetect => loopdetect) if l_obj and l_obj != s_obj s_loopdetect = loopdetect[0...loopdetect.index(l)] end next if l_obj == false s_obj = l_obj if l_obj end s_loopdetect ||= loopdetect todo << [s_obj, addr, :normal, s_loopdetect + [[s_obj, addr, :normal]] ] } elsif di # XXX should interpolate index if di is not in block.list, but what if the addresses are not Comparable ? di.block.list[0..(di.block.list.index(di) || -1)].reverse_each { |di_| di = di_ # XXX not sure.. if stopaddr and ea = di.next_addr and stopaddr.include?(ea) yield :stopaddr, obj, :addr => ea, :loopdetect => loopdetect break end ex_obj = obj obj = yield(:di, obj, :di => di, :loopdetect => loopdetect) break if obj == false obj ||= ex_obj } walk_up[obj, di.block.address, loopdetect] if obj elsif @function[addr] and addr != :default and addr != Expression::Unknown ex_obj = obj obj = yield(:func, obj, :func => @function[addr], :funcaddr => addr, :addr => addr, :loopdetect => loopdetect) next if obj == false obj ||= ex_obj walk_up[obj, addr, loopdetect] else yield :unknown_addr, obj, :addr => addr, :loopdetect => loopdetect end end end
walks the backtrace tree from an address, passing along an object the steps are (1st = event, followed by hash keys) for each decoded instruction encountered: :di :di when backtracking to a block through a decodedfunction: (yield for each of the block's subfunctions) (the decodedinstruction responsible for the call will be yield next) :func :func, :funcaddr, :addr, :depth when jumping from one block to another (excluding :loop): # XXX include :loops ? :up :from, :to, :sfret when the backtrack has nothing to backtrack to (eg program entrypoint): :end :addr when the backtrack stops by taking too long to complete: :maxdepth :addr when the backtrack stops for encountering the specified stop address: :stopaddr :addr when rebacktracking a block already seen in the current branch: (looptrace is an array of [obj, block end addr, from_subfuncret], from oldest to newest) :loop :looptrace when the address does not match a known instruction/function: :unknown_addr :addr the block return value is used as follow for :di, :func, :up and :loop: false => the backtrace stops for the branch nil => the backtrace continues with the current object anything else => the backtrace continues with this object method arguments: obj is the initial value of the object addr is the address where the backtrace starts include_start is a bool specifying if the backtrace should start at addr or just before from_subfuncret is a bool specifying if addr points to a decodedinstruction that calls a subfunction stopaddr is an [array of] address of instruction, the backtrace will stop just after executing it maxdepth is the maximum depth (in blocks) for each backtrace branch. (defaults to dasm.backtrace_maxblocks, which defaults do Dasm.backtrace_maxblocks)
backtrace_walk
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def function_walk(addr_start, obj_start) # addresses of instrs already seen => obj done = {} todo = [[addr_start, obj_start]] while hop = todo.pop addr, obj = hop next if done.has_key?(done) di = di_at(addr) next if not di if done.empty? dilist = di.block.list[di.block.list.index(di)..-1] else # new block, check all 'from' have been seen if not hop[2] # may retry later all_ok = true di.block.each_from_samefunc(self) { |fa| all_ok = false unless done.has_key?(fa) } if not all_ok todo.unshift([addr, obj, true]) next end end froms = {} di.block.each_from_samefunc(self) { |fa| froms[fa] = done[fa] if done[fa] } if froms.values.uniq.length > 1 obj = yield([:merge, addr, froms, froms.values.first]) next if obj == false end dilist = di.block.list end if dilist.each { |_di| break if done.has_key?(_di.address) # looped back into addr_start done[_di.address] = obj obj = yield([:di, _di.address, _di, obj]) break if obj == false # also return false for the previous 'if' } from = dilist.last.address if di.block.to_normal and di.block.to_normal[0] and di.block.to_subfuncret and di.block.to_subfuncret[0] # current instruction block calls into a subfunction obj = di.block.to_normal.map { |subf| yield([:subfunc, subf, from, obj]) }.first # propagate 1st subfunc result next if obj == false end wantclone = false di.block.each_to_samefunc(self) { |ta| if wantclone nobj = yield([:clone, ta, from, obj]) next if obj == false todo << [ta, nobj] else todo << [ta, obj] wantclone = true end } end end end
iterates over all instructions of a function from a given entrypoint carries an object while walking, the object is yielded every instruction every block is walked only once, after all previous blocks are done (if possible) on a 'jz', a [:clone] event is yielded for every path beside the first on a juction (eg a -> b -> d, a -> c -> d), a [:merge] event occurs if froms have different objs event list: [:di, <addr>, <decoded_instruction>, <object>] [:clone, <newaddr>, <oldaddr>, <object>] [:merge, <newaddr>, {<oldaddr1> => <object1>, <oldaddr2> => <object2>, ...}, <object1>] [:subfunc, <subfunc_addr>, <call_addr>, <object>] all events should return an object :merge has a copy of object1 at the end so that uninterested callers can always return args[-1] if an event returns false, the trace stops for the current branch
function_walk
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def backtrace(expr, start_addr, nargs={}) include_start = nargs.delete :include_start from_subfuncret = nargs.delete :from_subfuncret origin = nargs.delete :origin origexpr = nargs.delete :orig_expr type = nargs.delete :type len = nargs.delete :len snapshot_addr = nargs.delete(:snapshot_addr) || nargs.delete(:stopaddr) maxdepth = nargs.delete(:maxdepth) || @backtrace_maxblocks detached = nargs.delete :detached max_complexity = nargs.delete(:max_complexity) || @backtrace_maxcomplexity max_complexity_data = nargs.delete(:max_complexity) || @backtrace_maxcomplexity_data bt_log = nargs.delete :log # array to receive the ongoing backtrace info only_upto = nargs.delete :only_upto no_check = nargs.delete :no_check terminals = nargs.delete(:terminals) || [] raise ArgumentError, "invalid argument to backtrace #{nargs.keys.inspect}" if not nargs.empty? expr = Expression[expr] origexpr = expr if origin == start_addr start_addr = normalize(start_addr) di = @decoded[start_addr] if not snapshot_addr and @cpu.backtrace_is_stack_address(expr) puts " not backtracking stack address #{expr}" if debug_backtrace return [] end if type == :r or type == :w max_complexity = max_complexity_data maxdepth = @backtrace_maxblocks_data if backtrace_maxblocks_data and maxdepth > @backtrace_maxblocks_data end if vals = (no_check ? (!need_backtrace(expr, terminals) and [expr]) : backtrace_check_found(expr, di, origin, type, len, maxdepth, detached, snapshot_addr)) # no need to update backtracked_for return vals elsif maxdepth <= 0 return [Expression::Unknown] end # create initial backtracked_for if type and origin == start_addr and di btt = BacktraceTrace.new(expr, origin, origexpr, type, len, maxdepth-1) btt.address = di.address btt.exclude_instr = true if not include_start btt.from_subfuncret = true if from_subfuncret and include_start btt.detached = true if detached di.block.backtracked_for |= [btt] end @callback_prebacktrace[] if callback_prebacktrace # list of Expression/Integer result = [] puts "backtracking #{type} #{expr} from #{di || Expression[start_addr || 0]} for #{@decoded[origin]}" if debug_backtrace or $DEBUG bt_log << [:start, expr, start_addr] if bt_log backtrace_walk(expr, start_addr, include_start, from_subfuncret, snapshot_addr, maxdepth) { |ev, expr_, h| expr = expr_ case ev when :unknown_addr, :maxdepth puts " backtrace end #{ev} #{expr}" if debug_backtrace result |= [expr] if not snapshot_addr @addrs_todo << [expr, (detached ? nil : origin)] if not snapshot_addr and type == :x and origin when :end if not expr.kind_of? StoppedExpr oldexpr = expr expr = backtrace_emu_blockup(h[:addr], expr) puts " backtrace up #{Expression[h[:addr]]} #{oldexpr}#{" => #{expr}" if expr != oldexpr}" if debug_backtrace bt_log << [:up, expr, oldexpr, h[:addr], :end] if bt_log and expr != oldexpr if expr != oldexpr and not snapshot_addr and vals = (no_check ? (!need_backtrace(expr, terminals) and [expr]) : backtrace_check_found(expr, nil, origin, type, len, maxdepth-h[:loopdetect].length, detached, snapshot_addr)) result |= vals next end end puts " backtrace end #{ev} #{expr}" if debug_backtrace if not snapshot_addr result |= [expr] btt = BacktraceTrace.new(expr, origin, origexpr, type, len, maxdepth-h[:loopdetect].length-1) btt.detached = true if detached @decoded[h[:addr]].block.backtracked_for |= [btt] if @decoded[h[:addr]] @function[h[:addr]].backtracked_for |= [btt] if @function[h[:addr]] and h[:addr] != :default @addrs_todo << [expr, (detached ? nil : origin)] if type == :x and origin end when :stopaddr if not expr.kind_of? StoppedExpr oldexpr = expr expr = backtrace_emu_blockup(h[:addr], expr) puts " backtrace up #{Expression[h[:addr]]} #{oldexpr}#{" => #{expr}" if expr != oldexpr}" if debug_backtrace bt_log << [:up, expr, oldexpr, h[:addr], :end] if bt_log and expr != oldexpr end puts " backtrace end #{ev} #{expr}" if debug_backtrace result |= ((expr.kind_of?(StoppedExpr)) ? expr.exprs : [expr]) when :loop next false if expr.kind_of? StoppedExpr t = h[:looptrace] oldexpr = t[0][0] next false if expr == oldexpr # unmodifying loop puts " bt loop at #{Expression[t[0][1]]}: #{oldexpr} => #{expr} (#{t.map { |z| Expression[z[1]] }.join(' <- ')})" if debug_backtrace false when :up next false if only_upto and h[:to] != only_upto next expr if expr.kind_of? StoppedExpr oldexpr = expr expr = backtrace_emu_blockup(h[:from], expr) puts " backtrace up #{Expression[h[:from]]}->#{Expression[h[:to]]} #{oldexpr}#{" => #{expr}" if expr != oldexpr}" if debug_backtrace bt_log << [:up, expr, oldexpr, h[:from], h[:to]] if bt_log if expr != oldexpr and vals = (no_check ? (!need_backtrace(expr, terminals) and [expr]) : backtrace_check_found(expr, @decoded[h[:from]], origin, type, len, maxdepth-h[:loopdetect].length, detached, snapshot_addr)) if snapshot_addr expr = StoppedExpr.new vals next expr else result |= vals bt_log << [:found, vals, h[:from]] if bt_log next false end end if origin and type # update backtracked_for update_btf = lambda { |btf, new_btt| # returns true if btf was modified if i = btf.index(new_btt) btf[i] = new_btt if btf[i].maxdepth < new_btt.maxdepth else btf << new_btt end } btt = BacktraceTrace.new(expr, origin, origexpr, type, len, maxdepth-h[:loopdetect].length-1) btt.detached = true if detached if x = di_at(h[:from]) update_btf[x.block.backtracked_for, btt] end if x = @function[h[:from]] and h[:from] != :default update_btf[x.backtracked_for, btt] end if x = di_at(h[:to]) btt = btt.dup btt.address = x.address btt.from_subfuncret = true if h[:sfret] == :subfuncret if backtrace_check_funcret(btt, h[:from], h[:real_to] || h[:to]) puts " function returns to caller" if debug_backtrace next false end if not update_btf[x.block.backtracked_for, btt] puts " already backtraced" if debug_backtrace next false end end end expr when :di, :func next if expr.kind_of? StoppedExpr if not snapshot_addr and @cpu.backtrace_is_stack_address(expr) puts " not backtracking stack address #{expr}" if debug_backtrace next false end oldexpr = expr case ev when :di h[:addr] = h[:di].address expr = backtrace_emu_instr(h[:di], expr) bt_log << [ev, expr, oldexpr, h[:di], h[:addr]] if bt_log and expr != oldexpr when :func expr = backtrace_emu_subfunc(h[:func], h[:funcaddr], h[:addr], expr, origin, maxdepth-h[:loopdetect].length) if snapshot_addr and snapshot_addr == h[:funcaddr] # XXX recursiveness detection needs to be fixed puts " backtrace: recursive function #{Expression[h[:funcaddr]]}" if debug_backtrace next false end bt_log << [ev, expr, oldexpr, h[:funcaddr], h[:addr]] if bt_log and expr != oldexpr end puts " backtrace #{h[:di] || Expression[h[:funcaddr]]} #{oldexpr} => #{expr}" if debug_backtrace and expr != oldexpr if vals = (no_check ? (!need_backtrace(expr, terminals) and [expr]) : backtrace_check_found(expr, h[:di], origin, type, len, maxdepth-h[:loopdetect].length, detached, snapshot_addr)) if snapshot_addr expr = StoppedExpr.new vals else result |= vals bt_log << [:found, vals, h[:addr]] if bt_log next false end elsif expr.complexity > max_complexity puts " backtrace aborting, expr too complex" if debug_backtrace next false end expr else raise ev.inspect end } puts ' backtrace result: ' + result.map { |r| Expression[r] }.join(', ') if debug_backtrace result end
backtraces the value of an expression from start_addr updates blocks backtracked_for if type is set uses backtrace_walk all values returned are from backtrace_check_found (which may generate xrefs, labels, addrs to dasm) unless :no_check is specified options: :include_start => start backtracking including start_addr :from_subfuncret => :origin => origin to set for xrefs when resolution is successful :orig_expr => initial expression :type => xref type (:r, :w, :x, :addr) when :x, the results are added to #addrs_todo :len => xref len (for :r/:w) :snapshot_addr => addr (or array of) where the backtracker should stop if a snapshot_addr is given, values found are ignored if continuing the backtrace does not get to it (eg maxdepth/unk_addr/end) :maxdepth => maximum number of blocks to backtrace :detached => true if backtracking type :x and the result should not have from = origin set in @addrs_todo :max_complexity{_data} => maximum complexity of the expression before aborting its backtrace :log => Array, will be updated with the backtrace evolution :only_upto => backtrace only to update bt_for for current block & previous ending at only_upto :no_check => don't use backtrace_check_found (will not backtrace indirection static values) :terminals => array of symbols with constant value (stop backtracking if all symbols in the expr are terminals) (only supported with no_check)
backtrace
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def backtrace_check_funcret(btt, funcaddr, instraddr) if di = @decoded[instraddr] and @function[funcaddr] and btt.type == :x and not btt.from_subfuncret and @cpu.backtrace_is_function_return(btt.expr, @decoded[btt.origin]) and retaddr = backtrace_emu_instr(di, btt.expr) and not need_backtrace(retaddr) puts " backtrace addrs_todo << #{Expression[retaddr]} from #{di} (funcret)" if debug_backtrace di.block.add_to_subfuncret normalize(retaddr) if @decoded[funcaddr].kind_of? DecodedInstruction # check that all callers :saveip returns (eg recursive call that was resolved # before we found funcaddr was a function) @decoded[funcaddr].block.each_from_normal { |fm| if fdi = di_at(fm) and fdi.opcode.props[:saveip] and not fdi.block.to_subfuncret backtrace_check_funcret(btt, funcaddr, fm) end } end if not @function[funcaddr].finalized # the function is not fully disassembled: arrange for the retaddr to be # disassembled only after the subfunction is finished # for that we walk the code from the call, mark each block start, and insert the sfret # just before the 1st function block address in @addrs_todo (which is pop()ed by dasm_step) faddrlist = [] todo = [] di.block.each_to_normal { |t| todo << normalize(t) } while a = todo.pop next if faddrlist.include? a or not get_section_at(a) faddrlist << a if @decoded[a].kind_of? DecodedInstruction @decoded[a].block.each_to_samefunc(self) { |t| todo << normalize(t) } end end idx = @addrs_todo.index(@addrs_todo.find { |r, i, sfr| faddrlist.include? normalize(r) }) || -1 @addrs_todo.insert(idx, [retaddr, instraddr, true]) else @addrs_todo << [retaddr, instraddr, true] end true end end
checks if the BacktraceTrace is a call to a known subfunction returns true and updates self.addrs_todo
backtrace_check_funcret
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def backtrace_emu_instr(di, expr) @cpu.backtrace_emu(di, expr) end
applies one decodedinstruction to an expression
backtrace_emu_instr
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def backtrace_emu_subfunc(func, funcaddr, calladdr, expr, origin, maxdepth) bind = func.get_backtrace_binding(self, funcaddr, calladdr, expr, origin, maxdepth) Expression[expr.bind(bind).reduce] end
applies one subfunction to an expression
backtrace_emu_subfunc
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def need_backtrace(expr, terminals=[]) return if expr.kind_of? ::Integer !(expr.externals.grep(::Symbol) - [:unknown] - terminals).empty? end
returns true if the expression needs more backtrace it checks for the presence of a symbol (not :unknown), which means it depends on some register value
need_backtrace
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def backtrace_check_found(expr, di, origin, type, len, maxdepth, detached, snapshot_addr=nil) # only entrypoints or block starts called by a :saveip are checked for being a function # want to execute [esp] from a block start if type == :x and di and di == di.block.list.first and @cpu.backtrace_is_function_return(expr, @decoded[origin]) and ( # which is an entrypoint.. (not di.block.from_normal and not di.block.from_subfuncret) or # ..or called from a saveip (bool = false ; di.block.each_from_normal { |fn| bool = true if @decoded[fn] and @decoded[fn].opcode.props[:saveip] } ; bool)) # now we can mark the current address a function start # the actual return address will be found later (we tell the caller to continue the backtrace) addr = di.address l = auto_label_at(addr, 'sub', 'loc', 'xref') if not f = @function[addr] f = @function[addr] = DecodedFunction.new puts "found new function #{l} at #{Expression[addr]}" if $VERBOSE end f.finalized = false if @decoded[origin] f.return_address ||= [] f.return_address |= [origin] @decoded[origin].add_comment "endsub #{l}" # TODO add_xref (to update the comment on rename_label) end f.backtracked_for |= @decoded[addr].block.backtracked_for.find_all { |btt| not btt.address } end return if need_backtrace(expr) if snapshot_addr return if expr.expr_externals(true).find { |ee| ee.kind_of?(Indirection) } end puts "backtrace #{type} found #{expr} from #{di} orig #{@decoded[origin] || Expression[origin] if origin}" if debug_backtrace result = backtrace_value(expr, maxdepth) # keep the ori pointer in the results to emulate volatile memory (eg decompiler prefers this) #result << expr if not type # XXX returning multiple values for nothing is too confusing, TODO fix decompiler result.uniq! # create xrefs/labels result.each { |e| backtrace_found_result(e, di, type, origin, len, detached) } if type and origin result end
returns an array of expressions, or nil if expr needs more backtrace it needs more backtrace if expr.externals include a Symbol != :unknown (symbol == register value) if it need no more backtrace, expr's indirections are recursively resolved xrefs are created, and di args are updated (immediate => label) if type is :x, addrs_todo is updated, and if di starts a block, expr is checked to see if it may be a subfunction return value expr indirection are solved by first finding the value of the pointer, and then rebacktracking for write-type access detached is true if type is :x and from should not be set in addrs_todo (indirect call flow, eg external function callback) if the backtrace ends pre entrypoint, returns the value encoded in the raw binary XXX global variable (modified by another function), exported data, multithreaded app.. TODO handle memory aliasing (mov ebx, eax ; write [ebx] ; read [eax]) TODO trace expr evolution through backtrace, to modify immediates to an expr involving label names TODO mov [ptr], imm ; <...> ; jmp [ptr] => rename imm as loc_XX eg. mov eax, 42 ; add eax, 4 ; jmp eax => mov eax, some_label-4
backtrace_check_found
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def backtrace_value(expr, maxdepth) # array of expression with all indirections resolved result = [Expression[expr.reduce]] # solve each indirection sequentially, clone expr for each value (aka cross-product) result.first.expr_indirections.uniq.each { |i| next_result = [] backtrace_indirection(i, maxdepth).each { |rr| next_result |= result.map { |e| Expression[e.bind(i => rr).reduce] } } result = next_result } result.uniq end
returns an array of expressions with Indirections resolved (recursive with backtrace_indirection)
backtrace_value
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def backtrace_indirection(ind, maxdepth) if not ind.origin puts "backtrace_ind: no origin for #{ind}" if $VERBOSE return [ind] end ret = [] decode_imm = lambda { |addr, len| edata = get_edata_at(addr) if edata Expression[ edata.decode_imm("u#{8*len}".to_sym, @cpu.endianness) ] else Expression::Unknown end } # resolve pointers (they may include Indirections) backtrace_value(ind.target, maxdepth).each { |ptr| # find write xrefs to the ptr refs = [] each_xref(ptr, :w) { |x| # XXX should be rebacktracked on new xref next if not @decoded[x.origin] refs |= [x.origin] } if ptr != Expression::Unknown if refs.empty? if get_section_at(ptr) # static data, newer written : return encoded value ret |= [decode_imm[ptr, ind.len]] next else # unknown pointer : backtrace the indirection, hope it solves itself initval = ind end else # wait until we find a write xref, then backtrace the written value initval = true end # wait until we arrive at an xref'ing instruction, then backtrace the written value backtrace_walk(initval, ind.origin, true, false, nil, maxdepth-1) { |ev, expr, h| case ev when :unknown_addr, :maxdepth, :stopaddr puts " backtrace_indirection for #{ind.target} failed: #{ev}" if debug_backtrace ret |= [Expression::Unknown] when :end if not refs.empty? and (expr == true or not need_backtrace(expr)) if expr == true # found a path avoiding the :w xrefs, read the encoded initial value ret |= [decode_imm[ptr, ind.len]] else bd = expr.expr_indirections.inject({}) { |h_, i| h_.update i => decode_imm[i.target, i.len] } ret |= [Expression[expr.bind(bd).reduce]] end else # unknown pointer, backtrace did not resolve... ret |= [Expression::Unknown] end when :di di = h[:di] if expr == true next true if not refs.include? di.address # find the expression to backtrace: assume this is the :w xref from this di writes = get_xrefs_rw(di) writes = writes.find_all { |x_type, x_ptr, x_len| x_type == :w and x_len == ind.len } if writes.length != 1 puts "backtrace_ind: incompatible xrefs to #{ptr} from #{di}" if $DEBUG ret |= [Expression::Unknown] next false end expr = Indirection.new(writes[0][1], ind.len, di.address) end expr = backtrace_emu_instr(di, expr) # may have new indirections... recall bt_value ? #if not need_backtrace(expr) if expr.expr_externals.all? { |e| @prog_binding[e] or @function[normalize(e)] } and expr.expr_indirections.empty? ret |= backtrace_value(expr, maxdepth-1-h[:loopdetect].length) false else expr end when :func next true if expr == true # XXX expr = backtrace_emu_subfunc(h[:func], h[:funcaddr], h[:addr], expr, ind.origin, maxdepth-h[:loopdetect].length) #if not need_backtrace(expr) if expr.expr_externals.all? { |e| @prog_binding[e] or @function[normalize(e)] } and expr.expr_indirections.empty? ret |= backtrace_value(expr, maxdepth-1-h[:loopdetect].length) false else expr end end } } ret end
returns the array of values pointed by the indirection at its invocation (ind.origin) first resolves the pointer using backtrace_value, if it does not point in edata keep the original pointer then backtraces from ind.origin until it finds an :w xref origin if no :w access is found, returns the value encoded in the raw section data TODO handle unaligned (partial?) writes
backtrace_indirection
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def backtrace_found_result(expr, di, type, origin, len, detached) n = normalize(expr) fallthrough = true if type == :x and o = di_at(origin) and not o.opcode.props[:stopexec] and n == o.block.list.last.next_addr # delay_slot add_xref(n, Xref.new(type, origin, len)) if origin != :default and origin != Expression::Unknown and not fallthrough unk = true if n == Expression::Unknown add_xref(n, Xref.new(:addr, di.address)) if di and di.address != origin and not unk base = { nil => 'loc', 1 => 'byte', 2 => 'word', 4 => 'dword', 8 => 'qword' }[len] || 'xref' base = 'sub' if @function[n] n = Expression[auto_label_at(n, base, 'xref') || n] if not fallthrough n = Expression[n] # update instr args # TODO trace expression evolution to allow handling of # mov eax, 28 ; add eax, 4 ; jmp eax # => mov eax, (loc_xx-4) if di and not unk and expr != n # and di.address == origin @cpu.replace_instr_arg_immediate(di.instruction, expr, n) end if @decoded[origin] and not unk @cpu.backtrace_found_result(self, @decoded[origin], expr, type, len) end # add comment if type and @decoded[origin] # and not @decoded[origin].instruction.args.include? n @decoded[origin].add_comment "#{type}#{len}:#{n}" if not fallthrough end # check if target is a string if di and type == :r and (len == 1 or len == 2) and s = get_section_at(n) l = s[0].inv_export[s[0].ptr] case len when 1; str = s[0].read(32).unpack('C*') when 2; str = s[0].read(64).unpack('v*') end str = str.inject('') { |str_, c| case c when 0x20..0x7e, ?\n, ?\r, ?\t; str_ << c else break str_ end } if str.length >= 4 di.add_comment "#{'L' if len == 2}#{str.inspect}" str = 'a_' + str.downcase.delete('^a-z0-9')[0, 12] if str.length >= 8 and l[0, 5] == 'byte_' rename_label(l, @program.new_label(str)) end end end # XXX all this should be done in backtrace() { <here> } if type == :x and origin if detached o = @decoded[origin] ? origin : di ? di.address : nil # lib function callback have origin == libfuncname, so we must find a block somewhere else origin = nil @decoded[o].block.add_to_indirect(normalize(n)) if @decoded[o] and not unk else @decoded[origin].block.add_to_normal(normalize(n)) if @decoded[origin] and not unk end @addrs_todo << [n, origin] end end
creates xrefs, updates addrs_todo, updates instr args
backtrace_found_result
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause
def dump(dump_data=true, &b) b ||= lambda { |l| puts l } @sections.sort_by { |addr, edata| addr.kind_of?(::Integer) ? addr : 0 }.each { |addr, edata| addr = Expression[addr] if addr.kind_of? ::String blockoffs = @decoded.values.grep(DecodedInstruction).map { |di| Expression[di.block.address, :-, addr].reduce if di.block_head? }.grep(::Integer).sort.reject { |o| o < 0 or o >= edata.length } b[@program.dump_section_header(addr, edata)] if not dump_data and edata.length > 16*1024 and blockoffs.empty? b["// [#{edata.length} data bytes]"] next end unk_off = 0 # last off displayed # blocks.sort_by { |b| b.addr }.each { |b| while unk_off < edata.length if unk_off == blockoffs.first blockoffs.shift di = @decoded[addr+unk_off] if unk_off != di.block.edata_ptr b["\n// ------ overlap (#{unk_off-di.block.edata_ptr}) ------"] elsif di.block.from_normal.kind_of? ::Array b["\n"] end dump_block(di.block, &b) unk_off += [di.block.bin_length, 1].max unk_off = blockoffs.first if blockoffs.first and unk_off > blockoffs.first else next_off = blockoffs.first || edata.length if dump_data or next_off - unk_off < 16 unk_off = dump_data(addr + unk_off, edata, unk_off, &b) else b["// [#{next_off - unk_off} data bytes]"] unk_off = next_off end end end } end
dumps the source, optionnally including data yields (defaults puts) each line
dump
ruby
stephenfewer/grinder
node/lib/metasm/metasm/disassemble.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb
BSD-3-Clause