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 disassembler_default_btbind_callback esp = register_symbols[4] lambda { |dasm, bind, funcaddr, calladdr, expr, origin, maxdepth| @dasm_func_default_off ||= {} if off = @dasm_func_default_off[[dasm, calladdr]] bind = bind.merge(esp => Expression[esp, :+, off]) break bind end break bind if not odi = dasm.decoded[origin] or odi.opcode.basename != 'ret' expr = expr.reduce_rec if expr.kind_of? Expression break bind unless expr.kind_of? Indirection and expr.origin == origin break bind unless expr.externals.reject { |e| e =~ /^autostackoffset_/ } == [esp] curfunc = dasm.function[funcaddr] if curfunc.backtrace_binding and tk = curfunc.backtrace_binding[:thunk] and dasm.function[tk] curfunc = dasm.function[tk] end # scan from calladdr for the probable parent function start func_start = nil dasm.backtrace_walk(true, calladdr, false, false, nil, maxdepth) { |ev, foo, h| if ev == :up and h[:sfret] != :subfuncret and di = dasm.decoded[h[:to]] and di.opcode.basename == 'call' func_start = h[:from] break elsif ev == :end # entrypoints are functions too func_start = h[:addr] break end } break bind if not func_start puts "automagic #{Expression[funcaddr]}: found func start for #{dasm.decoded[origin]} at #{Expression[func_start]}" if dasm.debug_backtrace s_off = "autostackoffset_#{Expression[funcaddr]}_#{Expression[calladdr]}" list = dasm.backtrace(expr.bind(esp => Expression[esp, :+, s_off]), calladdr, :include_start => true, :snapshot_addr => func_start, :maxdepth => maxdepth, :origin => origin) # check if this backtrace made us find our binding if off = @dasm_func_default_off[[dasm, calladdr]] bind = bind.merge(esp => Expression[esp, :+, off]) break bind elsif not curfunc.btbind_callback break curfunc.backtrace_binding end e_expr = list.find { |e_expr_| # TODO cleanup this e_expr_ = Expression[e_expr_].reduce_rec next if not e_expr_.kind_of? Indirection off = Expression[[esp, :+, s_off], :-, e_expr_.target].reduce off.kind_of? Integer and off >= @size/8 and off < 10*@size/8 and (off % (@size/8)) == 0 } || list.first e_expr = e_expr.rexpr if e_expr.kind_of? Expression and e_expr.op == :+ and not e_expr.lexpr break bind unless e_expr.kind_of? Indirection off = Expression[[esp, :+, s_off], :-, e_expr.target].reduce if off.kind_of? Expression bd = off.externals.grep(/^autostackoffset_/).inject({}) { |bd_, xt| bd_.update xt => @size/8 } bd.delete s_off if off.bind(bd).reduce == @size/8 # all __cdecl off = @size/8 else # check if all calls are to the same extern func bd.delete_if { |k, v| k !~ /^autostackoffset_#{Expression[funcaddr]}_/ } bd.each_key { |k| bd[k] = 0 } if off.bind(bd).reduce.kind_of? Integer off = off.bind(bd).reduce / (bd.length + 1) end end end if off.kind_of? Integer if off < @size/8 or off > 20*@size/8 or (off % (@size/8)) != 0 puts "autostackoffset: ignoring off #{off} for #{Expression[funcaddr]} from #{dasm.decoded[calladdr]}" if $VERBOSE off = :unknown end end bind = bind.merge esp => Expression[esp, :+, off] if off != :unknown if funcaddr != :default if not off.kind_of? ::Integer #XXX we allow the current function to return, so we should handle the func backtracking its esp #(and other register that are saved and restored in epilog) puts "stackoff #{dasm.decoded[calladdr]} | #{Expression[func_start]} | #{expr} | #{e_expr} | #{off}" if dasm.debug_backtrace else puts "autostackoffset: found #{off} for #{Expression[funcaddr]} from #{dasm.decoded[calladdr]}" if $VERBOSE curfunc.btbind_callback = nil curfunc.backtrace_binding = bind # rebacktrace the return address, so that other unknown funcs that depend on us are solved dasm.backtrace(Indirection[esp, @size/8, origin], origin, :origin => origin) end else if off.kind_of? ::Integer and dasm.decoded[calladdr] puts "autostackoffset: found #{off-@size/8} for #{dasm.decoded[calladdr]}" if $VERBOSE di = dasm.decoded[calladdr] di.comment.delete_if { |c| c =~ /^stackoff=/ } if di.comment di.add_comment "stackoff=#{off-@size/8}" @dasm_func_default_off[[dasm, calladdr]] = off dasm.backtrace(Indirection[esp, @size/8, origin], origin, :origin => origin) elsif cachedoff = @dasm_func_default_off[[dasm, calladdr]] bind[esp] = Expression[esp, :+, cachedoff] elsif off.kind_of? ::Integer dasm.decoded[calladdr].add_comment "stackoff=#{off-@size/8}" end puts "stackoff #{dasm.decoded[calladdr]} | #{Expression[func_start]} | #{expr} | #{e_expr} | #{off}" if dasm.debug_backtrace end bind } end
the lambda for the :default backtrace_binding callback of the disassembler tries to determine the stack offset of unprototyped functions working: checks that origin is a ret, that expr is an indirection from esp and that expr.origin is the ret bt_walk from calladdr until we finds a call into us, and assumes it is the current function start TODO handle foo: call bar ; bar: pop eax ; call <withourcallback> ; ret -> bar is not the function start (foo is) then backtrace expr from calladdr to funcstart (snapshot), using esp -> esp+<stackoffvariable> from the result, compute stackoffvariable (only if trivial) will not work if the current function calls any other unknown function (unless all are __cdecl) will not work if the current function is framed (ebp leave ret): in this case the function will return, but its esp will be unknown if the stack offset is found and funcaddr is a string, fixup the static binding and remove the dynamic binding TODO dynamise thunks bt_for & bt_cb
disassembler_default_btbind_callback
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/decode.rb
BSD-3-Clause
def disassembler_default_btfor_callback lambda { |dasm, btfor, funcaddr, calladdr| if funcaddr != :default; btfor elsif di = dasm.decoded[calladdr] and (di.opcode.name == 'call' or di.opcode.name == 'jmp'); btfor else [] end } end
the :default backtracked_for callback returns empty unless funcaddr is not default or calladdr is a call or a jmp
disassembler_default_btfor_callback
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/decode.rb
BSD-3-Clause
def code_binding(dasm, entry, finish=nil) entry = dasm.normalize(entry) finish = dasm.normalize(finish) if finish lastdi = nil binding = {} bt = lambda { |from, expr, inc_start| ret = dasm.backtrace(Expression[expr], from, :snapshot_addr => entry, :include_start => inc_start) ret.length == 1 ? ret.first : Expression::Unknown } # walk blocks, search for finish, scan memory writes todo = [entry] done = [Expression::Unknown] while addr = todo.pop addr = dasm.normalize(addr) next if done.include? addr or addr == finish or not dasm.decoded[addr].kind_of? DecodedInstruction done << addr b = dasm.decoded[addr].block next if b.list.find { |di| a = di.address if a == finish lastdi = b.list[b.list.index(di) - 1] true else # check writes from the instruction get_xrefs_w(dasm, di).each { |waddr, len| # we want the ptr expressed with reg values at entry ptr = bt[a, waddr, false] binding[Indirection[ptr, len, a]] = bt[a, Indirection[waddr, len, a], true] } false end } hasnext = false b.each_to_samefunc(dasm) { |t| hasnext = true if t == finish lastdi = b.list.last else todo << t end } # check end of sequence if not hasnext raise "two-ended code_binding #{lastdi} & #{b.list.last}" if lastdi lastdi = b.list.last if lastdi.opcode.props[:setip] e = get_xrefs_x(dasm, lastdi) raise 'bad code_binding ending' if e.to_a.length != 1 or not lastdi.opcode.props[:stopexec] binding[:ip] = bt[lastdi.address, e.first, false] elsif not lastdi.opcode.props[:stopexec] binding[:ip] = lastdi.next_addr end end end binding.delete_if { |k, v| Expression[k] == Expression[v] } # add register binding raise "no code_binding end" if not lastdi and not finish register_symbols.each { |reg| val = if lastdi; bt[lastdi.address, reg, true] else bt[finish, reg, false] end next if val == Expression[reg] mask = 0xffff_ffff # dont use 1<<@size, because 16bit code may use e.g. edi (through opszoverride) mask = 0xffff_ffff_ffff_ffff if @size == 64 val = Expression[val, :&, mask].reduce binding[reg] = Expression[val] } binding end
computes the binding of the sequence of code starting at entry included the binding is a hash showing the value of modified elements at the end of the code sequence, relative to their value at entry the elements are all the registers and the memory written to if finish is nil, the binding will include :ip, which is the address to be executed next (if it exists) the binding will not include memory access from subfunctions entry should be an entrypoint of the disassembler if finish is nil the code sequence must have only one end, with no to_normal
code_binding
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/decode.rb
BSD-3-Clause
def name_local_vars(dasm, funcaddr) esp = register_symbols[4] func = dasm.function[funcaddr] subs = [] dasm.trace_function_register(funcaddr, esp => 0) { |di, r, off, trace| next if r.to_s =~ /flag/ if di.opcode.name == 'call' and tf = di.block.to_normal.find { |t| dasm.function[t] and dasm.function[t].localvars } subs << [trace[esp], dasm.function[tf].localvars] end di.instruction.args.grep(ModRM).each { |mrm| b = mrm.b || (mrm.i if mrm.s == 1) # its a modrm => b is read, so ignore r/off (not yet applied), use trace only stackoff = trace[b.symbolic] if b next if not stackoff imm = mrm.imm || Expression[0] frameoff = imm + stackoff if frameoff.kind_of?(::Integer) # XXX register args ? non-ABI standard register args ? (eg optimized x64) str = 'var_%X' % (-frameoff) str = 'arg_%X' % (frameoff-@size/8) if frameoff > 0 str = func.get_localvar_stackoff(frameoff, di, str) if func imm = imm.expr if imm.kind_of?(ExpressionString) mrm.imm = ExpressionString.new(imm, str, :stackvar) end } off = off.reduce if off.kind_of?(Expression) next unless off.kind_of?(Integer) off } # if subfunctions are called at a fixed stack offset, rename var_3c -> subarg_0 if func and func.localvars and not subs.empty? and subs.all? { |sb| sb[0] == subs.first[0] } func.localvars.each { |varoff, varname| subargnames = subs.map { |o, sb| sb[varoff-o+@size/8] }.compact if subargnames.uniq.length == 1 varname.replace 'sub'+subargnames[0] end } end end
trace the stack pointer register across a function, rename occurences of esp+XX to esp+var_XX
name_local_vars
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/decode.rb
BSD-3-Clause
def decompile_makestackvars(dasm, funcstart, blocks) oldfuncbd = dasm.address_binding[funcstart] dasm.address_binding[funcstart] = { :esp => :frameptr } # this would suffice, the rest here is just optimisation patched_binding = [funcstart] # list of addresses to cleanup later ebp_frame = true # pretrace esp and ebp for each function block (cleared later) # TODO with more than 1 unknown __stdcall ext func per path, esp -> unknown, which makes very ugly C (*esp-- = 12...); add heuristics ? blocks.each { |block| blockstart = block.address if not dasm.address_binding[blockstart] patched_binding << blockstart dasm.address_binding[blockstart] = {} foo = dasm.backtrace(:esp, blockstart, :snapshot_addr => funcstart) if foo.length == 1 and ee = foo.first and ee.kind_of? Expression and (ee == Expression[:frameptr] or (ee.lexpr == :frameptr and ee.op == :+ and ee.rexpr.kind_of? ::Integer)) dasm.address_binding[blockstart][:esp] = ee end if ebp_frame foo = dasm.backtrace(:ebp, blockstart, :snapshot_addr => funcstart) if foo.length == 1 and ee = foo.first and ee.kind_of? Expression and (ee == Expression[:frameptr] or (ee.lexpr == :frameptr and ee.op == :+ and ee.rexpr.kind_of? ::Integer)) dasm.address_binding[blockstart][:ebp] = ee else ebp_frame = false # func does not use ebp as frame ptr, no need to bt for later blocks end end end yield block } ensure patched_binding.each { |a| dasm.address_binding.delete a } dasm.address_binding[funcstart] = oldfuncbd if oldfuncbd end
temporarily setup dasm.address_binding so that backtracking stack-related offsets resolve in :frameptr (relative to func start)
decompile_makestackvars
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/decompile.rb
BSD-3-Clause
def decompile_func_finddeps(dcmp, blocks, func) deps_r = {} ; deps_w = {} ; deps_to = {} deps_subfunc = {} # things read/written by subfuncs # find read/writes by each block blocks.each { |b, to| deps_r[b] = [] ; deps_w[b] = [] ; deps_to[b] = to deps_subfunc[b] = [] blk = dcmp.dasm.decoded[b].block blk.list.each { |di| a = di.backtrace_binding.values w = [] di.backtrace_binding.keys.each { |k| case k when ::Symbol; w |= [k] else a |= Expression[k].externals # if dword [eax] <- 42, eax is read end } a << :eax if di.opcode.name == 'ret' and (not func.type.kind_of? C::BaseType or func.type.type.name != :void) # standard ABI deps_r[b] |= a.map { |ee| Expression[ee].externals.grep(::Symbol) }.flatten - [:unknown] - deps_w[b] deps_w[b] |= w.map { |ee| Expression[ee].externals.grep(::Symbol) }.flatten - [:unknown] } stackoff = nil blk.each_to_normal { |t| t = dcmp.backtrace_target(t, blk.list.last.address) next if not t = dcmp.c_parser.toplevel.symbol[t] t.type = C::Function.new(C::BaseType.new(:int)) if not t.type.kind_of? C::Function # XXX this may seem a bit extreme, and yes, it is. stackoff ||= Expression[dcmp.dasm.backtrace(:esp, blk.list.last.address, :snapshot_addr => blocks.first[0]).first, :-, :esp].reduce # things that are needed by the subfunction if t.has_attribute('fastcall') a = t.type.args.to_a dep = [:ecx, :edx] dep.shift if not a[0] or a[0].has_attribute('unused') dep.pop if not a[1] or a[1].has_attribute('unused') deps_subfunc[b] |= dep end t.type.args.to_a.each { |arg| if reg = arg.has_attribute('register') deps_subfunc[b] |= [reg.to_sym] end } } if stackoff # last block instr == subfunction call deps_r[b] |= deps_subfunc[b] - deps_w[b] deps_w[b] |= [:eax, :ecx, :edx] # standard ABI end } bt = blocks.transpose roots = bt[0] - bt[1].flatten # XXX jmp 1stblock ? # find regs read and never written (must have been set by caller and are part of the func ABI) uninitialized = lambda { |b, r, done| if not deps_r[b] elsif deps_r[b].include?(r) blk = dcmp.dasm.decoded[b].block bw = [] rdi = blk.list.find { |di| a = di.backtrace_binding.values w = [] di.backtrace_binding.keys.each { |k| case k when ::Symbol; w |= [k] else a |= Expression[k].externals # if dword [eax] <- 42, eax is read end } a << :eax if di.opcode.name == 'ret' and (not func.type.kind_of? C::BaseType or func.type.type.name != :void) # standard ABI next true if (a.map { |ee| Expression[ee].externals.grep(::Symbol) }.flatten - [:unknown] - bw).include? r bw |= w.map { |ee| Expression[ee].externals.grep(::Symbol) }.flatten - [:unknown] false } if r == :eax and (rdi || blk.list.last).opcode.name == 'ret' func.type.type = C::BaseType.new(:void) false elsif rdi and rdi.backtrace_binding[r] false # mov al, 42 ; ret -> don't regarg eax else true end elsif deps_w[b].include?(r) else done << b (deps_to[b] - done).find { |tb| uninitialized[tb, r, done] } end } regargs = [] register_symbols.each { |r| if roots.find { |root| uninitialized[root, r, []] } regargs << r end } # TODO honor user-defined prototype if available (eg no, really, eax is not read in this function returning al) regargs.sort_by { |r| r.to_s }.each { |r| a = C::Variable.new(r.to_s, C::BaseType.new(:int, :unsigned)) a.add_attribute("register(#{r})") func.type.args << a } # remove writes from a block if no following block read the value dw = {} deps_w.each { |b, deps| dw[b] = deps.reject { |dep| ret = true done = [] todo = deps_to[b].dup while a = todo.pop next if done.include? a done << a if not deps_r[a] or deps_r[a].include? dep ret = false break elsif not deps_w[a].include? dep todo.concat deps_to[a] end end ret } } dw end
list variable dependency for each block, remove useless writes returns { blockaddr => [list of vars that are needed by a following block] }
decompile_func_finddeps
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/decompile.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/decompile.rb
BSD-3-Clause
def encode(reg = 0, endianness = :little) reg = reg.val if reg.kind_of? Argument case @adsz when 16; encode16(reg, endianness) when 32; encode32(reg, endianness) end end
The argument is an integer representing the 'reg' field of the mrm caller is responsible for setting the adsz returns an array, 1 element per possible immediate size (for un-reduce()able Expression)
encode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/encode.rb
BSD-3-Clause
def encode_instr_op(program, i, op) base = op.bin.dup oi = op.args.zip(i.args) set_field = lambda { |f, v| v ||= 0 # ST => ST(0) fld = op.fields[f] base[fld[0]] |= v << fld[1] } size = i.prefix[:sz] || @size # # handle prefixes and bit fields # pfx = i.prefix.map { |k, v| case k when :jmp; {:jmp => 0x3e, :nojmp => 0x2e}[v] when :lock; 0xf0 when :rep; {'repnz' => 0xf2, 'repz' => 0xf3, 'rep' => 0xf2}[v] when :jmphint; {'hintjmp' => 0x3e, 'hintnojmp' => 0x2e}[v] when :seg; [0x26, 0x2E, 0x36, 0x3E, 0x64, 0x65][v.val] end }.compact.pack 'C*' if op.name == 'movsx' or op.name == 'movzx' pfx << 0x66 if size == 48-i.args[0].sz elsif op.name == 'crc32' pfx << 0x66 if size == 48-i.args[1].sz else opsz = op.props[:argsz] oi.each { |oa, ia| case oa when :reg, :reg_eax, :modrm, :mrm_imm raise EncodeError, "Incompatible arg size in #{i}" if ia.sz and opsz and opsz != ia.sz opsz = ia.sz end } pfx << 0x66 if (op.props[:opsz] and size == 48 - op.props[:opsz]) or (not op.props[:argsz] and opsz and size == 48 - opsz) opsz ||= op.props[:opsz] end opsz ||= size if op.props[:adsz] and size == 48 - op.props[:adsz] pfx << 0x67 adsz = 48 - size end adsz ||= size # addrsize override / segment override if mrm = i.args.grep(ModRM).first if not op.props[:adsz] and ((mrm.b and mrm.b.sz == 48 - adsz) or (mrm.i and mrm.i.sz == 48 - adsz)) pfx << 0x67 adsz = 48 - adsz end pfx << [0x26, 0x2E, 0x36, 0x3E, 0x64, 0x65][mrm.seg.val] if mrm.seg end # # encode embedded arguments # postponed = [] oi.each { |oa, ia| case oa when :reg, :seg3, :seg3A, :seg2, :seg2A, :eeec, :eeed, :eeet, :regfp, :regmmx, :regxmm, :regymm # field arg set_field[oa, ia.val] pfx << 0x66 if oa == :regmmx and op.props[:xmmx] and ia.sz == 128 when :vexvreg, :vexvxmm, :vexvymm set_field[:vex_vvvv, ia.val ^ 0xf] when :imm_val1, :imm_val3, :reg_cl, :reg_eax, :reg_dx, :regfp0 # implicit else postponed << [oa, ia] end } if !(op.args & [:modrm, :modrmmmx, :modrmxmm, :modrmymm]).empty? # reg field of modrm regval = (base[-1] >> 3) & 7 base.pop end # convert label name for jmp/call/loop to relative offset if op.props[:setip] and op.name[0, 3] != 'ret' and i.args.first.kind_of? Expression postlabel = program.new_label('post'+op.name) target = postponed.first[1] target = target.rexpr if target.kind_of? Expression and target.op == :+ and not target.lexpr postponed.first[1] = Expression[target, :-, postlabel] end pfx << op.props[:needpfx] if op.props[:needpfx] # # append other arguments # ret = EncodedData.new(pfx + base.pack('C*')) postponed.each { |oa, ia| case oa when :farptr; ed = ia.encode(@endianness, "a#{opsz}".to_sym) when :modrm, :modrmmmx, :modrmxmm, :modrmymm if ia.kind_of? ModRM ed = ia.encode(regval, @endianness) if ed.kind_of?(::Array) if ed.length > 1 # we know that no opcode can have more than 1 modrm ary = [] ed.each { |m| ary << (ret.dup << m) } ret = ary next else ed = ed.first end end else ed = ModRM.encode_reg(ia, regval) end when :mrm_imm; ed = ia.imm.encode("a#{adsz}".to_sym, @endianness) when :i8, :u8, :u16; ed = ia.encode(oa, @endianness) when :i; ed = ia.encode("a#{opsz}".to_sym, @endianness) when :i4xmm, :i4ymm; ed = ia.val << 4 # u8 else raise SyntaxError, "Internal error: want to encode field #{oa.inspect} as arg in #{i}" end if ret.kind_of?(::Array) ret.each { |e| e << ed } else ret << ed end } # we know that no opcode with setip accept both modrm and immediate arg, so ret is not an ::Array ret.add_export(postlabel, ret.virtsize) if postlabel ret end
returns all forms of the encoding of instruction i using opcode op program may be used to create a new label for relative jump/call
encode_instr_op
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/encode.rb
BSD-3-Clause
def symbolic(di=nil) s = Sym[@val] if @sz == 8 and to_s[-1] == ?h Expression[[Sym[@val-4], :>>, 8], :&, 0xff] elsif @sz == 8 Expression[s, :&, 0xff] elsif @sz == 16 Expression[s, :&, 0xffff] else s end end
returns a symbolic representation of the register: eax => :eax cx => :ecx & 0xffff ah => (:eax >> 8) & 0xff
symbolic
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/main.rb
BSD-3-Clause
def share?(other) other.val % (other.sz >> 1) == @val % (@sz >> 1) and (other.sz != @sz or @sz != 8 or other.val == @val) end
checks if two registers have bits in common
share?
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/main.rb
BSD-3-Clause
def initialize(adsz, sz, s, i, b, imm, seg = nil) @adsz, @sz = adsz, sz @s, @i = s, i if i @b = b if b @imm = imm if imm @seg = seg if seg end
creates a new ModRM with the specified attributes: - adsz (16/32), sz (8/16/32: byte ptr, word ptr, dword ptr) - s, i, b, imm - segment selector override
initialize
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/main.rb
BSD-3-Clause
def symbolic(di=nil) p = nil p = Expression[p, :+, @b.symbolic(di)] if b p = Expression[p, :+, [@s, :*, @i.symbolic(di)]] if i p = Expression[p, :+, @imm] if imm p = Expression["segment_base_#@seg", :+, p] if seg and seg.val != ((b && (@b.val == 4 || @b.val == 5)) ? 2 : 3) Indirection[p.reduce, @sz/8, (di.address if di)] end
returns the symbolic representation of the ModRM (ie an Indirection) segment selectors are represented as eg "segment_base_fs" not present when same as implicit (ds:edx, ss:esp)
symbolic
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/main.rb
BSD-3-Clause
def initialize(*a) super() @size = (a & [16, 32]).first || 32 a.delete @size @endianness = (a & [:big, :little]).first || :little a.delete @endianness @family = a.pop || :latest raise "Invalid arguments #{a.inspect}" if not a.empty? raise "Invalid Ia32 family #{@family.inspect}" if not respond_to?("init_#@family") end
Create a new instance of an Ia32 cpu arguments (any order) - size in bits (16, 32) [32] - instruction set (386, 486, pentium...) [latest] - endianness [:little]
initialize
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/main.rb
BSD-3-Clause
def tune_prepro(pp, nodefine = false) super(pp) return if nodefine pp.define_weak('_M_IX86', 500) pp.define_weak('_X86_') pp.define_weak('__i386__') end
defines some preprocessor macros to say who we are: _M_IX86 = 500, _X86_, __i386__ pass any value in nodefine to just call super w/o defining anything of our own
tune_prepro
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/main.rb
BSD-3-Clause
def str_to_reg(str) Reg.s_to_i.has_key?(str) ? Reg.from_str(str) : SimdReg.s_to_i.has_key?(str) ? SimdReg.from_str(str) : nil end
returns a Reg/SimdReg object if the arg is a valid register (eg 'ax' => Reg.new(0, 16)) returns nil if str is invalid
str_to_reg
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/main.rb
BSD-3-Clause
def instr_args_regs(i) i = i.instruction if i.kind_of?(DecodedInstruction) i.args.grep(Reg) end
returns the list of Regs in the instruction arguments may be converted into symbols through Reg#symbolic
instr_args_regs
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/main.rb
BSD-3-Clause
def instr_args_memoryptr(i) i = i.instruction if i.kind_of?(DecodedInstruction) i.args.grep(ModRM) end
returns the list of ModRMs in the instruction arguments may be converted into Indirection through ModRM#symbolic
instr_args_memoryptr
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/main.rb
BSD-3-Clause
def instr_args_memoryptr_getbase(mrm) mrm.b || (mrm.i if mrm.s == 1) end
return the 'base' of the ModRM (Reg/nil)
instr_args_memoryptr_getbase
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/main.rb
BSD-3-Clause
def instr_args_memoryptr_setoffset(mrm, imm) mrm.imm = (imm ? Expression[imm] : imm) end
define ModRM offset (eg to changing imm into an ExpressionString)
instr_args_memoryptr_setoffset
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/main.rb
BSD-3-Clause
def init_386_common_only init_cpu_constants addop_macro1 'adc', 2 addop_macro1 'add', 0 addop_macro1 'and', 4, :unsigned_imm addop 'bswap', [0x0F, 0xC8], :reg addop 'call', [0xE8], nil, :stopexec, :setip, :i, :saveip addop 'call', [0xFF], 2, :stopexec, :setip, :saveip addop('cbw', [0x98]) { |o| o.props[:opsz] = 16 } addop('cwde', [0x98]) { |o| o.props[:opsz] = 32 } addop('cwd', [0x99]) { |o| o.props[:opsz] = 16 } addop('cdq', [0x99]) { |o| o.props[:opsz] = 32 } addop_macro1 'cmp', 7 addop_macrostr 'cmps', [0xA6], :stropz addop 'dec', [0x48], :reg addop 'dec', [0xFE], 1, {:w => [0, 0]} addop 'div', [0xF6], 6, {:w => [0, 0]} addop 'enter', [0xC8], nil, :u16, :u8 addop 'idiv', [0xF6], 7, {:w => [0, 0]} addop 'imul', [0xF6], 5, {:w => [0, 0]} # implicit eax, but different semantic from imul eax, ebx (the implicit version updates edx:eax) addop 'imul', [0x0F, 0xAF], :mrm addop 'imul', [0x69], :mrm, {:s => [0, 1]}, :i addop 'inc', [0x40], :reg addop 'inc', [0xFE], 0, {:w => [0, 0]} addop 'int', [0xCC], nil, :imm_val3, :stopexec addop 'int', [0xCD], nil, :u8 addop_macrotttn 'j', [0x70], nil, :setip, :i8 addop_macrotttn('j', [0x70], nil, :setip, :i8) { |o| o.name << '.i8' } addop_macrotttn 'j', [0x0F, 0x80], nil, :setip, :i addop_macrotttn('j', [0x0F, 0x80], nil, :setip, :i) { |o| o.name << '.i' } addop 'jmp', [0xE9], nil, {:s => [0, 1]}, :setip, :i, :stopexec addop 'jmp', [0xFF], 4, :setip, :stopexec addop 'lea', [0x8D], :mrmA addop 'leave', [0xC9] addop_macrostr 'lods', [0xAC], :strop addop 'loop', [0xE2], nil, :setip, :i8 addop 'loopz', [0xE1], nil, :setip, :i8 addop 'loope', [0xE1], nil, :setip, :i8 addop 'loopnz',[0xE0], nil, :setip, :i8 addop 'loopne',[0xE0], nil, :setip, :i8 addop 'mov', [0xA0], nil, {:w => [0, 0], :d => [0, 1]}, :reg_eax, :mrm_imm addop('mov', [0x88], :mrmw,{:d => [0, 1]}) { |o| o.args.reverse! } addop 'mov', [0xB0], :reg, {:w => [0, 3]}, :i, :unsigned_imm addop 'mov', [0xC6], 0, {:w => [0, 0]}, :i, :unsigned_imm addop_macrostr 'movs', [0xA4], :strop addop 'movsx', [0x0F, 0xBE], :mrmw addop 'movzx', [0x0F, 0xB6], :mrmw addop 'mul', [0xF6], 4, {:w => [0, 0]} addop 'neg', [0xF6], 3, {:w => [0, 0]} addop 'nop', [0x90] addop 'not', [0xF6], 2, {:w => [0, 0]} addop_macro1 'or', 1, :unsigned_imm addop 'pop', [0x58], :reg addop 'pop', [0x8F], 0 addop 'push', [0x50], :reg addop 'push', [0xFF], 6 addop 'push', [0x68], nil, {:s => [0, 1]}, :i, :unsigned_imm addop 'ret', [0xC3], nil, :stopexec, :setip addop 'ret', [0xC2], nil, :stopexec, :u16, :setip addop_macro3 'rol', 0 addop_macro3 'ror', 1 addop_macro3 'sar', 7 addop_macro1 'sbb', 3 addop_macrostr 'scas', [0xAE], :stropz addop_macrotttn('set', [0x0F, 0x90], 0) { |o| o.props[:argsz] = 8 } addop_macrotttn('set', [0x0F, 0x90], :mrm) { |o| o.props[:argsz] = 8 ; o.args.reverse! } # :reg field is unused addop_macro3 'shl', 4 addop_macro3 'sal', 6 addop 'shld', [0x0F, 0xA4], :mrm, :u8 addop 'shld', [0x0F, 0xA5], :mrm, :reg_cl addop_macro3 'shr', 5 addop 'shrd', [0x0F, 0xAC], :mrm, :u8 addop 'shrd', [0x0F, 0xAD], :mrm, :reg_cl addop_macrostr 'stos', [0xAA], :strop addop_macro1 'sub', 5 addop 'test', [0x84], :mrmw addop 'test', [0xA8], nil, {:w => [0, 0]}, :reg_eax, :i, :unsigned_imm addop 'test', [0xF6], 0, {:w => [0, 0]}, :i, :unsigned_imm addop 'xchg', [0x90], :reg, :reg_eax addop('xchg', [0x90], :reg, :reg_eax) { |o| o.args.reverse! } # xchg eax, ebx == xchg ebx, eax) addop 'xchg', [0x86], :mrmw addop('xchg', [0x86], :mrmw) { |o| o.args.reverse! } addop_macro1 'xor', 6, :unsigned_imm end
only most common instructions from the 386 instruction set inexhaustive list : no aaa, arpl, mov crX, call/jmp/ret far, in/out, bts, xchg...
init_386_common_only
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/opcodes.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/opcodes.rb
BSD-3-Clause
def parse_parser_instruction(lexer, instr) case instr.raw.downcase when '.mode', '.bits' lexer.skip_space if tok = lexer.readtok and tok.type == :string and (tok.raw == '16' or tok.raw == '32') @size = tok.raw.to_i lexer.skip_space raise instr, 'syntax error' if ntok = lexer.nexttok and ntok.type != :eol else raise instr, 'invalid cpu mode' end else super(lexer, instr) end end
handles cpu-specific parser instruction, falls back to Ancestor's version if unknown keyword XXX changing the cpu size in the middle of the code may have baaad effects...
parse_parser_instruction
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/parse.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/parse.rb
BSD-3-Clause
def parse_arg_valid?(o, spec, arg) if o.name == 'movsx' or o.name == 'movzx' if not arg.kind_of?(Reg) and not arg.kind_of?(ModRM) return elsif not arg.sz puts "ambiguous arg size for indirection in #{o.name}" if $VERBOSE return elsif spec == :reg # reg=dst, modrm=src (smaller) return (arg.kind_of?(Reg) and arg.sz >= 16) elsif o.props[:argsz] return arg.sz == o.props[:argsz] else return arg.sz == 16 end elsif o.name == 'crc32' if not arg.kind_of?(Reg) and not arg.kind_of?(ModRM) return elsif not arg.sz puts "ambiguous arg size for indirection in #{o.name}" if $VERBOSE return elsif spec == :reg return (arg.kind_of?(Reg) and arg.sz >= 32) elsif o.props[:argsz] return arg.sz == o.props[:argsz] else return arg.sz >= 16 end end return false if arg.kind_of? ModRM and arg.adsz and o.props[:adsz] and arg.adsz != o.props[:adsz] cond = true if s = o.props[:argsz] and (arg.kind_of? Reg or arg.kind_of? ModRM) cond = (!arg.sz or arg.sz == s or spec == :reg_dx) end cond and case spec when :reg; arg.kind_of? Reg and (arg.sz >= 16 or o.props[:argsz]) when :modrm; (arg.kind_of? ModRM or arg.kind_of? Reg) and (!arg.sz or arg.sz >= 16 or o.props[:argsz]) and (!o.props[:modrmA] or arg.kind_of? ModRM) and (!o.props[:modrmR] or arg.kind_of? Reg) when :i; arg.kind_of? Expression when :imm_val1; arg.kind_of? Expression and arg.reduce == 1 when :imm_val3; arg.kind_of? Expression and arg.reduce == 3 when :reg_eax; arg.kind_of? Reg and arg.val == 0 when :reg_cl; arg.kind_of? Reg and arg.val == 1 and arg.sz == 8 when :reg_dx; arg.kind_of? Reg and arg.val == 2 and arg.sz == 16 when :seg3; arg.kind_of? SegReg when :seg3A; arg.kind_of? SegReg and arg.val > 3 when :seg2; arg.kind_of? SegReg and arg.val < 4 when :seg2A; arg.kind_of? SegReg and arg.val < 4 and arg.val != 1 when :eeec; arg.kind_of? CtrlReg when :eeed; arg.kind_of? DbgReg when :eeet; arg.kind_of? TstReg when :mrm_imm; arg.kind_of? ModRM and not arg.s and not arg.i and not arg.b when :farptr; arg.kind_of? Farptr when :regfp; arg.kind_of? FpReg when :regfp0; arg.kind_of? FpReg and (arg.val == nil or arg.val == 0) when :modrmmmx; arg.kind_of? ModRM or (arg.kind_of? SimdReg and (arg.sz == 64 or (arg.sz == 128 and o.props[:xmmx]))) and (!o.props[:modrmA] or arg.kind_of? ModRM) and (!o.props[:modrmR] or arg.kind_of? SimdReg) when :regmmx; arg.kind_of? SimdReg and (arg.sz == 64 or (arg.sz == 128 and o.props[:xmmx])) when :modrmxmm; arg.kind_of? ModRM or (arg.kind_of? SimdReg and arg.sz == 128) and (!o.props[:modrmA] or arg.kind_of? ModRM) and (!o.props[:modrmR] or arg.kind_of? SimdReg) when :regxmm; arg.kind_of? SimdReg and arg.sz == 128 when :modrmymm; arg.kind_of? ModRM or (arg.kind_of? SimdReg and arg.sz == 256) and (!o.props[:modrmA] or arg.kind_of? ModRM) and (!o.props[:modrmR] or arg.kind_of? SimdReg) when :regymm; arg.kind_of? SimdReg and arg.sz == 256 when :vexvreg; arg.kind_of? Reg and arg.sz == @size when :vexvxmm, :i4xmm; arg.kind_of? SimdReg and arg.sz == 128 when :vexvymm, :i4ymm; arg.kind_of? SimdReg and arg.sz == 256 when :i8, :u8, :u16 arg.kind_of? Expression and (o.props[:setip] or Expression.in_range?(arg, spec) != false) # true or nil allowed # jz 0x28282828 may fit in :i8 depending on instr addr else raise EncodeError, "Internal error: unknown argument specification #{spec.inspect}" end end
check if the argument matches the opcode's argument spec
parse_arg_valid?
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/parse.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/parse.rb
BSD-3-Clause
def parse_instruction_fixup(i) if m = i.args.grep(ModRM).first and not m.sz if i.opname == 'movzx' or i.opname == 'movsx' m.sz = 8 else if r = i.args.grep(Reg).first m.sz = r.sz elsif l = opcode_list_byname[i.opname].map { |o| o.props[:argsz] }.uniq and l.length == 1 and l.first m.sz = l.first else # this is also the size of ctrlreg/dbgreg etc # XXX fpu/simd ? m.sz = i.prefix[:sz] || @size end end end if m and not m.adsz if opcode_list_byname[i.opname].all? { |o| o.props[:adsz] } m.adsz = opcode_list_byname[i.opname].first.props[:adsz] else m.adsz = i.prefix[:sz] || @size end end end
fixup the sz of a modrm argument, defaults to other argument size or current cpu mode
parse_instruction_fixup
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/parse.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/parse.rb
BSD-3-Clause
def decode_instr_interpret(di, addr) if di.opcode.props[:setip] and di.instruction.args.last.kind_of? Expression and di.opcode.name[0] != ?t delta = Expression[di.instruction.args.last, :<<, 2].reduce if di.opcode.args.include? :i26 # absolute jump in the 0x3ff_ffff region surrounding next_pc if delta.kind_of? Expression and delta.op == :& and delta.rexpr == 0x3ff_fffc # relocated arg: assume the linker mapped so that instr&target are in the same region arg = Expression[delta.lexpr].reduce else arg = Expression[[[addr, :+, di.bin_length], :&, 0xfc00_0000], :+, delta].reduce end else arg = Expression[[addr, :+, di.bin_length], :+, delta].reduce end di.instruction.args[-1] = Expression[arg] end di end
converts relative branch offsets to absolute addresses else just add the offset +off+ of the instruction + its length (off may be an Expression) assumes edata.ptr points just after the instruction (as decode_instr_op left it) do not call twice on the same di !
decode_instr_interpret
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/mips/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/mips/decode.rb
BSD-3-Clause
def backtrace_found_result(dasm, di, expr, type, len) if di.opcode.name == 'jalr' and di.instruction.args == [:$t9] expr = dasm.normalize(expr) (dasm.address_binding[expr] ||= {})[:$t9] ||= expr end end
make the target of the call know the value of $t9 (specified by the ABI) XXX hackish
backtrace_found_result
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/mips/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/mips/decode.rb
BSD-3-Clause
def addop_branch(nbase, bin, *argprops) nbase += 'ctr' if argprops.delete :ctr nbase += 'lr' if argprops.delete :lr addop(nbase, bin, :setip, *argprops) addop(nbase+'l', bin|1, :setip, :saveip, *argprops) return if nbase[-2, 2] == 'lr' or nbase[-3, 3] == 'ctr' addop(nbase+'a', bin|2, :setip, *argprops) addop(nbase+'la', bin|3, :setip, :saveip, *argprops) end
generate l/a variations, add :setip/:saveip, include lr/ctr in opname
addop_branch
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ppc/opcodes.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ppc/opcodes.rb
BSD-3-Clause
def transfer_size_mode(list) return list if list.find { |op| not op.name.include? 'mov' } @transfersz == 0 ? list.find_all { |op| op.name.include? 'fmov.s' } : list.reject { |op| op.name.include? 'fmov.s' } end
depending on transfert size mode (sz flag), fmov instructions manipulate single ou double precision values instruction aliasing appears when sz is not handled
transfer_size_mode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/sh4/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/sh4/decode.rb
BSD-3-Clause
def precision_mode(list) @fpprecision == 0 ? list.reject { |op| op.args.include? :drn } : list.find_all { |op| op.args.include? :frn } end
when pr flag is set, floating point instructions are executed as double-precision operations thus register pair is used (DRn registers)
precision_mode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/sh4/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/sh4/decode.rb
BSD-3-Clause
def decode_cmp_expr(di, a0, a1) case di.opcode.name when 'cmp/eq'; Expression[a0, :'==', a1] when 'cmp/ge'; Expression[a0, :'>=', a1] # signed when 'cmp/gt'; Expression[a0, :'>', a1] # signed when 'cmp/hi'; Expression[a0, :'>', a1] # unsigned when 'cmp/hs'; Expression[a0, :'>=', a1] # unsigned end end
interprets a condition code (in an opcode name) as an expression
decode_cmp_expr
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/sh4/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/sh4/decode.rb
BSD-3-Clause
def findreg(sz = @cpusz) caching = @state.cache.keys.grep(Reg).map { |r| r.val } if not regval = (@state.abi_trashregs - @state.used - caching).first || ([*0..@regnummax] - @state.used).first raise 'need more registers! (or a better compiler?)' end getreg(regval, sz) end
returns an available register, tries to find one not in @state.cache do not use with sz==8 (aliasing ah=>esp) does not put it in @state.inuse
findreg
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
BSD-3-Clause
def make_volatile(e, type, rsz=@cpusz) if e.kind_of? ModRM or @state.bound.index(e) if type.integral? or type.pointer? oldval = @state.cache[e] unuse e sz = typesize[type.pointer? ? :ptr : type.name]*8 if sz < @cpusz or sz < rsz or e.sz < rsz e2 = inuse findreg(rsz) op = ((type.specifier == :unsigned) ? 'movzx' : 'movsx') op = 'mov' if e.sz == e2.sz if e2.sz == 64 and e.sz == 32 if op == 'movsx' instr 'movsxd', e2, e else instr 'mov', Reg.new(e2.val, 32), e end else instr op, e2, e end else e2 = inuse findreg(sz) instr 'mov', e2, e end @state.cache[e2] = oldval if oldval and e.kind_of? ModRM e2 elsif type.float? raise 'float unhandled' else raise "cannot cast #{e} to #{type}" end elsif e.kind_of? Address make_volatile resolve_address(e), type, rsz elsif e.kind_of? Expression if type.integral? or type.pointer? e2 = inuse findreg instr 'mov', e2, e e2 elsif type.float? raise 'float unhandled' else raise "cannot cast #{e} to #{type}" end else e end end
copies the arg e to a volatile location (register/composite) if it is not already unuses the old storage may return a register bigger than the type size (eg __int8 are stored in full reg size)
make_volatile
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
BSD-3-Clause
def i_to_i32(v) if v.kind_of? Expression and i = v.reduce and i.kind_of?(Integer) i &= 0xffff_ffff_ffff_ffff if i <= 0x7fff_ffff elsif i >= (1<<64)-0x8000_0000 v = Expression[Expression.make_signed(i, 64)] else v = make_volatile(v, C::BaseType.new(:int)) unuse v end end v end
takes an argument, if the argument is an integer that does not fit in an i32, moves it to a temp reg the reg is unused, so use this only right when generating the offending instr (eg cmp, add..)
i_to_i32
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
BSD-3-Clause
def c_cexpr_inner(expr) case expr when ::Integer; Expression[expr] when C::Variable; findvar(expr) when C::CExpression if not expr.lexpr or not expr.rexpr inuse c_cexpr_inner_nol(expr) else inuse c_cexpr_inner_l(expr) end when C::Label; findvar(C::Variable.new(expr.name, C::Array.new(C::BaseType.new(:void), 1))) else puts "c_ce_i: unsupported #{expr}" if $VERBOSE end end
compiles a c expression, returns an X64 instruction argument
c_cexpr_inner
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/compile_c.rb
BSD-3-Clause
def decode_c_function_prototype(cp, sym, orig=nil) sym = cp.toplevel.symbol[sym] if sym.kind_of?(::String) df = DecodedFunction.new orig ||= Expression[sym.name] new_bt = lambda { |expr, rlen| df.backtracked_for << BacktraceTrace.new(expr, orig, expr, rlen ? :r : :x, rlen) } # return instr emulation if sym.has_attribute 'noreturn' or sym.has_attribute '__noreturn__' df.noreturn = true else new_bt[Indirection[:rsp, @size/8, orig], nil] end # register dirty (MS standard ABI) [:rax, :rcx, :rdx, :r8, :r9, :r10, :r11].each { |r| df.backtrace_binding.update r => Expression::Unknown } if cp.lexer.definition['__MS_X86_64_ABI__'] reg_args = [:rcx, :rdx, :r8, :r9] else reg_args = [:rdi, :rsi, :rdx, :rcx, :r8, :r9] end al = cp.typesize[:ptr] df.backtrace_binding[:rsp] = Expression[:rsp, :+, al] # scan args for function pointers # TODO walk structs/unions.. stackoff = al sym.type.args.to_a.zip(reg_args).each { |a, r| if not r r = Indirection[[:rsp, :+, stackoff], al, orig] stackoff += (cp.sizeof(a) + al - 1) / al * al end if a.type.untypedef.kind_of? C::Pointer pt = a.type.untypedef.type.untypedef if pt.kind_of? C::Function new_bt[r, nil] df.backtracked_for.last.detached = true elsif pt.kind_of? C::Struct new_bt[r, al] else new_bt[r, cp.sizeof(nil, pt)] end end } df end
returns a DecodedFunction from a parsed C function prototype
decode_c_function_prototype
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/decode.rb
BSD-3-Clause
def symbolic(di=nil) s = Sym[@val] s = di.next_addr if s == :rip and di if @sz == 8 and to_s[-1] == ?h Expression[[Sym[@val-16], :>>, 8], :&, 0xff] elsif @sz == 8 Expression[s, :&, 0xff] elsif @sz == 16 Expression[s, :&, 0xffff] elsif @sz == 32 Expression[s, :&, 0xffffffff] else s end end
returns a symbolic representation of the register: cx => :rcx & 0xffff ah => (:rax >> 8) & 0xff XXX in x64, 32bits operations are zero-extended to 64bits (eg mov rax, 0x1234_ffff_ffff ; add eax, 1 => rax == 0
symbolic
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/main.rb
BSD-3-Clause
def val_enc if @sz == 8 and @val >= 16; @val-12 # ah, bh, ch, dh elsif @val >= 16 # rip else @val & 7 # others end end
returns the part of @val to encode in an instruction field
val_enc
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/main.rb
BSD-3-Clause
def val_rex if @sz == 8 and @val >= 16 # ah, bh, ch, dh: rex forbidden elsif @val >= 16 # rip else @val >> 3 # others end end
returns the part of @val to encode in an instruction's rex prefix
val_rex
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/main.rb
BSD-3-Clause
def initialize(*a) super(:latest) @size = 64 a.delete @size @endianness = (a & [:big, :little]).first || :little a.delete @endianness @family = a.pop || :latest raise "Invalid arguments #{a.inspect}" if not a.empty? raise "Invalid X86_64 family #{@family.inspect}" if not respond_to?("init_#@family") end
Create a new instance of an X86 cpu arguments (any order) - instruction set (386, 486, sse2...) [latest] - endianness [:little]
initialize
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/main.rb
BSD-3-Clause
def tune_prepro(pp) super(pp, :itsmeX64) # ask Ia32's to just call super() pp.define_weak('_M_AMD64') pp.define_weak('_M_X64') pp.define_weak('__amd64__') pp.define_weak('__x86_64__') end
defines some preprocessor macros to say who we are: TODO
tune_prepro
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/main.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/main.rb
BSD-3-Clause
def parse_argregclasslist [Reg, SimdReg, SegReg, DbgReg, TstReg, CtrlReg, FpReg] end
needed due to how ruby inheritance works wrt constants
parse_argregclasslist
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/x86_64/parse.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/x86_64/parse.rb
BSD-3-Clause
def init_z80_common @opcode_list = [] @valid_args.update [:i8, :u8, :i16, :u16, :m16, :r_a, :r_af, :r_hl, :r_de, :r_sp, :r_i, :m_bc, :m_de, :m_sp, :m_hl, :mf8, :mfc ].inject({}) { |h, v| h.update v => true } @fields_mask.update :rz => 7, :ry => 7, :rp => 3, :rp2 => 3, :iy => 7, :iy8 => 7 @fields_shift.update :rz => 0, :ry => 3, :rp => 4, :rp2 => 4, :iy => 3, :iy8 => 3 # some opcodes are in init_z80 when they are not part of the GB ABI addop 'nop', [0b00_000_000] addop 'jr', [0b00_011_000], :setip, :stopexec, :i8 %w[nz z nc c].each_with_index { |cc, i| addop 'jr' + cc, [0b00_100_000 | (i << 3)], :setip, :i8 } addop 'ld', [0b00_000_001], :rp, :i16 addop 'add', [0b00_001_001], :r_hl, :rp addop 'ld', [0b00_000_010], :m_bc, :r_a addop 'ld', [0b00_001_010], :r_a, :m_bc addop 'ld', [0b00_010_010], :m_de, :r_a addop 'ld', [0b00_011_010], :r_a, :m_de addop 'inc', [0b00_000_011], :rp addop 'dec', [0b00_001_011], :rp addop 'inc', [0b00_000_100], :ry addop 'dec', [0b00_000_101], :ry addop 'ld', [0b00_000_110], :ry, :i8 addop 'rlca', [0b00_000_111] # rotate addop 'rrca', [0b00_001_111] addop 'rla', [0b00_010_111] addop 'rra', [0b00_011_111] addop 'daa', [0b00_100_111] addop 'cpl', [0b00_101_111] addop 'scf', [0b00_110_111] addop 'ccf', [0b00_111_111] addop 'halt', [0b01_110_110] # ld (HL), (HL) addop 'ld', [0b01_000_000], :ry, :rz addop 'add', [0b10_000_000], :r_a, :rz addop 'adc', [0b10_001_000], :r_a, :rz addop 'sub', [0b10_010_000], :r_a, :rz addop 'sbc', [0b10_011_000], :r_a, :rz addop 'and', [0b10_100_000], :r_a, :rz addop 'xor', [0b10_101_000], :r_a, :rz addop 'or', [0b10_110_000], :r_a, :rz addop 'cmp', [0b10_111_000], :r_a, :rz # alias cp addop 'cp', [0b10_111_000], :r_a, :rz # compare addop_macrocc 'ret', [0b11_000_000], :setip addop 'pop', [0b11_000_001], :rp2 addop 'ret', [0b11_001_001], :stopexec, :setip addop 'jmp', [0b11_101_001], :r_hl, :setip, :stopexec # alias jp addop 'jp', [0b11_101_001], :r_hl, :setip, :stopexec addop 'ld', [0b11_111_001], :r_sp, :r_hl addop_macrocc 'j', [0b11_000_010], :setip, :u16 # alias jp addop_macrocc 'jp', [0b11_000_010], :setip, :u16 addop 'jmp', [0b11_000_011], :setip, :stopexec, :u16 # alias jp addop 'jp', [0b11_000_011], :setip, :stopexec, :u16 addop 'di', [0b11_110_011] # disable interrupts addop 'ei', [0b11_111_011] addop_macrocc 'call', [0b11_000_100], :u16, :setip, :saveip addop 'push', [0b11_000_101], :rp2 addop 'call', [0b11_001_101], :u16, :setip, :saveip, :stopexec addop 'add', [0b11_000_110], :r_a, :i8 addop 'adc', [0b11_001_110], :r_a, :i8 addop 'sub', [0b11_010_110], :r_a, :i8 addop 'sbc', [0b11_011_110], :r_a, :i8 addop 'and', [0b11_100_110], :r_a, :i8 addop 'xor', [0b11_101_110], :r_a, :i8 addop 'or', [0b11_110_110], :r_a, :i8 addop 'cp', [0b11_111_110], :r_a, :i8 addop 'rst', [0b11_000_111], :iy8 # call off in page 0 addop 'rlc', [0xCB, 0b00_000_000], :rz # rotate addop 'rrc', [0xCB, 0b00_001_000], :rz addop 'rl', [0xCB, 0b00_010_000], :rz addop 'rr', [0xCB, 0b00_011_000], :rz addop 'sla', [0xCB, 0b00_100_000], :rz # shift addop 'sra', [0xCB, 0b00_101_000], :rz addop 'srl', [0xCB, 0b00_111_000], :rz addop 'bit', [0xCB, 0b01_000_000], :iy, :rz # bit test addop 'res', [0xCB, 0b10_000_000], :iy, :rz # bit reset addop 'set', [0xCB, 0b11_000_000], :iy, :rz # bit set end
data from http://www.z80.info/decoding.htm
init_z80_common
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/z80/opcodes.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/z80/opcodes.rb
BSD-3-Clause
def init_gb init_z80_common addop 'ld', [0x08], :m16, :r_sp addop 'stop', [0x10] addop 'ldi', [0x22], :m_hl, :r_a # (hl++) <- a addop 'ldi', [0x2A], :r_a, :m_hl addop 'ldd', [0x32], :m_hl, :r_a # (hl--) <- a addop 'ldd', [0x3A], :r_a, :m_hl addop 'reti', [0xD9], :setip, :stopexec # override retpo/jpo @opcode_list.delete_if { |op| op.bin[0] & 0xE5 == 0xE0 } # rm E0 E2 E8 EA F0 F2 F8 FA addop 'ld', [0xE0], :mf8, :r_a # (0xff00 + :i8) addop 'ld', [0xE2], :mfc, :r_a # (0xff00 + :r_c) addop 'add', [0xE8], :r_sp, :i8 addop 'ld', [0xEA], :m16, :r_a addop 'ld', [0xF0], :r_a, :mf8 addop 'ld', [0xF2], :r_a, :mfc addop 'ld', [0xF8], :r_hl, :r_sp, :i8 # hl <- sp+:i8 addop 'ld', [0xFA], :r_a, :m16 addop 'swap', [0xCB, 0x30], :rz addop 'inv_dd', [0xDD], :stopexec # invalid prefixes addop 'inv_ed', [0xED], :stopexec addop 'inv_fd', [0xFD], :stopexec addop 'unk_nop', [], :i8 # undefined opcode = nop @unknown_opcode = @opcode_list.last end
gameboy processor from http://nocash.emubase.de/pandocs.htm#cpucomparisionwithz80
init_gb
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/z80/opcodes.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/z80/opcodes.rb
BSD-3-Clause
def member(name) @members.find { |m| m.name == name } end
return the 1st member whose name is name
member
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff.rb
BSD-3-Clause
def decode(coff) return set_default_values(coff) if coff.header.size_opthdr == 0 and not coff.header.characteristics.include?('EXECUTABLE_IMAGE') off = coff.curencoded.ptr super(coff) nrva = (coff.header.size_opthdr - (coff.curencoded.ptr - off)) / 8 nrva = @numrva if nrva < 0 if nrva > DIRECTORIES.length or nrva != @numrva puts "W: COFF: Weird directories count #{@numrva}" if $VERBOSE nrva = DIRECTORIES.length if nrva > DIRECTORIES.length end coff.directory = {} DIRECTORIES[0, nrva].each { |dir| rva = coff.decode_word sz = coff.decode_word if rva != 0 or sz != 0 coff.directory[dir] = [rva, sz] end } end
decodes a COFF optional header from coff.cursection also decodes directories in coff.directory
decode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def decode(coff) super(coff) if coff.sect_at_rva(@libname_p) @libname = coff.decode_strz end if coff.sect_at_rva(@func_p) @exports = [] addrs = [] @num_exports.times { addrs << coff.decode_word } @num_exports.times { |i| e = Export.new e.ordinal = i + @ordinal_base addr = addrs[i] if addr >= coff.directory['export_table'][0] and addr < coff.directory['export_table'][0] + coff.directory['export_table'][1] and coff.sect_at_rva(addr) name = coff.decode_strz e.forwarder_lib, name = name.split('.', 2) if name[0] == ?# e.forwarder_ordinal = name[1..-1].to_i else e.forwarder_name = name end else e.target = e.target_rva = addr end @exports << e } end if coff.sect_at_rva(@names_p) namep = [] num_names.times { namep << coff.decode_word } end if coff.sect_at_rva(@ord_p) ords = [] num_names.times { ords << coff.decode_half } end if namep and ords namep.zip(ords).each { |np, oi| @exports[oi].name_p = np if coff.sect_at_rva(np) @exports[oi].name = coff.decode_strz end } end end
decodes a COFF export table from coff.cursection
decode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def decode(coff) super(coff) len = coff.decode_word len -= 8 if len < 0 or len % 2 != 0 puts "W: COFF: Invalid relocation table length #{len+8}" if $VERBOSE coff.curencoded.read(len) if len > 0 @relocs = [] return end @relocs = coff.curencoded.read(len).unpack(coff.endianness == :big ? 'n*' : 'v*').map { |r| Relocation.new(r&0xfff, r>>12) } #(len/2).times { @relocs << Relocation.decode(coff) } # tables may be big, this is too slow end
decodes a relocation table from coff.encoded.ptr
decode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def sect_at_rva(rva) return if not rva or rva <= 0 if sections and not @sections.empty? if s = @sections.find { |s_| s_.virtaddr <= rva and s_.virtaddr + EncodedData.align_size((s_.virtsize == 0 ? s_.rawsize : s_.virtsize), @optheader.sect_align) > rva } s.encoded.ptr = rva - s.virtaddr @cursection = s elsif rva < @sections.map { |s_| s_.virtaddr }.min @encoded.ptr = rva @cursection = self end elsif rva <= @encoded.length @encoded.ptr = rva @cursection = self end end
converts an RVA (offset from base address of file when loaded in memory) to the section containing it using the section table updates @cursection and @cursection.encoded.ptr to point to the specified address may return self when rva points to the coff header returns nil if none match, 0 never matches
sect_at_rva
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def fileoff_to_addr(foff) if s = @sections.find { |s_| s_.rawaddr <= foff and s_.rawaddr + s_.rawsize > foff } s.virtaddr + foff - s.rawaddr + (@load_address ||= @optheader.image_base) elsif foff >= 0 and foff < @optheader.headers_size foff + (@load_address ||= @optheader.image_base) end end
file offset -> memory address handles LoadedPE
fileoff_to_addr
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def decode_header @cursection ||= self @encoded.ptr ||= 0 @sections = [] @header.decode(self) optoff = @encoded.ptr @optheader.decode(self) decode_symbols if @header.num_sym != 0 and not @header.characteristics.include? 'DEBUG_STRIPPED' curencoded.ptr = optoff + @header.size_opthdr decode_sections if sect_at_rva(@optheader.entrypoint) curencoded.add_export new_label('entrypoint') end (DIRECTORIES - ['certificate_table']).each { |d| if @directory[d] and sect_at_rva(@directory[d][0]) curencoded.add_export new_label(d) end } end
decodes the COFF header, optional header, section headers marks entrypoint and directories as edata.expord
decode_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def decode_symbols endptr = @encoded.ptr = @header.ptr_sym + 18*@header.num_sym strlen = decode_word @encoded.ptr = endptr strtab = @encoded.read(strlen) @encoded.ptr = @header.ptr_sym @symbols = [] @header.num_sym.times { break if @encoded.ptr >= endptr or @encoded.ptr >= @encoded.length @symbols << Symbol.decode(self, strtab) # keep the reloc.sym_idx accurate @symbols.last.nr_aux.times { @symbols << nil } } end
decode the COFF symbol table (obj only)
decode_symbols
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def decode_section_body(s) raw = EncodedData.align_size(s.rawsize, @optheader.file_align) virt = s.virtsize virt = raw = s.rawsize if @header.size_opthdr == 0 virt = raw if virt == 0 virt = EncodedData.align_size(virt, @optheader.sect_align) s.encoded = @encoded[s.rawaddr, [raw, virt].min] || EncodedData.new s.encoded.virtsize = virt end
decodes a section content (allows simpler LoadedPE override)
decode_section_body
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def decode_exports if @directory['export_table'] and sect_at_rva(@directory['export_table'][0]) @export = ExportDirectory.decode(self) @export.exports.to_a.each { |e| if e.name and sect_at_rva(e.target) name = e.name elsif e.ordinal and sect_at_rva(e.target) name = "ord_#{@export.libname}_#{e.ordinal}" end e.target = curencoded.add_export new_label(name) if name } end end
decodes COFF export table from directory mark exported names as encoded.export
decode_exports
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def decode_imports if @directory['import_table'] and sect_at_rva(@directory['import_table'][0]) @imports = ImportDirectory.decode_all(self) iatlen = @bitsize/8 @imports.each { |id| if sect_at_rva(id.iat_p) ptr = curencoded.ptr id.imports.each { |i| if i.name name = new_label i.name elsif i.ordinal name = new_label "ord_#{id.libname}_#{i.ordinal}" end if name i.target ||= name r = Metasm::Relocation.new(Expression[name], "u#@bitsize".to_sym, @endianness) curencoded.reloc[ptr] = r curencoded.add_export new_label('iat_'+name), ptr, true end ptr += iatlen } end } end end
decodes COFF import tables from directory mark iat entries as encoded.export
decode_imports
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def decode_relocs if @directory['base_relocation_table'] and sect_at_rva(@directory['base_relocation_table'][0]) end_ptr = curencoded.ptr + @directory['base_relocation_table'][1] @relocations = [] while curencoded.ptr < end_ptr @relocations << RelocationTable.decode(self) end # interpret as EncodedData relocations relocfunc = ('decode_reloc_' << @header.machine.downcase).to_sym if not respond_to? relocfunc puts "W: COFF: unsupported relocs for architecture #{@header.machine}" if $VERBOSE return end @relocations.each { |rt| rt.relocs.each { |r| if s = sect_at_rva(rt.base_addr + r.offset) e, p = s.encoded, s.encoded.ptr rel = send(relocfunc, r) e.reloc[p] = rel if rel end } } end end
decode COFF relocation tables from directory
decode_relocs
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def decode_reloc_i386(r) case r.type when 'ABSOLUTE' when 'HIGHLOW' addr = decode_word if s = sect_at_va(addr) label = label_at(s.encoded, s.encoded.ptr, "xref_#{Expression[addr]}") Metasm::Relocation.new(Expression[label], :u32, @endianness) end when 'DIR64' addr = decode_xword if s = sect_at_va(addr) label = label_at(s.encoded, s.encoded.ptr, "xref_#{Expression[addr]}") Metasm::Relocation.new(Expression[label], :u64, @endianness) end else puts "W: COFF: Unsupported i386 relocation #{r.inspect}" if $VERBOSE end end
decodes an I386 COFF relocation pointing to encoded.ptr
decode_reloc_i386
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def decode_tls if @directory['tls_table'] and sect_at_rva(@directory['tls_table'][0]) @tls = TLSDirectory.decode(self) if s = sect_at_va(@tls.callback_p) s.encoded.add_export 'tls_callback_table' @tls.callbacks.each_with_index { |cb, i| @tls.callbacks[i] = curencoded.add_export "tls_callback_#{i}" if sect_at_rva(cb) } end end end
decode TLS directory, including tls callback table
decode_tls
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def decode decode_header decode_exports decode_imports decode_resources decode_certificates decode_debug decode_tls decode_loadconfig decode_delayimports decode_com decode_relocs unless nodecode_relocs or ENV['METASM_NODECODE_RELOCS'] # decode relocs last end
decodes a COFF file (headers/exports/imports/relocs/sections) starts at encoded.ptr
decode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def cpu_from_headers case @header.machine when 'I386'; Ia32.new when 'AMD64'; X86_64.new when 'R4000'; MIPS.new(:little) else raise "unknown cpu #{@header.machine}" end end
returns a metasm CPU object corresponding to +header.machine+
cpu_from_headers
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def get_default_entrypoints ep = [] ep.concat @tls.callbacks.to_a if tls ep << (@optheader.image_base + label_rva(@optheader.entrypoint)) @export.exports.to_a.each { |e| next if e.forwarder_lib or not e.target ep << (@optheader.image_base + label_rva(e.target)) } if export ep end
returns an array including the PE entrypoint and the exported functions entrypoints TODO filter out exported data, include safeseh ?
get_default_entrypoints
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def section_info [['header', @optheader.image_base, @optheader.headers_size, nil]] + @sections.map { |s| [s.name, @optheader.image_base + s.virtaddr, s.virtsize, s.characteristics.join(',')] } end
returns an array of [name, addr, length, info]
section_info
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def fixup_names @members.each { |m| case m.name when '/' when '//' when /^\/(\d+)/ @longnames.ptr = $1.to_i m.name = decode_strz(@longnames).chomp("/") else m.name.chomp! "/" end } end
set real name to archive members look it up in the name table member if needed, or just remove the trailing /
fixup_names
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_decode.rb
BSD-3-Clause
def encode(coff) opth = super(coff) DIRECTORIES[0, @numrva].each { |d| if d = coff.directory[d] d = d.dup d[0] = Expression[d[0], :-, coff.label_at(coff.encoded, 0)] if d[0].kind_of?(::String) else d = [0, 0] end opth << coff.encode_word(d[0]) << coff.encode_word(d[1]) } opth end
encodes an Optional header and the directories
encode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def set_default_values(coff) @signature ||= (coff.bitsize == 64 ? 'PE+' : 'PE') @link_ver_maj ||= 1 @link_ver_min ||= 0 @sect_align ||= 0x1000 align = lambda { |sz| EncodedData.align_size(sz, @sect_align) } @code_size ||= coff.sections.find_all { |s| s.characteristics.include? 'CONTAINS_CODE' }.inject(0) { |sum, s| sum + align[s.virtsize] } @data_size ||= coff.sections.find_all { |s| s.characteristics.include? 'CONTAINS_DATA' }.inject(0) { |sum, s| sum + align[s.virtsize] } @udata_size ||= coff.sections.find_all { |s| s.characteristics.include? 'CONTAINS_UDATA' }.inject(0) { |sum, s| sum + align[s.virtsize] } @entrypoint = Expression[@entrypoint, :-, coff.label_at(coff.encoded, 0)] if entrypoint and not @entrypoint.kind_of?(::Integer) tmp = coff.sections.find { |s| s.characteristics.include? 'CONTAINS_CODE' } @base_of_code ||= (tmp ? Expression[coff.label_at(tmp.encoded, 0), :-, coff.label_at(coff.encoded, 0)] : 0) tmp = coff.sections.find { |s| s.characteristics.include? 'CONTAINS_DATA' } @base_of_data ||= (tmp ? Expression[coff.label_at(tmp.encoded, 0), :-, coff.label_at(coff.encoded, 0)] : 0) @file_align ||= 0x200 @os_ver_maj ||= 4 @subsys_maj ||= 4 @stack_reserve||= 0x100000 @stack_commit ||= 0x1000 @heap_reserve ||= 0x100000 @heap_commit ||= 0x1000 @numrva ||= DIRECTORIES.length super(coff) end
find good default values for optheader members, based on coff.sections
set_default_values
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def set_default_values(coff) @name ||= '' @virtsize ||= @encoded.virtsize @virtaddr ||= Expression[coff.label_at(@encoded, 0, 'sect_start'), :-, coff.label_at(coff.encoded, 0)] @rawsize ||= coff.new_label('sect_rawsize') @rawaddr ||= coff.new_label('sect_rawaddr') super(coff) end
find good default values for section header members, defines rawaddr/rawsize as new_label for later fixup
set_default_values
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def encode(coff, edata) edata['iat'] << EncodedData.new # edata['ilt'] = edata['iat'] label = lambda { |n| coff.label_at(edata[n], 0, n) } rva_end = lambda { |n| Expression[[label[n], :-, coff.label_at(coff.encoded, 0)], :+, edata[n].virtsize] } @libname_p = rva_end['nametable'] @ilt_p = rva_end['ilt'] @iat_p ||= Expression[coff.label_at(edata['iat'].last, 0, 'iat'), :-, coff.label_at(coff.encoded, 0)] edata['idata'] << super(coff) edata['nametable'] << @libname << 0 ord_mask = 1 << (coff.bitsize - 1) @imports.each { |i| edata['iat'].last.add_export i.target, edata['iat'].last.virtsize if i.target if i.ordinal ptr = coff.encode_xword(Expression[i.ordinal, :|, ord_mask]) else edata['nametable'].align 2 ptr = coff.encode_xword(rva_end['nametable']) edata['nametable'] << coff.encode_half(i.hint || 0) << i.name << 0 end edata['ilt'] << ptr edata['iat'].last << ptr } edata['ilt'] << coff.encode_xword(0) edata['iat'].last << coff.encode_xword(0) end
encode one import directory + iat + names in the edata hash received as arg
encode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def encode_exports edata = @export.encode self # must include name tables (for forwarders) @directory['export_table'] = [label_at(edata, 0, 'export_table'), edata.virtsize] s = Section.new s.name = '.edata' s.encoded = edata s.characteristics = %w[MEM_READ] encode_append_section s end
encodes the export table as a new section, updates directory['export_table']
encode_exports
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def encode_imports idata, iat = ImportDirectory.encode(self, @imports) @directory['import_table'] = [label_at(idata, 0, 'idata'), idata.virtsize] s = Section.new s.name = '.idata' s.encoded = idata s.characteristics = %w[MEM_READ MEM_WRITE MEM_DISCARDABLE] encode_append_section s if @imports.first and @imports.first.iat_p.kind_of?(Integer) # ordiat = iat.sort_by { @import[x].iat_p } ordiat = @imports.zip(iat).sort_by { |id, it| id.iat_p.kind_of?(Integer) ? id.iat_p : 1<<65 }.map { |id, it| it } else ordiat = iat end @directory['iat'] = [label_at(ordiat.first, 0, 'iat'), Expression[label_at(ordiat.last, ordiat.last.virtsize, 'iat_end'), :-, label_at(ordiat.first, 0)]] if not ordiat.empty? iat_s = nil plt = Section.new plt.name = '.plt' plt.encoded = EncodedData.new plt.characteristics = %w[MEM_READ MEM_EXECUTE] @imports.zip(iat) { |id, it| if id.iat_p.kind_of?(Integer) and @sections.find { |s_| s_.virtaddr <= id.iat_p and s_.virtaddr + (s_.virtsize || s_.encoded.virtsize) > id.iat_p } id.iat = it # will be fixed up after encode_section else # XXX should not be mixed (for @directory['iat'][1]) if not iat_s iat_s = Section.new iat_s.name = '.iat' iat_s.encoded = EncodedData.new iat_s.characteristics = %w[MEM_READ MEM_WRITE] encode_append_section iat_s end iat_s.encoded << it end id.imports.each { |i| if i.thunk arch_encode_thunk(plt.encoded, i) end } } encode_append_section plt if not plt.encoded.empty? end
encodes the import tables as a new section, updates directory['import_table'] and directory['iat']
encode_imports
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def encode_relocs if @relocations.empty? rt = RelocationTable.new rt.base_addr = 0 rt.relocs = [] @relocations << rt end relocs = @relocations.inject(EncodedData.new) { |edata, rt_| edata << rt_.encode(self) } @directory['base_relocation_table'] = [label_at(relocs, 0, 'reloc_table'), relocs.virtsize] s = Section.new s.name = '.reloc' s.encoded = relocs s.characteristics = %w[MEM_READ MEM_DISCARDABLE] encode_append_section s end
encodes relocation tables in a new section .reloc, updates @directory['base_relocation_table']
encode_relocs
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def create_relocation_tables @relocations = [] # create a fake binding with all exports, to find only-image_base-dependant relocs targets # not foolproof, but works in standard cases startaddr = curaddr = label_at(@encoded, 0, 'coff_start') binding = {} @sections.each { |s| binding.update s.encoded.binding(curaddr) curaddr = Expression[curaddr, :+, s.encoded.virtsize] } # for each section.encoded, make as many RelocationTables as needed @sections.each { |s| # rt.base_addr temporarily holds the offset from section_start, and is fixed up to rva before '@reloc << rt' rt = RelocationTable.new s.encoded.reloc.each { |off, rel| # check that the relocation looks like "program_start + integer" when bound using the fake binding # XXX allow :i32 etc if rel.endianness == @endianness and [:u32, :a32, :u64, :a64].include?(rel.type) and rel.target.bind(binding).reduce.kind_of?(Expression) and Expression[rel.target, :-, startaddr].bind(binding).reduce.kind_of?(::Integer) # winner ! # build relocation r = RelocationTable::Relocation.new r.offset = off & 0xfff r.type = { :u32 => 'HIGHLOW', :u64 => 'DIR64', :a32 => 'HIGHLOW', :a64 => 'DIR64' }[rel.type] # check if we need to start a new relocation table if rt.base_addr and (rt.base_addr & ~0xfff) != (off & ~0xfff) rt.base_addr = Expression[[label_at(s.encoded, 0, 'sect_start'), :-, startaddr], :+, rt.base_addr] @relocations << rt rt = RelocationTable.new end # initialize reloc table base address if needed rt.base_addr ||= off & ~0xfff (rt.relocs ||= []) << r elsif $DEBUG and not rel.target.bind(binding).reduce.kind_of?(Integer) puts "W: COFF: Ignoring weird relocation #{rel.inspect} when building relocation tables" end } if rt and rt.relocs rt.base_addr = Expression[[label_at(s.encoded, 0, 'sect_start'), :-, startaddr], :+, rt.base_addr] @relocations << rt end } end
creates the @relocations from sections.encoded.reloc
create_relocation_tables
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def pre_encode_header(target='exe', want_relocs=true) target = {:bin => 'exe', :lib => 'dll', :obj => 'obj', 'sys' => 'kmod', 'drv' => 'kmod'}.fetch(target, target) @header.machine ||= case @cpu.shortname when 'x64'; 'AMD64' when 'ia32'; 'I386' end @optheader.signature ||= case @cpu.size when 32; 'PE' when 64; 'PE+' end @bitsize = (@optheader.signature == 'PE+' ? 64 : 32) # setup header flags tmp = %w[LINE_NUMS_STRIPPED LOCAL_SYMS_STRIPPED DEBUG_STRIPPED] + case target when 'exe'; %w[EXECUTABLE_IMAGE] when 'dll'; %w[EXECUTABLE_IMAGE DLL] when 'kmod'; %w[EXECUTABLE_IMAGE] when 'obj'; [] end if @cpu.size == 32 tmp << 'x32BIT_MACHINE' else tmp << 'LARGE_ADDRESS_AWARE' end tmp << 'RELOCS_STRIPPED' if not want_relocs @header.characteristics ||= tmp @optheader.subsystem ||= case target when 'exe', 'dll'; 'WINDOWS_GUI' when 'kmod'; 'NATIVE' end tmp = [] tmp << 'NX_COMPAT' tmp << 'DYNAMIC_BASE' if want_relocs @optheader.dll_characts ||= tmp end
initialize the header from target/cpu/etc, target in ['exe' 'dll' 'kmod' 'obj']
pre_encode_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def invalidate_header # set those values to nil, they will be # recomputed during encode_header [:code_size, :data_size, :udata_size, :base_of_code, :base_of_data, :sect_align, :file_align, :image_size, :headers_size, :checksum].each { |m| @optheader.send("#{m}=", nil) } [:num_sect, :ptr_sym, :num_sym, :size_opthdr].each { |m| @header.send("#{m}=", nil) } end
resets the values in the header that may have been modified by your script (eg section count, size, imagesize, etc) call this whenever you decode a file, modify it, and want to reencode it later
invalidate_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def encode_header # encode section table, add CONTAINS_* flags from other characteristics flags s_table = EncodedData.new @sections.each { |s| if s.characteristics.kind_of? Array and s.characteristics.include? 'MEM_READ' if s.characteristics.include? 'MEM_EXECUTE' s.characteristics |= ['CONTAINS_CODE'] elsif s.encoded if s.encoded.rawsize == 0 s.characteristics |= ['CONTAINS_UDATA'] else s.characteristics |= ['CONTAINS_DATA'] end end end s.rawaddr = nil if s.rawaddr.kind_of?(::Integer) # XXX allow to force rawaddr ? s_table << s.encode(self) } # encode optional header @optheader.image_size ||= new_label('image_size') @optheader.image_base ||= label_at(@encoded, 0) @optheader.headers_size ||= new_label('headers_size') @optheader.checksum ||= new_label('checksum') @optheader.subsystem ||= 'WINDOWS_GUI' @optheader.numrva = nil opth = @optheader.encode(self) # encode header @header.machine ||= 'UNKNOWN' @header.num_sect ||= sections.length @header.time ||= Time.now.to_i & -255 @header.size_opthdr ||= opth.virtsize @encoded << @header.encode(self) << opth << s_table end
appends the header/optheader/directories/section table to @encoded
encode_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def encode_sections_fixup if @optheader.headers_size.kind_of?(::String) @encoded.fixup! @optheader.headers_size => @encoded.virtsize @optheader.headers_size = @encoded.virtsize end @encoded.align @optheader.file_align baseaddr = @optheader.image_base.kind_of?(::Integer) ? @optheader.image_base : 0x400000 binding = @encoded.binding(baseaddr) curaddr = baseaddr + @optheader.headers_size @sections.each { |s| # align curaddr = EncodedData.align_size(curaddr, @optheader.sect_align) if s.rawaddr.kind_of?(::String) @encoded.fixup! s.rawaddr => @encoded.virtsize s.rawaddr = @encoded.virtsize end if s.virtaddr.kind_of?(::Integer) raise "E: COFF: cannot encode section #{s.name}: hardcoded address too short" if curaddr > baseaddr + s.virtaddr curaddr = baseaddr + s.virtaddr end binding.update s.encoded.binding(curaddr) curaddr += s.virtsize pre_sz = @encoded.virtsize @encoded << s.encoded[0, s.encoded.rawsize] @encoded.align @optheader.file_align if s.rawsize.kind_of?(::String) @encoded.fixup! s.rawsize => (@encoded.virtsize - pre_sz) s.rawsize = @encoded.virtsize - pre_sz end } # not aligned ? spec says it is, visual studio does not binding[@optheader.image_size] = curaddr - baseaddr if @optheader.image_size.kind_of?(::String) # patch the iat where iat_p was defined # sort to ensure a 0-terminated will not overwrite an entry # (try to dump notepad.exe, which has a forwarder;) @imports.find_all { |id| id.iat_p.kind_of?(Integer) }.sort_by { |id| id.iat_p }.each { |id| s = sect_at_rva(id.iat_p) @encoded[s.rawaddr + s.encoded.ptr, id.iat.virtsize] = id.iat binding.update id.iat.binding(baseaddr + id.iat_p) } if imports @encoded.fill @encoded.fixup! binding if @optheader.checksum.kind_of?(::String) and @encoded.reloc.length == 1 # won't work if there are other unresolved relocs checksum = self.class.checksum(@encoded.data, @endianness) @encoded.fixup @optheader.checksum => checksum @optheader.checksum = checksum end end
append the section bodies to @encoded, and link the resulting binary
encode_sections_fixup
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def encode(target='exe', want_relocs=true) @encoded = EncodedData.new label_at(@encoded, 0, 'coff_start') pre_encode_header(target, want_relocs) autoimport encode_exports if export encode_imports if imports encode_resource if resource encode_tls if tls create_relocation_tables if want_relocs encode_relocs if relocations encode_header encode_sections_fixup @encoded.data end
encode a COFF file, building export/import/reloc tables if needed creates the base relocation tables (need for references to IAT not known before) defaults to generating relocatable files, eg ALSR-aware pass want_relocs=false to avoid the file overhead induced by this
encode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def read_c_attrs(cp) cp.toplevel.symbol.each_value { |v| next if not v.kind_of? C::Variable if v.has_attribute 'export' or ea = v.has_attribute_var('export_as') @export ||= ExportDirectory.new @export.exports ||= [] e = ExportDirectory::Export.new begin e.ordinal = Integer(ea || v.name) rescue ArgumentError e.name = ea || v.name end e.target = v.name @export.exports << e end if v.has_attribute('import') or ln = v.has_attribute_var('import_from') ln ||= WindowsExports::EXPORT[v.name] raise "unknown library for #{v.name}" if not ln i = ImportDirectory::Import.new if ln.include? ':' ln, name = ln.split(':') begin i.ordinal = Integer(name) rescue ArgumentError i.name = name end else i.name = v.name end if v.type.kind_of? C::Function i.thunk = v.name i.target = 'iat_'+i.thunk else i.target = v.name end @imports ||= [] if not id = @imports.find { |id_| id_.libname == ln } id = ImportDirectory.new id.libname = ln id.imports = [] @imports << id end id.imports << i end if v.has_attribute 'entrypoint' @optheader.entrypoint = v.name end } end
honors C attributes: export, export_as(foo), import_from(kernel32), entrypoint import by ordinal: extern __stdcall int anyname(int) __attribute__((import_from(ws2_32:28))); can alias imports with int mygpaddr_alias() attr(import_from(kernel32:GetProcAddr))
read_c_attrs
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def autoimport(fallback_append='A') WindowsExports rescue return # autorequire autoexports = WindowsExports::EXPORT.dup @sections.each { |s| next if not s.encoded s.encoded.export.keys.each { |e| autoexports.delete e } } @sections.each { |s| next if not s.encoded s.encoded.reloc.each_value { |r| if r.target.op == :+ and not r.target.lexpr and r.target.rexpr.kind_of?(::String) sym = target = r.target.rexpr sym = sym[4..-1] if sym[0, 4] == 'iat_' elsif r.target.op == :- and r.target.rexpr.kind_of?(::String) and r.target.lexpr.kind_of?(::String) sym = thunk = r.target.lexpr end if not dll = autoexports[sym] sym += fallback_append if sym.kind_of?(::String) and fallback_append.kind_of?(::String) next if not dll = autoexports[sym] end @imports ||= [] next if @imports.find { |id| id.imports.find { |ii| ii.name == sym } } if not id = @imports.find { |id_| id_.libname =~ /^#{dll}(\.dll)?$/i } id = ImportDirectory.new id.libname = dll id.imports = [] @imports << id end if not i = id.imports.find { |i_| i_.name == sym } i = ImportDirectory::Import.new i.name = sym id.imports << i end if (target and i.target and (i.target != target or i.thunk == target)) or (thunk and i.thunk and (i.thunk != thunk or i.target == thunk)) puts "autoimport: conflict for #{target} #{thunk} #{i.inspect}" if $VERBOSE else i.target ||= new_label(target || 'iat_' + thunk) i.thunk ||= thunk if thunk end } } end
try to resolve automatically COFF import tables from self.sections.encoded.relocations and WindowsExports::EXPORT if the relocation target is '<symbolname>' or 'iat_<symbolname>, link to the IAT address, if it is '<symbolname> + <expr>', link to a thunk (plt-like) if the relocation is not found, try again after appending 'fallback_append' to the symbol (eg wsprintf => wsprintfA)
autoimport
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/coff_encode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/coff_encode.rb
BSD-3-Clause
def addr_to_off(addr) s = @segments.find { |s_| s_.type == 'LOAD' and s_.vaddr <= addr and s_.vaddr + s_.memsz > addr } if addr addr - s.vaddr + s.offset if s end
transforms a virtual address to a file offset, from mmaped segments addresses
addr_to_off
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def addr_to_fileoff(addr) la = module_address la = (la == 0 ? (@load_address ||= 0) : 0) addr_to_off(addr - la) end
memory address -> file offset handles relocated LoadedELF
addr_to_fileoff
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def fileoff_to_addr(foff) if s = @segments.find { |s_| s_.type == 'LOAD' and s_.offset <= foff and s_.offset + s_.filesz > foff } la = module_address la = (la == 0 ? (@load_address ||= 0) : 0) s.vaddr + la + foff - s.offset end end
file offset -> memory address handles relocated LoadedELF
fileoff_to_addr
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def add_label(name, addr) if not o = addr_to_off(addr) puts "W: Elf: #{name} points to unmmaped space #{'0x%08X' % addr}" if $VERBOSE else l = new_label(name) @encoded.add_export l, o end l end
make an export of +self.encoded+, returns the label name if successful
add_label
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_header(off = 0, decode_phdr=true, decode_shdr=true) @encoded.ptr = off @header.decode self raise InvalidExeFormat, "Invalid elf header size: #{@header.ehsize}" if Header.size(self) != @header.ehsize if decode_phdr and @header.phoff != 0 decode_program_header(@header.phoff+off) end if decode_shdr and @header.shoff != 0 decode_section_header(@header.shoff+off) end end
decodes the elf header, section & program header
decode_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_section_header(off = @header.shoff) raise InvalidExeFormat, "Invalid elf section header size: #{@header.shentsize}" if Section.size(self) != @header.shentsize @encoded.add_export new_label('section_header'), off @encoded.ptr = off @sections = [] @header.shnum.times { @sections << Section.decode(self) } # read sections name if @header.shstrndx != 0 and str = @sections[@header.shstrndx] and str.encoded = @encoded[str.offset, str.size] # LoadedElf may not have shstr mmaped @sections[1..-1].each { |s| s.name = readstr(str.encoded.data, s.name_p) add_label("section_#{s.name}", s.addr) if s.name and s.addr > 0 } end end
decodes the section header section names are read from shstrndx if possible
decode_section_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_program_header(off = @header.phoff) raise InvalidExeFormat, "Invalid elf program header size: #{@header.phentsize}" if Segment.size(self) != @header.phentsize @encoded.add_export new_label('program_header'), off @encoded.ptr = off @segments = [] @header.phnum.times { @segments << Segment.decode(self) } if @header.entry != 0 add_label('entrypoint', @header.entry) end end
decodes the program header table marks the elf entrypoint as an export of +self.encoded+
decode_program_header
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def check_symbols_hash(off = @tag['HASH']) return if not @encoded.ptr = off hash_bucket_len = decode_word sym_count = decode_word hash_bucket = [] ; hash_bucket_len.times { hash_bucket << decode_word } hash_table = [] ; sym_count.times { hash_table << decode_word } @symbols.each { |s| next if not s.name or s.bind != 'GLOBAL' or s.shndx == 'UNDEF' found = false h = ELF.hash_symbol_name(s.name) off = hash_bucket[h % hash_bucket_len] sym_count.times { # to avoid DoS by loop break if off == 0 if ss = @symbols[off] and ss.name == s.name found = true break end off = hash_table[off] } if not found puts "W: Elf: Symbol #{s.name.inspect} not found in hash table" if $VERBOSE end } end
read the dynamic symbols hash table, and checks that every global and named symbol is accessible through it outputs a warning if it's not and $VERBOSE is set
check_symbols_hash
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def check_symbols_gnu_hash(off = @tag['GNU_HASH'], just_get_count=false) return if not @encoded.ptr = off # when present: the symndx first symbols are not sorted (SECTION/LOCAL/FILE/etc) symtable[symndx] is sorted (1st sorted symbol) # the sorted symbols are sorted by [gnu_hash_symbol_name(symbol.name) % hash_bucket_len] hash_bucket_len = decode_word symndx = decode_word # index of first sorted symbol in symtab maskwords = decode_word # number of words in the second part of the ghash section (32 or 64 bits) shift2 = decode_word # used in the bloom filter bloomfilter = [] ; maskwords.times { bloomfilter << decode_xword } # "bloomfilter[N] has bit B cleared if there is no M (M > symndx) which satisfies (C = @header.class) # ((gnu_hash(sym[M].name) / C) % maskwords) == N && # ((gnu_hash(sym[M].name) % C) == B || # ((gnu_hash(sym[M].name) >> shift2) % C) == B" # bloomfilter may be [~0] if shift2 end hash_bucket = [] ; hash_bucket_len.times { hash_bucket << decode_word } # bucket[N] contains the lowest M for which # gnu_hash(sym[M]) % nbuckets == N # or 0 if none hsymcount = 0 part4 = [] hash_bucket.each { |hmodidx| # for each bucket, walk all the chain # we do not walk the chains in hash_bucket order here, this # is just to read all the part4 as we don't know # beforehand the number of hashed symbols next if hmodidx == 0 # no hash chain for this mod loop do fu = decode_word hsymcount += 1 part4 << fu break if fu & 1 == 1 end } # part4[N] contains # (gnu_hash(sym[N].name) & ~1) | (N == dynsymcount-1 || (gnu_hash(sym[N].name) % nbucket) != (gnu_hash(sym[N+1].name) % nbucket)) # that's the hash, with its lower bit replaced by the bool [1 if i am the last sym having my hash as hash] # we're going to decode the symbol table, and we just want to get the nr of symbols to read if just_get_count # index of highest hashed (exported) symbols ns = hsymcount+symndx # no way to get the number of non-exported symbols from what we have here # so we'll decode all relocs and use the largest index we see.. rels = [] if @encoded.ptr = @tag['REL'] and @tag['RELENT'] == Relocation.size(self) p_end = @encoded.ptr + @tag['RELSZ'] while @encoded.ptr < p_end rels << Relocation.decode(self) end end if @encoded.ptr = @tag['RELA'] and @tag['RELAENT'] == RelocationAddend.size(self) p_end = @encoded.ptr + @tag['RELASZ'] while @encoded.ptr < p_end rels << RelocationAddend.decode(self) end end if @encoded.ptr = @tag['JMPREL'] and relcls = case @tag['PLTREL'] when 'REL'; Relocation when 'RELA'; RelocationAddend end p_end = @encoded.ptr + @tag['PLTRELSZ'] while @encoded.ptr < p_end rels << relcls.decode(self) end end maxr = rels.map { |rel| rel.symbol }.grep(::Integer).max || -1 return [ns, maxr+1].max end # TODO end
checks every symbol's accessibility through the gnu_hash table
check_symbols_gnu_hash
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_segments_tags_interpret if @tag['STRTAB'] if not sz = @tag['STRSZ'] puts "W: Elf: no string table size tag" if $VERBOSE else if l = add_label('dynamic_strtab', @tag['STRTAB']) @tag['STRTAB'] = l strtab = @encoded[l, sz].data end end end @tag.keys.each { |k| case k when Integer when 'NEEDED' # array of strings if not strtab puts "W: Elf: no string table, needed for tag #{k}" if $VERBOSE next end @tag[k].map! { |v| readstr(strtab, v) } when 'SONAME', 'RPATH', 'RUNPATH' # string if not strtab puts "W: Elf: no string table, needed for tag #{k}" if $VERBOSE next end @tag[k] = readstr(strtab, @tag[k]) when 'INIT', 'FINI', 'PLTGOT', 'HASH', 'GNU_HASH', 'SYMTAB', 'RELA', 'REL', 'JMPREL' @tag[k] = add_label('dynamic_' + k.downcase, @tag[k]) || @tag[k] when 'INIT_ARRAY', 'FINI_ARRAY', 'PREINIT_ARRAY' next if not l = add_label('dynamic_' + k.downcase, @tag[k]) if not sz = @tag.delete(k+'SZ') puts "W: Elf: tag #{k} has no corresponding size tag" if $VERBOSE next end tab = @encoded[l, sz] tab.ptr = 0 @tag[k] = [] while tab.ptr < tab.length a = decode_addr(tab) @tag[k] << (add_label("dynamic_#{k.downcase}_#{@tag[k].length}", a) || a) end when 'PLTREL'; @tag[k] = int_to_hash(@tag[k], DYNAMIC_TAG) when 'FLAGS'; @tag[k] = bits_to_hash(@tag[k], DYNAMIC_FLAGS) when 'FLAGS_1'; @tag[k] = bits_to_hash(@tag[k], DYNAMIC_FLAGS_1) when 'FEATURES_1'; @tag[k] = bits_to_hash(@tag[k], DYNAMIC_FEATURES_1) end } end
interprets tags (convert flags, arrays etc), mark them as self.encoded.export
decode_segments_tags_interpret
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_symbol_export(s) if s.name and s.shndx != 'UNDEF' and %w[NOTYPE OBJECT FUNC].include?(s.type) if @header.type == 'REL' sec = @sections[s.shndx] o = sec.offset + s.value elsif not o = addr_to_off(s.value) # allow to point to end of segment if not seg = @segments.find { |seg_| seg_.type == 'LOAD' and seg_.vaddr + seg_.memsz == s.value } # check end puts "W: Elf: symbol points to unmmaped space (#{s.inspect})" if $VERBOSE and s.shndx != 'ABS' return end # LoadedELF would have returned an addr_to_off = addr o = s.value - seg.vaddr + seg.offset end name = s.name while @encoded.export[name] and @encoded.export[name] != o puts "W: Elf: symbol #{name} already seen at #{'%X' % @encoded.export[name]} - now at #{'%X' % o}) (may be a different version definition)" if $VERBOSE name += '_' # do not modify inplace end @encoded.add_export name, o end end
marks a symbol as @encoded.export (from s.value, using segments or sections)
decode_symbol_export
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_segments_symbols return unless @tag['STRTAB'] and @tag['STRSZ'] and @tag['SYMTAB'] and (@tag['HASH'] or @tag['GNU_HASH']) raise "E: ELF: unsupported symbol entry size: #{@tag['SYMENT']}" if @tag['SYMENT'] != Symbol.size(self) # find number of symbols if @tag['HASH'] @encoded.ptr = @tag['HASH'] # assume tag already interpreted (would need addr_to_off otherwise) decode_word sym_count = decode_word else sym_count = check_symbols_gnu_hash(@tag['GNU_HASH'], true) end strtab = @encoded[@tag['STRTAB'], @tag['STRSZ']].data.to_str @encoded.ptr = @tag['SYMTAB'] @symbols.clear sym_count.times { s = Symbol.decode(self, strtab) @symbols << s decode_symbol_export(s) } check_symbols_hash if $VERBOSE check_symbols_gnu_hash if $VERBOSE end
read symbol table, and mark all symbols found as exports of self.encoded tables locations are found in self.tags XXX symbol count is found from the hash table, this may not work with GNU_HASH only binaries
decode_segments_symbols
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_segments_relocs @relocations.clear if @encoded.ptr = @tag['REL'] raise "E: ELF: unsupported rel entry size #{@tag['RELENT']}" if @tag['RELENT'] != Relocation.size(self) p_end = @encoded.ptr + @tag['RELSZ'] while @encoded.ptr < p_end @relocations << Relocation.decode(self) end end if @encoded.ptr = @tag['RELA'] raise "E: ELF: unsupported rela entry size #{@tag['RELAENT'].inspect}" if @tag['RELAENT'] != RelocationAddend.size(self) p_end = @encoded.ptr + @tag['RELASZ'] while @encoded.ptr < p_end @relocations << RelocationAddend.decode(self) end end if @encoded.ptr = @tag['JMPREL'] case reltype = @tag['PLTREL'] when 'REL'; relcls = Relocation when 'RELA'; relcls = RelocationAddend else raise "E: ELF: unsupported plt relocation type #{reltype}" end p_end = @encoded.ptr + @tag['PLTRELSZ'] while @encoded.ptr < p_end @relocations << relcls.decode(self) end end end
decode relocation tables (REL, RELA, JMPREL) from @tags
decode_segments_relocs
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_segments_relocs_interpret relocproc = "arch_decode_segments_reloc_#{@header.machine.to_s.downcase}" if not respond_to? relocproc puts "W: Elf: relocs for arch #{@header.machine} unsupported" if $VERBOSE return end @relocations.each { |r| next if r.offset == 0 if not o = addr_to_off(r.offset) puts "W: Elf: relocation in unmmaped space (#{r.inspect})" if $VERBOSE next end if @encoded.reloc[o] puts "W: Elf: not rerelocating address #{'%08X' % r.offset}" if $VERBOSE next end @encoded.ptr = o if rel = send(relocproc, r) @encoded.reloc[o] = rel end } if @header.machine == 'MIPS' and @tag['PLTGOT'] and @tag['GOTSYM'] and @tag['LOCAL_GOTNO'] puts "emulating mips PLT-like relocs" if $VERBOSE wsz = @bitsize/8 dyntab = label_addr(@tag['PLTGOT']) - (@tag['GOTSYM'] - @tag['LOCAL_GOTNO']) * wsz dt_o = addr_to_off(dyntab) @symbols.each_with_index { |sym, i| next if i < @tag['GOTSYM'] or not sym.name r = Metasm::Relocation.new(Expression[sym.name], "u#@bitsize".to_sym, @endianness) @encoded.reloc[dt_o + wsz*i] = r } end end
use relocations as self.encoded.reloc
decode_segments_relocs_interpret
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def reloc_target(reloc) target = 0 if reloc.symbol.kind_of?(Symbol) if reloc.symbol.type == 'SECTION' s = @sections[reloc.symbol.shndx] if not target = @encoded.inv_export[s.offset] target = new_label(s.name) @encoded.add_export(target, s.offset) end elsif reloc.symbol.name target = reloc.symbol.name end end target end
returns the target of a relocation using reloc.symbol may create new labels if the relocation targets a section
reloc_target
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def arch_decode_segments_reloc_386(reloc) if reloc.symbol.kind_of?(Symbol) and n = reloc.symbol.name and reloc.symbol.shndx == 'UNDEF' and @sections and s = @sections.find { |s_| s_.name and s_.offset <= @encoded.ptr and s_.offset + s_.size > @encoded.ptr } @encoded.add_export(new_label("#{s.name}_#{n}"), @encoded.ptr, true) end # decode addend if needed case reloc.type when 'NONE', 'COPY', 'GLOB_DAT', 'JMP_SLOT' # no addend else addend = reloc.addend || decode_sword end case reloc.type when 'NONE' when 'RELATIVE' # base = @segments.find_all { |s| s.type == 'LOAD' }.map { |s| s.vaddr }.min & 0xffff_f000 # compiled to be loaded at seg.vaddr target = addend if o = addr_to_off(target) if not label = @encoded.inv_export[o] label = new_label("xref_#{Expression[target]}") @encoded.add_export label, o end target = label else puts "W: Elf: relocation pointing out of mmaped space #{reloc.inspect}" if $VERBOSE end when 'GLOB_DAT', 'JMP_SLOT', '32', 'PC32', 'TLS_TPOFF', 'TLS_TPOFF32' # XXX use versionned version # lazy jmp_slot ? target = reloc_target(reloc) target = Expression[target, :-, reloc.offset] if reloc.type == 'PC32' target = Expression[target, :+, addend] if addend and addend != 0 target = Expression[target, :+, 'tlsoffset'] if reloc.type == 'TLS_TPOFF' target = Expression[:-, [target, :+, 'tlsoffset']] if reloc.type == 'TLS_TPOFF32' when 'COPY' # mark the address pointed as a copy of the relocation target if not reloc.symbol.kind_of?(Symbol) or not name = reloc.symbol.name puts "W: Elf: symbol to COPY has no name: #{reloc.inspect}" if $VERBOSE name = '' end name = new_label("copy_of_#{name}") @encoded.add_export name, @encoded.ptr target = nil else puts "W: Elf: unhandled 386 reloc #{reloc.inspect}" if $VERBOSE target = nil end Metasm::Relocation.new(Expression[target], :u32, @endianness) if target end
returns the Metasm::Relocation that should be applied for reloc self.encoded.ptr must point to the location that will be relocated (for implicit addends)
arch_decode_segments_reloc_386
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_leb(ed = @encoded) v = s = 0 loop { b = ed.read(1).unpack('C').first.to_i v |= (b & 0x7f) << s s += 7 break v if (b&0x80) == 0 } end
decode an ULEB128 (dwarf2): read bytes while high bit is set, littleendian
decode_leb
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_debug return if not @sections # assert presence of DWARF sections info = @sections.find { |sec| sec.name == '.debug_info' } abbrev = @sections.find { |sec| sec.name == '.debug_abbrev' } str = @sections.find { |sec| sec.name == '.debug_str' } return if not info or not abbrev # section -> content info = @encoded[info.offset, info.size] abbrev = @encoded[abbrev.offset, abbrev.size] str = @encoded[str.offset, str.size] if str @debug = [] while info.ptr < info.length @debug << DwarfDebug.decode(self, info, abbrev, str) end end
decodes the debugging information if available only a subset of DWARF2/3 is handled right now most info taken from http://ratonland.org/?entry=39 & libdwarf/dwarf.h
decode_debug
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_segments_dynamic(decode_relocs=true) return if not dynamic = @segments.find { |s| s.type == 'DYNAMIC' } @encoded.ptr = add_label('dynamic_tags', dynamic.vaddr) decode_tags decode_segments_tags_interpret decode_segments_symbols return if not decode_relocs decode_segments_relocs decode_segments_relocs_interpret end
decodes the ELF dynamic tags, interpret them, and decodes symbols and relocs
decode_segments_dynamic
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_segments decode_segments_dynamic decode_sections_symbols #decode_debug # too many info, decode on demand @segments.each { |s| case s.type when 'LOAD', 'INTERP' sz = s.filesz pagepad = (-(s.offset + sz)) % 4096 s.encoded = @encoded[s.offset, sz] || EncodedData.new if s.type == 'LOAD' and sz > 0 and not s.flags.include?('W') # align loaded data to the next page boundary for readonly mmap # but discard the labels/relocs etc s.encoded << @encoded[s.offset+sz, pagepad].data rescue nil s.encoded.virtsize = sz+pagepad end s.encoded.virtsize = s.memsz if s.memsz > s.encoded.virtsize end } end
decodes the dynamic segment, fills segments.encoded
decode_segments
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode_sections @symbols.clear # the NULL symbol is explicit in the symbol table decode_sections_symbols decode_sections_relocs @sections.each { |s| case s.type when 'PROGBITS', 'NOBITS' when 'TODO' # TODO end } @sections.find_all { |s| s.type == 'PROGBITS' or s.type == 'NOBITS' }.each { |s| if s.flags.include? 'ALLOC' if s.type == 'NOBITS' s.encoded = EncodedData.new '', :virtsize => s.size else s.encoded = @encoded[s.offset, s.size] || EncodedData.new s.encoded.virtsize = s.size end end } end
decodes sections, interprets symbols/relocs, fills sections.encoded
decode_sections
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def decode decode_header case @header.type when 'DYN', 'EXEC'; decode_segments when 'REL'; decode_sections when 'CORE' end end
decodes the elf header, and depending on the elf type, decode segments or sections
decode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def get_default_entrypoints ep = [] ep << @header.entry if @header.entry != 0 @symbols.each { |s| ep << s.value if s.shndx != 'UNDEF' and s.type == 'FUNC' } if @symbols ep end
returns an array including the ELF entrypoint (if not null) and the FUNC symbols addresses TODO include init/init_array
get_default_entrypoints
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause
def init_disassembler d = super() d.backtrace_maxblocks_data = 4 if d.get_section_at(0) # fixes call [constructor] => 0 d.decoded[0] = true d.function[0] = @cpu.disassembler_default_func end case @cpu.shortname when 'ia32', 'x64' old_cp = d.c_parser d.c_parser = nil d.parse_c <<EOC void *dlsym(int, char *); // has special callback // gcc's entrypoint, need pointers to reach main exe code (last callback) void __libc_start_main(void(*)(), int, int, void(*)(), void(*)()) __attribute__((noreturn)); // standard noreturn, optimized by gcc void __attribute__((noreturn)) exit(int); void _exit __attribute__((noreturn))(int); void abort(void) __attribute__((noreturn)); void __stack_chk_fail __attribute__((noreturn))(void); EOC d.function[Expression['dlsym']] = dls = @cpu.decode_c_function_prototype(d.c_parser, 'dlsym') d.function[Expression['__libc_start_main']] = @cpu.decode_c_function_prototype(d.c_parser, '__libc_start_main') d.function[Expression['exit']] = @cpu.decode_c_function_prototype(d.c_parser, 'exit') d.function[Expression['_exit']] = @cpu.decode_c_function_prototype(d.c_parser, '_exit') d.function[Expression['abort']] = @cpu.decode_c_function_prototype(d.c_parser, 'abort') d.function[Expression['__stack_chk_fail']] = @cpu.decode_c_function_prototype(d.c_parser, '__stack_chk_fail') d.c_parser = old_cp dls.btbind_callback = lambda { |dasm, bind, funcaddr, calladdr, expr, origin, maxdepth| sz = @cpu.size/8 raise 'dlsym call error' if not dasm.decoded[calladdr] if @cpu.shortname == 'x64' arg2 = :rsi else arg2 = Indirection.new(Expression[:esp, :+, 2*sz], sz, calladdr) end fnaddr = dasm.backtrace(arg2, calladdr, :include_start => true, :maxdepth => maxdepth) if fnaddr.kind_of? ::Array and fnaddr.length == 1 and s = dasm.get_section_at(fnaddr.first) and fn = s[0].read(64) and i = fn.index(?\0) and i > sz # try to avoid ordinals bind = bind.merge @cpu.register_symbols[0] => Expression[fn[0, i]] end bind } df = d.function[:default] = @cpu.disassembler_default_func df.backtrace_binding[@cpu.register_symbols[4]] = Expression[@cpu.register_symbols[4], :+, @cpu.size/8] df.btbind_callback = nil when 'mips' (d.address_binding[@header.entry] ||= {})[:$t9] ||= Expression[@header.entry] @symbols.each { |s| next if s.shndx == 'UNDEF' or s.type != 'FUNC' (d.address_binding[s.value] ||= {})[:$t9] ||= Expression[s.value] } d.function[:default] = @cpu.disassembler_default_func when 'sh4' noret = DecodedFunction.new noret.noreturn = true %w[__stack_chk_fail abort exit].each { |fn| d.function[Expression[fn]] = noret } d.function[:default] = @cpu.disassembler_default_func end d end
returns a disassembler with a special decodedfunction for dlsym, __libc_start_main, and a default function (i386 only)
init_disassembler
ruby
stephenfewer/grinder
node/lib/metasm/metasm/exe_format/elf_decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/elf_decode.rb
BSD-3-Clause