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... | 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 = ... | 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, max=@memory.length-0x1000-addr)
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... | 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
}
Expressio... | 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, sz=@cpu.size/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, sz=@cpu.size/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, len=@memory.length-start, &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_ran... | 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, ign... | 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]
e... | 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_... | 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::... | 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
... | 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.... | 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 <= -@dasm.cpu.size/8; 'var_%X' % (-off-@dasm.cpu.size/8) # -4 => var_0, -8 => var_4..
else 'var_0%X' % -of... | 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,... | 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 re... | 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::I... | 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 : ... | 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 =... | 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_... | 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 ... | 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... | 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.... | 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; int... | 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 use... | 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 ==... | 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 o... | 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 ... | 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 domai... | 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? ::Inte... | 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... | 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, @... | 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_norma... | 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... | 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
... | 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)
e... | 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_sect... | 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 memc... | 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? Expre... | 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... | 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 #{Expre... | 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_... | 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
b... | 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 ... | 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] = (@functio... | 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_add... | 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-sty... | 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_backtra... | 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... | 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 = normaliz... | 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
retur... | 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.nore... | 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 encounte... | 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... | 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]
... | 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 -... | 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 ... | 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
:f... | 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)... | 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(... | 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,... | 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, maxdept... | 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
Expr... | 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 ... | 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::... | 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 ... | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.