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 dump_block_header(block, &b)
b ||= lambda { |l| puts l }
xr = []
each_xref(block.address) { |x|
case x.type
when :x; xr << Expression[x.origin]
when :r, :w; xr << "#{x.type}#{x.len}:#{Expression[x.origin]}"
end
}
if not xr.empty?
b["\n// Xrefs: #{xr[0, 8].join(' ')}#{' ...' if xr.length > 8... | shows the xrefs/labels at block start | dump_block_header | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb | BSD-3-Clause |
def dump_data(addr, edata, off, &b)
b ||= lambda { |l| puts l }
if l = edata.inv_export[off] and label_alias[addr]
l_list = label_alias[addr].sort
l = l_list.pop || l
l_list.each { |ll|
b["#{ll}:"]
}
l = (l + ' ').ljust(16)
else l = ''
end
elemlen = 1 # size of each element we dump (db by d... | dumps data/labels, honours @xrefs.len if exists
dumps one line only
stops on end of edata/@decoded/@xref
returns the next offset to display
TODO array-style data access | dump_data | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble.rb | BSD-3-Clause |
def add_from(addr, type=:normal)
send "add_from_#{type}", addr
end | adds an address to the from_normal/from_subfuncret list | add_from | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def each_from
each_from_normal { |a| yield a, :normal }
each_from_subfuncret { |a| yield a, :subfuncret }
each_from_indirect { |a| yield a, :indirect }
end | iterates over every from address, yields [address, type in [:normal, :subfuncret, :indirect]] | each_from | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def each_from_samefunc(dasm, &b)
return if dasm.function[address]
@from_subfuncret.each(&b) if from_subfuncret
@from_normal.each(&b) if from_normal
end | yields all from that are from the same function | each_from_samefunc | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def each_from_otherfunc(dasm, &b)
@from_normal.each(&b) if from_normal and dasm.function[address]
@from_subfuncret.each(&b) if from_subfuncret and dasm.function[address]
@from_indirect.each(&b) if from_indirect
end | yields all from that are not in the same subfunction as this block | each_from_otherfunc | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def each_to_samefunc(dasm)
each_to { |to, type|
next if type != :normal and type != :subfuncret
to = dasm.normalize(to)
yield to if not dasm.function[to]
}
end | yields all to that are in the same subfunction as this block | each_to_samefunc | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def each_to_otherfunc(dasm)
each_to { |to, type|
to = dasm.normalize(to)
yield to if type == :indirect or dasm.function[to] or not dasm.decoded[to]
}
end | yields all to that are not in the same subfunction as this block | each_to_otherfunc | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def block_head?
self == @block.list.first
end | checks if this instruction is the first of its IBlock | block_head? | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def add_comment(addr, cmt)
@comment[addr] ||= []
@comment[addr] |= [cmt]
end | adds a commentary at the given address
comments are found in the array @comment: {addr => [list of strings]} | add_comment | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def get_edata_at(*a)
if s = get_section_at(*a)
s[0]
end
end | returns the 1st element of #get_section_at (ie the edata at a given address) or nil | get_edata_at | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def di_at(addr)
di = @decoded[addr] || @decoded[normalize(addr)] if addr
di if di.kind_of? DecodedInstruction
end | returns the DecodedInstruction at addr if it exists | di_at | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def block_at(addr)
di = di_at(addr)
di.block if di
end | returns the InstructionBlock containing the address at addr | block_at | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def function_at(addr)
f = @function[addr] || @function[normalize(addr)] if addr
f if f.kind_of? DecodedFunction
end | returns the DecodedFunction at addr if it exists | function_at | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def di_including(addr)
return if not addr
addr = normalize(addr)
if off = (0...16).find { |o| @decoded[addr-o].kind_of? DecodedInstruction and @decoded[addr-o].bin_length > o }
@decoded[addr-off]
end
end | returns the DecodedInstruction covering addr
returns one at starting nearest addr if multiple are available (overlapping instrs) | di_including | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def block_including(addr)
di = di_including(addr)
di.block if di
end | returns the InstructionBlock containing the byte at addr
returns the one of di_including() on multiple matches (overlapping instrs) | block_including | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def function_including(addr)
return if not di = di_including(addr)
function_at(find_function_start(di.address))
end | returns the DecodedFunction including this byte
return the one of find_function_start() if multiple are possible (block shared by multiple funcs) | function_including | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def each_instructionblock(&b)
ret = []
@decoded.each { |addr, di|
next if not di.kind_of? DecodedInstruction or not di.block_head?
ret << di.block
b.call(di.block) if b
}
ret
end | yields every InstructionBlock
returns the list of IBlocks | each_instructionblock | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def get_fwdemu_binding(di, pc=nil)
@cpu.get_fwdemu_binding(di, pc)
end | return a backtrace_binding reversed (akin to code emulation) (but not really) | get_fwdemu_binding | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def read_raw_data(addr, len)
if e = get_section_at(addr)
e[0].read(len)
end
end | reads len raw bytes from the mmaped address space | read_raw_data | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def decode_int(addr, type)
type = "u#{type*8}".to_sym if type.kind_of? Integer
if e = get_section_at(addr)
e[0].decode_imm(type, @cpu.endianness)
end
end | read an int of arbitrary type (:u8, :i32, ...) | decode_int | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def decode_dword(addr)
decode_int(addr, @cpu.size/8)
end | read a dword at address addr
the dword is cpu-sized (eg 32 or 64bits) | decode_dword | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def decode_strz(addr, maxsz=4096)
if e = get_section_at(addr)
str = e[0].read(maxsz).to_s
return if not len = str.index(?\0)
str[0, len]
end
end | read a zero-terminated string from addr
if no terminal 0 is found, return nil | decode_strz | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def decode_wstrz(addr, maxsz=4096)
if e = get_section_at(addr)
str = e[0].read(maxsz).to_s
return if not len = str.unpack('v*').index(0)
str[0, 2*len]
end
end | read a zero-terminated wide string from addr
return nil if no terminal found | decode_wstrz | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def disassemble_instruction(addr)
if e = get_section_at(addr)
@cpu.decode_instruction(e[0], normalize(addr))
end
end | disassembles one instruction at address
returns nil if no instruction can be decoded there
does not update any internal state of the disassembler, nor reuse the @decoded cache | disassemble_instruction | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def disassemble_from(addr, from_addr)
from_addr = from_addr.address if from_addr.kind_of? DecodedInstruction
from_addr = normalize(from_addr)
if b = block_at(from_addr)
b.add_to_normal(addr)
end
@addrs_todo << [addr, from_addr]
disassemble
end | disassemble addr as if the code flow came from from_addr | disassemble_from | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def get_label_at(addr)
e = get_edata_at(addr, false)
e.inv_export[e.ptr] if e
end | returns the label associated to an addr, or nil if none exist | get_label_at | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def set_label_at(addr, name, memcheck=true, overwrite=true)
addr = Expression[addr].reduce
e, b = get_section_at(addr, memcheck)
if not e
elsif not l = e.inv_export[e.ptr] or (!overwrite and l != name)
l = @program.new_label(name)
e.add_export l, e.ptr
@label_alias_cache = nil
@old_prog_binding[l] =... | sets the label for the specified address
returns nil if the address is not mapped
memcheck is passed to get_section_at to validate that the address is mapped
keep existing label if 'overwrite' is false | set_label_at | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def rename_label(old, new)
return new if old == new
raise "label #{new.inspect} exists" if @prog_binding[new]
each_xref(normalize(old)) { |x|
next if not di = @decoded[x.origin]
@cpu.replace_instr_arg_immediate(di.instruction, old, new)
di.comment.to_a.each { |c| c.gsub!(old, new) }
}
e = get_edata_a... | changes a label to another, updates referring instructions etc
returns the new label
the new label must be program-uniq (see @program.new_label) | rename_label | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def find_function_start(addr)
addr = addr.address if addr.kind_of? DecodedInstruction
todo = [addr]
done = []
while a = todo.pop
a = normalize(a)
di = @decoded[a]
next if done.include? a or not di.kind_of? DecodedInstruction
done << a
a = di.block.address
break a if @function[a]
l = []
d... | finds the start of a function from the address of an instruction | find_function_start | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def each_function_block(addr, incl_subfuncs = false, find_func_start = true)
addr = @function.index(addr) if addr.kind_of? DecodedFunction
addr = addr.address if addr.kind_of? DecodedInstruction
addr = find_function_start(addr) if not @function[addr] and find_func_start
todo = [addr]
ret = {}
while a = todo... | iterates over the blocks of a function, yields each func block address
returns the graph of blocks (block address => [list of samefunc blocks]) | each_function_block | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def function_graph(funcs = @function.keys + @entrypoints.to_a, ret={})
funcs = funcs.map { |f| normalize(f) }.uniq.find_all { |f| @decoded[f] }
funcs.each { |f|
next if ret[f]
ret[f] = []
each_function_block(f) { |b|
@decoded[b].block.each_to_otherfunc(self) { |sf|
ret[f] |= [sf]
}
}
}
... | returns a graph of function calls
for each func passed as arg (default: all), update the 'ret' hash
associating func => [list of direct subfuncs called] | function_graph | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def function_graph_from(addr)
addr = normalize(addr)
addr = find_function_start(addr) || addr
ret = {}
osz = ret.length-1
while ret.length != osz
osz = ret.length
function_graph(ret.values.flatten + [addr], ret)
end
ret
end | return the graph of function => subfunction list
recurses from an entrypoint | function_graph_from | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def function_graph_to(addr)
addr = normalize(addr)
addr = find_function_start(addr) || addr
full = function_graph
ret = {}
todo = [addr]
done = []
while a = todo.pop
next if done.include? a
done << a
full.each { |f, sf|
next if not sf.include? a
ret[f] ||= []
ret[f] |= [a]
todo <<... | return the graph of function => subfunction list
for which a (sub-sub)function includes addr | function_graph_to | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def section_info
if @program.respond_to? :section_info
@program.section_info
else
list = []
@sections.each { |k, v|
list << [get_label_at(k), normalize(k), v.length, nil]
}
list
end
end | returns info on sections, from @program if supported
returns an array of [name, addr, length, info] | section_info | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def addr_to_fileoff(addr)
addr = normalize(addr)
@program.addr_to_fileoff(addr)
end | transform an address into a file offset | addr_to_fileoff | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def replace_instrs(from, to, by, patch_by=false)
raise 'bad from' if not fdi = di_at(from) or not fdi.block.list.index(fdi)
raise 'bad to' if not tdi = di_at(to) or not tdi.block.list.index(tdi)
# create DecodedInstruction from Instructions in 'by' if needed
split_block(fdi.block, fdi.address)
split_block(td... | remove the decodedinstruction from..to, replace them by the new Instructions in 'by'
this updates the block list structure, old di will still be visible in @decoded, except from original block (those are deleted)
if from..to spans multiple blocks
to.block is splitted after to
all path from from are replaced by a single... | replace_instrs | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def undefine_from(addr)
return if not di_at(addr)
@comment.delete addr if @function.delete addr
split_block(addr)
addrs = []
while di = di_at(addr)
di.block.list.each { |ddi| addrs << ddi.address }
break if di.block.to_subfuncret.to_a != [] or di.block.to_normal.to_a.length != 1
addr = di.block.to_no... | undefine a sequence of decodedinstructions from an address
stops at first non-linear branch
removes @decoded, @comments, @xrefs, @addrs_done
does not update @prog_binding (does not undefine labels) | undefine_from | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def merge_blocks(b1, b2, allow_nonadjacent = false)
if b1 and not b1.kind_of? InstructionBlock
return if not b1 = block_at(b1)
end
if b2 and not b2.kind_of? InstructionBlock
return if not b2 = block_at(b2)
end
if b1 and b2 and (allow_nonadjacent or b1.list.last.next_addr == b2.address) and
b1.to_nor... | merge two instruction blocks if they form a simple chain and are adjacent
returns true if merged | merge_blocks | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def code_binding(*a)
@cpu.code_binding(self, *a)
end | computes the binding of a code sequence
just a forwarder to CPU#code_binding | code_binding | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def flatten_graph(entry, include_subfunc=true)
ret = []
entry = [entry] if not entry.kind_of? Array
todo = entry.map { |a| normalize(a) }
done = []
inv_binding = @prog_binding.invert
while addr = todo.pop
next if done.include? addr or not di_at(addr)
done << addr
b = @decoded[addr].block
ret <<... | returns an array of instructions/label that, once parsed and assembled, should
give something equivalent to the code accessible from the (list of) entrypoints given
from the @decoded dasm graph
assume all jump targets have a matching label in @prog_binding
may add inconditionnal jumps in the listing to preserve the cod... | flatten_graph | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def demangle_gcc(name)
subs = []
ret = ''
decode_tok = lambda {
name ||= ''
case name[0]
when nil
ret = nil
when ?N
name = name[1..-1]
decode_tok[]
until name[0] == ?E
break if not ret
ret << '::'
decode_tok[]
end
name = name[1..-1]
when ?I
name = name[1..... | from http://www.codesourcery.com/public/cxx-abi/abi.html | demangle_gcc | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def pattern_scan(pat, addr_start=nil, length=nil, chunksz=nil, margin=nil, &b)
chunksz ||= 4*1024*1024 # scan 4MB at a time
margin ||= 65536 # add this much bytes at each chunk to find /pat/ over chunk boundaries
pat = Regexp.new(Regexp.escape(pat)) if pat.kind_of? ::String
found = []
@sections.each { |sec_... | scans all the sections raw for a given regexp
return/yields all the addresses matching
if yield returns nil/false, do not include the addr in the final result
sections are scanned MB by MB, so this should work (slowly) on 4GB sections (eg debugger VM)
with addr_start/length, symbol-based section are skipped | pattern_scan | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def strings_scan(minlen=6, &b)
ret = []
nexto = 0
pattern_scan(/[\x20-\x7e]{#{minlen},}/m, nil, 1024) { |o|
if o - nexto > 0
next unless e = get_edata_at(o)
str = e.data[e.ptr, 1024][/[\x20-\x7e]{#{minlen},}/m]
ret << [o, str] if not b or b.call(o, str)
nexto = o + str.length
end
}
ret
... | returns/yields [addr, string] found using pattern_scan /[\x20-\x7e]/ | strings_scan | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def save_map
@prog_binding.map { |l, o|
type = di_at(o) ? 'c' : 'd' # XXX
o = o.to_s(16).rjust(8, '0') if o.kind_of? ::Integer
"#{o} #{type} #{l}"
}
end | exports the addr => symbol map (see load_map) | save_map | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def load_map(str, off=0)
str = File.read(str) rescue nil if not str.index("\n")
sks = @sections.keys.sort
seen = {}
str.each_line { |l|
case l.strip
when /^([0-9A-F]+)\s+(\w+)\s+(\w+)/i # kernel.map style
addr = $1.to_i(16)+off
set_label_at(addr, $3, false, !seen[addr])
seen[addr] = true
wh... | loads a map file (addr => symbol)
off is an optionnal offset to add to every address found (for eg rebased binaries)
understands:
standard map files (eg linux-kernel.map: <addr> <type> <name>, e.g. 'c01001ba t setup_idt')
ida map files (<sectionidx>:<sectionoffset> <name>)
arg is either the map itself or the filename o... | load_map | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def save_file(file)
tmpfile = file + '.tmp'
File.open(tmpfile, 'wb') { |fd| save_io(fd) }
File.rename tmpfile, file
end | saves the dasm state in a file | save_file | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def save_io(fd)
fd.puts 'Metasm.dasm'
if @program.filename and not @program.kind_of?(Shellcode)
t = @program.filename.to_s
fd.puts "binarypath #{t.length}", t
else
t = "#{@cpu.class.name.sub(/.*::/, '')} #{@cpu.size} #{@cpu.endianness}"
fd.puts "cpu #{t.length}", t
# XXX will be reloaded as a Shel... | saves the dasm state to an IO | save_io | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def load(str)
raise 'Not a metasm save file' if str[0, 12].chomp != 'Metasm.dasm'
off = 12
pp = Preprocessor.new
app = AsmPreprocessor.new
while off < str.length
i = str.index("\n", off) || str.length
type, len = str[off..i].chomp.split
off = i+1
data = str[off, len.to_i]
off += len.to_i
cas... | loads the dasm state from a savefile content
will yield unknown segments / binarypath notfound | load | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def rebase(newaddr)
rebase_delta(newaddr - @sections.keys.min)
end | change the base address of the loaded binary
better done early (before disassembling anything)
returns the delta | rebase | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def trace_function_register(start_addr, init_state)
function_walk(start_addr, init_state) { |args|
trace_state = args.last
case args.first
when :di
di = args[2]
update = {}
get_fwdemu_binding(di).each { |r, v|
if v.kind_of?(Expression) and v.externals.find { |e| trace_state[e] }
# XXX ... | dataflow method
walks a function, starting at addr
follows the usage of registers, computing the evolution from the value they had at start_addr
whenever an instruction references the register (or anything derived from it),
yield [di, used_register, reg_value, trace_state] where reg_value is the Expression holding the ... | trace_function_register | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def trace_update_reg_structptr(addr, reg, structname, structoff=0)
sname = soff = ctx = nil
expr_to_sname = lambda { |expr|
if not expr.kind_of?(Expression) or expr.op != :+
sname = nil
next
end
sname = expr.lexpr || expr.rexpr
soff = (expr.lexpr ? expr.rexpr : 0)
if soff.kind_of?(Expressio... | define a register as a pointer to a structure
rename all [reg+off] as [reg+struct.member] in current function
also trace assignments of pointer members | trace_update_reg_structptr | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def trace_update_reg_structptr_arg_enum(di, ind, mb, str)
if ename = mb.has_attribute_var('enum') and enum = c_parser.toplevel.struct[ename] and enum.kind_of?(C::Enum)
# handle enums: struct moo { int __attribute__((enum(bla))) fld; };
doit = lambda { |_di|
if num = _di.instruction.args.grep(Expression).fir... | found a special member of a struct, check if we can apply
bitfield/enum name to other constants in the di | trace_update_reg_structptr_arg_enum | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def toggle_expr_char(o)
return if not o.kind_of?(Renderable)
tochars = lambda { |v|
if v.kind_of?(::Integer)
a = []
vv = v.abs
a << (vv & 0xff)
vv >>= 8
while vv > 0
a << (vv & 0xff)
vv >>= 8
end
if a.all? { |b| b < 0x7f }
s = a.pack('C*').inspect.gsub("'") { '\\\'' }[1... | change Expression display mode for current object o to display integers as char constants | toggle_expr_char | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def toggle_expr_offset(o)
return if not o.kind_of? Renderable
o.each_expr { |e|
next unless e.kind_of?(Expression)
if n = @prog_binding[e.lexpr]
e.lexpr = n
elsif e.lexpr.kind_of? ::Integer and n = get_label_at(e.lexpr)
add_xref(normalize(e.lexpr), Xref.new(:addr, o.address)) if o.respond_to? :addr... | patch Expressions in current object to include label names when available
XXX should we also create labels ? | toggle_expr_offset | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def fix_noreturn(o)
each_xref(o, :x) { |a|
a = normalize(a.origin)
next if not di = di_at(a) or not di.opcode.props[:saveip]
# XXX should check if caller also becomes __noreturn
di.block.each_to_subfuncret { |to|
next if not tdi = di_at(to) or not tdi.block.from_subfuncret
tdi.block.from_subfuncre... | call this function on a function entrypoint if the function is in fact a __noreturn
will cut the to_subfuncret of callers | fix_noreturn | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def call_sites(funcaddr)
find_call_site = proc { |a|
until not di = di_at(a)
if di.opcode.props[:saveip]
cs = di.address
break
end
if di.block.from_subfuncret.to_a.first
while di.block.from_subfuncret.to_a.length == 1
a = di.block.from_subfuncret[0]
break if not di_at(a)
... | find the addresses of calls calling the address, handles thunks | call_sites | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def load_plugin(plugin_filename)
if not File.exist?(plugin_filename)
if File.exist?(plugin_filename+'.rb')
plugin_filename += '.rb'
elsif defined? Metasmdir
# try autocomplete
pf = File.join(Metasmdir, 'samples', 'dasm-plugins', plugin_filename)
if File.exist? pf
plugin_filename = pf
el... | loads a disassembler plugin script
this is simply a ruby script instance_eval() in the disassembler
the filename argument is autocompleted with '.rb' suffix, and also
searched for in the Metasmdir/samples/dasm-plugins subdirectory if not found in cwd | load_plugin | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def load_plugin_nogui(plugin_filename)
oldgui = gui
@gui = nil
load_plugin(plugin_filename)
ensure
@gui = oldgui
end | same as load_plugin, but hides the @gui attribute while loading, preventing the plugin do popup stuff
this is useful when you want to load a plugin from another plugin to enhance the plugin's functionnality
XXX this also prevents setting up kbd_callbacks etc.. | load_plugin_nogui | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def compose_bt_binding(bd1, bd2)
if bd1.kind_of? DecodedInstruction
bd1 = bd1.backtrace_binding ||= cpu.get_backtrace_binding(bd1)
end
if bd2.kind_of? DecodedInstruction
bd2 = bd2.backtrace_binding ||= cpu.get_backtrace_binding(bd2)
end
reduce = lambda { |e| Expression[Expression[e].reduce] }
bd = {... | compose two code/instruction's backtrace_binding
assumes bd1 is followed by bd2 in the code flow
eg inc edi + push edi =>
{ Ind[:esp, 4] => Expr[:edi + 1], :esp => Expr[:esp - 4], :edi => Expr[:edi + 1] }
XXX if bd1 writes to memory with a pointer that is reused in bd2, this function has to
revert the change made by bd... | compose_bt_binding | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def decode_c_struct(structname, addr)
if c_parser and edata = get_edata_at(addr)
c_parser.decode_c_struct(structname, edata.data, edata.ptr)
end
end | return a C::AllocCStruct from c_parser
TODO handle program.class::Header.to_c_struct | decode_c_struct | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def name_local_vars(addr)
if @cpu.respond_to?(:name_local_vars) and faddr = find_function_start(addr)
@function[faddr] ||= DecodedFunction.new # XXX
@cpu.name_local_vars(self, faddr)
end
end | find the function containing addr, and find & rename stack vars in it | name_local_vars | ruby | stephenfewer/grinder | node/lib/metasm/metasm/disassemble_api.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/disassemble_api.rb | BSD-3-Clause |
def assemble_sequence(seq, cpu)
# an array of edata or sub-array of ambiguous edata
# its last element is always an edata
ary = [EncodedData.new]
seq.each { |e|
case e
when Label; ary.last.add_export(e.name, ary.last.virtsize)
when Data; ary.last << e.encode(cpu.endianness)
when Align, Padding
... | encodes an Array of source (Label/Data/Instruction etc) to an EncodedData
resolves ambiguities using +encode_resolve+ | assemble_sequence | ruby | stephenfewer/grinder | node/lib/metasm/metasm/encode.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/encode.rb | BSD-3-Clause |
def assemble_resolve(ary)
startlabel = new_label('section_start')
# create two bindings where all elements are the shortest/longest possible
minbinding = {}
minoff = 0
maxbinding = {}
maxoff = 0
ary.each { |elem|
case elem
when Array
if elem.all? { |ed| ed.kind_of? EncodedData and ed.reloc.emp... | chose among multiple possible sub-EncodedData
assumes all ambiguous edata have the equivallent relocations in the same order | assemble_resolve | ruby | stephenfewer/grinder | node/lib/metasm/metasm/encode.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/encode.rb | BSD-3-Clause |
def encode_instruction(program, i)
errmsg = ''
oplist = opcode_list_byname[i.opname].to_a.find_all { |o|
o.args.length == i.args.length and
o.args.zip(i.args).all? { |f, a| parse_arg_valid?(o, f, a) }
}.map { |op|
begin
encode_instr_op(program, i, op)
rescue EncodeError
errmsg = " (#{$!.messag... | returns an EncodedData or an ary of them
uses +#parse_arg_valid?+ to find the opcode whose signature matches with the instruction
uses +encode_instr_op+ (arch-specific) | encode_instruction | ruby | stephenfewer/grinder | node/lib/metasm/metasm/encode.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/encode.rb | BSD-3-Clause |
def opcode_list_byname
@opcode_list_byname ||= opcode_list.inject({}) { |h, o| (h[o.name] ||= []) << o ; h }
end | returns a hash opcode_name => array of opcodes with this name | opcode_list_byname | ruby | stephenfewer/grinder | node/lib/metasm/metasm/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/main.rb | BSD-3-Clause |
def tune_cparser(cp)
case @size
when 64; cp.lp64
when 32; cp.ilp32
when 16; cp.ilp16
end
cp.endianness = @endianness
cp.lexer.define_weak('_STDC', 1)
# TODO gcc -dM -E - </dev/null
tune_prepro(cp.lexer)
end | sets up the C parser : standard macro definitions, type model (size of int etc) | tune_cparser | ruby | stephenfewer/grinder | node/lib/metasm/metasm/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/main.rb | BSD-3-Clause |
def dup
Instruction.new(@cpu, (@opname.dup if opname), @args.dup, (@prefix.dup if prefix), (@backtrace.dup if backtrace))
end | duplicates the argument list and prefix hash | dup | ruby | stephenfewer/grinder | node/lib/metasm/metasm/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/main.rb | BSD-3-Clause |
def initialize(cpu=nil)
@cpu = cpu
@encoded = EncodedData.new
@unique_labels_cache = {}
end | initializes self.cpu, creates an empty self.encoded | initialize | ruby | stephenfewer/grinder | node/lib/metasm/metasm/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/main.rb | BSD-3-Clause |
def label_at(edata, offset, base = '')
if not l = edata.inv_export[offset]
edata.add_export(l = new_label(base), offset)
end
l
end | return the label name corresponding to the specified offset of the encodeddata, creates it if necessary | label_at | ruby | stephenfewer/grinder | node/lib/metasm/metasm/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/main.rb | BSD-3-Clause |
def new_label(base = '')
base = base.dup.tr('^a-zA-Z0-9_', '_')
# use %x instead of to_s(16) for negative values
base = (base << '_uuid' << ('%08x' % base.object_id)).freeze if base.empty? or @unique_labels_cache[base]
@unique_labels_cache[base] = true
base
end | creates a new label, that is guaranteed to never be returned again as long as this object (ExeFormat) exists | new_label | ruby | stephenfewer/grinder | node/lib/metasm/metasm/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/main.rb | BSD-3-Clause |
def share_namespace(other)
return self if other.unique_labels_cache.equal? @unique_labels_cache
raise "share_ns #{(other.unique_labels_cache.keys & @unique_labels_cache.keys).inspect}" if !(other.unique_labels_cache.keys & @unique_labels_cache.keys).empty?
@unique_labels_cache.update other.unique_labels_cache
o... | share self.unique_labels_cache with other, checks for conflicts, returns self | share_namespace | ruby | stephenfewer/grinder | node/lib/metasm/metasm/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/main.rb | BSD-3-Clause |
def initialize(op, rexpr, lexpr)
raise ArgumentError, "Expression: invalid arg order: #{[lexpr, op, rexpr].inspect}" if not op.kind_of?(::Symbol)
@op = op
@lexpr = lexpr
@rexpr = rexpr
end | basic constructor
XXX funny args order, you should use +Expression[]+ instead | initialize | ruby | stephenfewer/grinder | node/lib/metasm/metasm/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/main.rb | BSD-3-Clause |
def hash
(@lexpr.hash + @op.hash + @rexpr.hash) & 0x7fff_ffff
end | make it useable as Hash key (see +==+) | hash | ruby | stephenfewer/grinder | node/lib/metasm/metasm/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/main.rb | BSD-3-Clause |
def bind(binding = {})
if binding[self]
return binding[self].dup
end
l = @lexpr
r = @rexpr
if l and binding[l]
raise "internal error - bound #{l.inspect}" if l.kind_of?(::Numeric)
l = binding[l]
elsif l.kind_of? ExpressionType
l = l.bind(binding)
end
if r and binding[r]
raise "internal e... | returns a new Expression with all variables found in the binding replaced with their value
does not check the binding's key class except for numeric
calls lexpr/rexpr #bind if they respond_to? it | bind | ruby | stephenfewer/grinder | node/lib/metasm/metasm/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/main.rb | BSD-3-Clause |
def bind!(binding = {})
if @lexpr.kind_of?(Expression)
@lexpr.bind!(binding)
elsif @lexpr
@lexpr = binding[@lexpr] || @lexpr
end
if @rexpr.kind_of?(Expression)
@rexpr.bind!(binding)
elsif @rexpr
@rexpr = binding[@rexpr] || @rexpr
end
self
end | bind in place (replace self.lexpr/self.rexpr with the binding value)
only recurse with Expressions (does not use respond_to?) | bind! | ruby | stephenfewer/grinder | node/lib/metasm/metasm/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/main.rb | BSD-3-Clause |
def reduce(&b)
old_rp, @@reduce_lambda = @@reduce_lambda, b if b
case e = reduce_rec
when Expression, Numeric; e
else Expression[e]
end
ensure
@@reduce_lambda = old_rp if b
end | returns a simplified copy of self
can return an +Expression+ or a +Numeric+, may return self
see +reduce_rec+ for simplifications description
if given a block, it will temporarily overwrite the global @@reduce_lambda XXX THIS IS NOT THREADSAFE | reduce | ruby | stephenfewer/grinder | node/lib/metasm/metasm/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/main.rb | BSD-3-Clause |
def reduce_rec
l = @lexpr.kind_of?(ExpressionType) ? @lexpr.reduce_rec : @lexpr
r = @rexpr.kind_of?(ExpressionType) ? @rexpr.reduce_rec : @rexpr
if @@reduce_lambda
l = @@reduce_lambda[l] || l if not @lexpr.kind_of? Expression
r = @@reduce_lambda[r] || r if not @rexpr.kind_of? Expression
end
v =
if r... | resolves logic operations (true || false, etc)
computes numeric operations (1 + 3)
expands substractions to addition of the opposite
reduces double-oppositions (-(-1) => 1)
reduces addition of 0 and unary +
canonicalize additions: put variables in the lhs, descend addition tree in the rhs => (a + (b + (c + 12)))
make f... | reduce_rec | ruby | stephenfewer/grinder | node/lib/metasm/metasm/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/main.rb | BSD-3-Clause |
def reduce_rec_composerol(e, mask)
m = Expression[['var', :sh_op, 'amt'], :|, ['var', :inv_sh_op, 'inv_amt']]
if vars = e.match(m, 'var', :sh_op, 'amt', :inv_sh_op, 'inv_amt') and vars[:sh_op] == {:>> => :<<, :<< => :>>}[vars[:inv_sh_op]] and
((vars['amt'].kind_of?(::Integer) and vars['inv_amt'].kind_of?(::In... | a check to see if an Expr is the composition of two rotations (rol eax, 4 ; rol eax, 6 => rol eax, 10)
this is a bit too ugly to stay in the main reduce_rec body. | reduce_rec_composerol | ruby | stephenfewer/grinder | node/lib/metasm/metasm/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/main.rb | BSD-3-Clause |
def match(target, *vars)
match_rec(target, vars.inject({}) { |h, v| h.update v => nil })
end | a pattern-matching method
Expression[42, :+, 28].match(Expression['any', :+, 28], 'any') => {'any' => 42}
Expression[42, :+, 28].match(Expression['any', :+, 'any'], 'any') => false
Expression[42, :+, 42].match(Expression['any', :+, 'any'], 'any') => {'any' => 42}
vars can match anything except nil | match | ruby | stephenfewer/grinder | node/lib/metasm/metasm/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/main.rb | BSD-3-Clause |
def externals
a = []
[@rexpr, @lexpr].each { |e|
case e
when ExpressionType; a.concat e.externals
when nil, ::Numeric; a
else a << e
end
}
a
end | returns the array of non-numeric members of the expression
if a variables appears 3 times, it will be present 3 times in the returned array | externals | ruby | stephenfewer/grinder | node/lib/metasm/metasm/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/main.rb | BSD-3-Clause |
def expr_externals(include_exprs=false)
a = []
[@rexpr, @lexpr].each { |e|
case e
when Expression; a.concat e.expr_externals(include_exprs)
when nil, ::Numeric; a
when ExpressionType; include_exprs ? a << e : a
else a << e
end
}
a
end | returns the externals that appears in the expression, does not walk through other ExpressionType | expr_externals | ruby | stephenfewer/grinder | node/lib/metasm/metasm/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/main.rb | BSD-3-Clause |
def fixup(edata, off, value)
str = Expression.encode_imm(value, @type, @endianness, @backtrace)
edata.fill off
edata.data[off, str.length] = str
end | fixup the encodeddata with value (reloc starts at off) | fixup | ruby | stephenfewer/grinder | node/lib/metasm/metasm/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/main.rb | BSD-3-Clause |
def initialize(data='', opts={})
if data.respond_to?(:force_encoding) and data.encoding.name != 'ASCII-8BIT' and data.length > 0
puts "Forcing edata.data.encoding = BINARY at", caller if $DEBUG
data = data.dup.force_encoding('binary')
end
@data = data
@reloc = opts[:reloc] || {}
@export = op... | opts' keys in :reloc, :export, :virtsize, defaults to empty/empty/data.length | initialize | ruby | stephenfewer/grinder | node/lib/metasm/metasm/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/main.rb | BSD-3-Clause |
def rawsize
[@data.length, *@reloc.map { |off, rel| off + rel.length } ].max
end | returns the size of raw data, that is [data.length, last relocation end].max | rawsize | ruby | stephenfewer/grinder | node/lib/metasm/metasm/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/main.rb | BSD-3-Clause |
def dup
self.class.new @data.dup, :reloc => @reloc.dup, :export => @export.dup, :virtsize => @virtsize
end | returns a copy of itself, with reloc/export duped (but not deep) | dup | ruby | stephenfewer/grinder | node/lib/metasm/metasm/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/main.rb | BSD-3-Clause |
def fixup_choice(binding, replace_target)
return if binding.empty?
@reloc.keys.each { |off|
val = @reloc[off].target.bind(binding).reduce
if val.kind_of? Integer
reloc = @reloc[off]
reloc.fixup(self, off, val)
@reloc.delete(off) # delete only if not overflowed
elsif replace_target
@reloc[of... | resolve relocations:
calculate each reloc target using Expression#bind(binding)
if numeric, replace the raw data with the encoding of this value (+fill+s preceding data if needed) and remove the reloc
if replace_target is true, the reloc target is replaced with its bound counterpart | fixup_choice | ruby | stephenfewer/grinder | node/lib/metasm/metasm/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/main.rb | BSD-3-Clause |
def binding(base = nil)
if not base
key = @export.index(@export.values.min)
return {} if not key
base = (@export[key] == 0 ? key : Expression[key, :-, @export[key]])
end
binding = {}
@export.each { |n, o| binding.update n => Expression.new(:+, o, base) }
binding
end | returns a default binding suitable for use in +fixup+
every export is expressed as base + offset
base defaults to the first export name + its offset | binding | ruby | stephenfewer/grinder | node/lib/metasm/metasm/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/main.rb | BSD-3-Clause |
def reloc_externals(interns = @export.keys)
@reloc.values.map { |r| r.target.externals }.flatten.uniq - interns
end | returns an array of variables that needs to be defined for a complete #fixup
ie the list of externals for all relocations | reloc_externals | ruby | stephenfewer/grinder | node/lib/metasm/metasm/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/main.rb | BSD-3-Clause |
def offset_of_reloc(t)
t = Expression[t]
@reloc.keys.find { |off| @reloc[off].target == t }
end | returns the offset where the relocation for target t is to be applied | offset_of_reloc | ruby | stephenfewer/grinder | node/lib/metasm/metasm/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/main.rb | BSD-3-Clause |
def fill(len = @virtsize, pattern = [0].pack('C'))
@virtsize = len if len > @virtsize
@data = @data.to_str.ljust(len, pattern) if len > @data.length
end | fill virtual space by repeating pattern (String) up to len
expand self if len is larger than self.virtsize | fill | ruby | stephenfewer/grinder | node/lib/metasm/metasm/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/main.rb | BSD-3-Clause |
def align(len, pattern=nil)
@virtsize = EncodedData.align_size(@virtsize, len)
fill(@virtsize, pattern) if pattern
end | rounds up virtsize to next multiple of len | align | ruby | stephenfewer/grinder | node/lib/metasm/metasm/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/main.rb | BSD-3-Clause |
def patch(from, to, content)
from = @export[from] || from
raise "invalid offset specification #{from}" if not from.kind_of? Integer
to = @export[to] || to
raise "invalid offset specification #{to}" if not to.kind_of? Integer
raise EncodeError, 'cannot patch data: new content too long' if to - from < content.l... | replace a portion of self
from/to may be Integers (offsets) or labels (from self.export)
content is a String or an EncodedData, which will be inserted in the specified location (padded if necessary)
raise if the string does not fit in. | patch | ruby | stephenfewer/grinder | node/lib/metasm/metasm/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/main.rb | BSD-3-Clause |
def pattern_scan(pat, chunksz=nil, margin=nil)
chunksz ||= 4*1024*1024 # scan 4MB at a time
margin ||= 65536 # add this much bytes at each chunk to find /pat/ over chunk boundaries
pat = Regexp.new(Regexp.escape(pat)) if pat.kind_of?(::String)
found = []
chunkoff = 0
while chunkoff < @data.length
... | returns a list of offsets where /pat/ can be found inside @data
scan is done per chunk of chunksz bytes, with a margin for chunk-overlapping patterns
yields each offset found, and only include it in the result if the block returns !false | pattern_scan | ruby | stephenfewer/grinder | node/lib/metasm/metasm/main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/main.rb | BSD-3-Clause |
def parse_instruction(lexer)
lexer = new_asmprepro(lexer) if lexer.kind_of? String
i = Instruction.new self
# find prefixes, break on opcode name
while tok = lexer.readtok and parse_prefix(i, tok.raw)
lexer.skip_space_eol
end
return if not tok
# allow '.' in opcode name
tok = tok.dup
while ntok ... | parses prefix/name/arguments
returns an +Instruction+ or raise a ParseError
if the parameter is a String, a custom AsmPP is built - XXX it will not be able to create labels (eg jmp 1b / jmp $) | parse_instruction | ruby | stephenfewer/grinder | node/lib/metasm/metasm/parse.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse.rb | BSD-3-Clause |
def parse_parser_instruction(lexer, instr)
raise instr, 'unknown parser instruction'
end | handles .instructions
XXX handle HLA here ? | parse_parser_instruction | ruby | stephenfewer/grinder | node/lib/metasm/metasm/parse.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse.rb | BSD-3-Clause |
def apply(macro, lexer, program)
args = Preprocessor::Macro.parse_arglist(lexer).to_a
raise @name, 'invalid argument count' if args.length != @args.length
labels = @labels.inject({}) { |h, l| h.update l => program.new_label(l) }
args = @args.zip(args).inject({}) { |h, (fa, a)| h.update fa.raw => a }
# ... | returns the array of token resulting from the application of the macro
parses arguments if needed, handles macro-local labels | apply | ruby | stephenfewer/grinder | node/lib/metasm/metasm/parse.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse.rb | BSD-3-Clause |
def parse_definition(lexer)
lexer.skip_space
while tok = lexer.nexttok and tok.type != :eol
# no preprocess argument list
raise @name, 'invalid arg definition' if not tok = lexer.readtok or tok.type != :string
@args << tok
lexer.skip_space
raise @name, 'invalid arg separator' if not tok = lexe... | parses the argument list and the body from lexer
recognize the local labels
XXX add eax,
toto db 42 ; zomg h4x | parse_definition | ruby | stephenfewer/grinder | node/lib/metasm/metasm/parse.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse.rb | BSD-3-Clause |
def readtok
tok = super()
return tok if not tok or tok.alreadyapp
# handle ; comments
if tok.type == :punct and tok.raw[0] == ?;
tok.type = :eol
begin
tok = tok.dup
while ntok = super() and ntok.type != :eol
tok.raw << ntok.raw
end
tok.raw << ntok.raw if ntok
rescue ParseError
... | reads a token, handles macros/comments/etc | readtok | ruby | stephenfewer/grinder | node/lib/metasm/metasm/parse.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse.rb | BSD-3-Clause |
def parse(text, file='<ruby>', lineno=0)
parse_init
@lexer ||= cpu.new_asmprepro('', self)
@lexer.feed text, file, lineno
lasteol = true
while not @lexer.eos?
tok = @lexer.readtok
next if not tok
case tok.type
when :space
when :eol
lasteol = true
when :punct
case tok.raw
when '.... | parses an asm source file to an array of Instruction/Data/Align/Offset/Padding | parse | ruby | stephenfewer/grinder | node/lib/metasm/metasm/parse.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse.rb | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.