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 initialize(*a)
if not a.empty?
a.zip(struct_fields.reject { |f| not f[NAME] }).each { |v, f|
v = int_to_hash(v, f[ENUM]) if f[ENUM]
v = bits_to_hash(v, f[BITS]) if f[BITS]
instance_variable_set f[NAME], v
}
end
end | set value of fields from argument list, runs int_to_hash if needed | initialize | ruby | stephenfewer/grinder | node/lib/metasm/metasm/exe_format/serialstruct.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/serialstruct.rb | BSD-3-Clause |
def struct_fields(exe=nil)
klass = self.class
klass = struct_specialized(exe) if respond_to? :struct_specialized
raise "SerialStruct: no fields for #{klass}" if $DEBUG and not @@fields[klass]
@@fields[klass]
end | returns this classes' field array
uses struct_specialized if defined (a method that returns another
SerialStruct class whose fields should be used) | struct_fields | ruby | stephenfewer/grinder | node/lib/metasm/metasm/exe_format/serialstruct.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/serialstruct.rb | BSD-3-Clause |
def decode(exe, *args)
struct_fields(exe).each { |f|
case d = f[DECODE]
when Symbol; val = exe.send(d, *args)
when Array; val = exe.send(*d)
when Proc; val = d[exe, self]
when nil; next
end
next if not f[NAME]
if h = f[ENUM]; h = h[exe, self] if h.kind_of? Proc; val = int_to_hash( val, h) end
if h = f[BITS]; h = h[exe, self] if h.kind_of? Proc; val = bits_to_hash(val, h) end
instance_variable_set(f[NAME], val)
}
end | decodes the fields from the exe | decode | ruby | stephenfewer/grinder | node/lib/metasm/metasm/exe_format/serialstruct.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/serialstruct.rb | BSD-3-Clause |
def encode(exe, *a)
set_default_values(exe, *a)
ed = EncodedData.new
struct_fields(exe).each { |f|
if not f[NAME]
ed << f[ENCODE][exe, self, nil] if f[ENCODE]
next
end
val = instance_variable_get(f[NAME])
if h = f[ENUM]; h = h[exe, self] if h.kind_of? Proc; val = int_from_hash( val, h) end
if h = f[BITS]; h = h[exe, self] if h.kind_of? Proc; val = bits_from_hash(val, h) end
case e = f[ENCODE]
when Symbol; val = exe.send(e, val)
when Array; val = exe.send(e, *val)
when Proc; val = e[exe, self, val]
when nil; next
end
ed << val
}
ed
end | sets default values, then encodes the fields, returns an EData | encode | ruby | stephenfewer/grinder | node/lib/metasm/metasm/exe_format/serialstruct.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/serialstruct.rb | BSD-3-Clause |
def to_s(a=[])
ivs = instance_variables.map { |iv| iv.to_sym }
ivs = (struct_fields.to_a.map { |f| f[NAME] }.compact & ivs) | ivs
"<#{self.class} " + ivs.map { |iv| "#{iv}=#{dump(instance_variable_get(iv), a+[self])}" }.join(' ') + ">"
end | displays the struct content, ordered by fields | to_s | ruby | stephenfewer/grinder | node/lib/metasm/metasm/exe_format/serialstruct.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/serialstruct.rb | BSD-3-Clause |
def parse_parser_instruction(instr)
case instr.raw.downcase
when '.base', '.baseaddr', '.base_addr'
# ".base_addr <expression>"
# expression should #reduce to integer
@lexer.skip_space
raise instr, 'syntax error' if not @base_addr = Expression.parse(@lexer).reduce
raise instr, 'syntax error' if tok = @lexer.nexttok and tok.type != :eol
else super(instr)
end
end | allows definition of the base address | parse_parser_instruction | ruby | stephenfewer/grinder | node/lib/metasm/metasm/exe_format/shellcode.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/shellcode.rb | BSD-3-Clause |
def assemble(*a)
parse(*a) if not a.empty?
@encoded << assemble_sequence(@source, @cpu)
@source.clear
self
end | encodes the source found in self.source
appends it to self.encoded
clears self.source
the optional parameter may contain a binding used to fixup! self.encoded
uses self.base_addr if it exists | assemble | ruby | stephenfewer/grinder | node/lib/metasm/metasm/exe_format/shellcode.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/shellcode.rb | BSD-3-Clause |
def parse_parser_instruction(instr)
case instr.raw.downcase
when '.base', '.baseaddr', '.base_addr'
# ".base_addr <expression>"
# expression should #reduce to integer
@lexer.skip_space
raise instr, 'syntax error' if not base = Expression.parse(@lexer).reduce
raise instr, 'syntax error' if tok = @lexer.nexttok and tok.type != :eol
if @cursource.equal?(@source_r)
@base_r = base
elsif @cursource.equal?(@source_w)
@base_w = base
elsif @cursource.equal?(@source_x)
@base_x = base
else raise instr, "Where am I ?"
end
when '.rdata', '.rodata'
@cursource = @source_r
when '.data', '.bss'
@cursource = @source_w
when '.text'
@cursource = @source_x
else super(instr)
end
end | allows definition of the base address | parse_parser_instruction | ruby | stephenfewer/grinder | node/lib/metasm/metasm/exe_format/shellcode_rwx.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/shellcode_rwx.rb | BSD-3-Clause |
def assemble(*a)
parse(*a) if not a.empty?
@encoded_r << assemble_sequence(@source_r, @cpu); @source_r.clear
@encoded_w << assemble_sequence(@source_w, @cpu); @source_w.clear
@encoded_x << assemble_sequence(@source_x, @cpu); @source_x.clear
self
end | encodes the source found in self.source
appends it to self.encoded
clears self.source
the optional parameter may contain a binding used to fixup! self.encoded
uses self.base_addr if it exists | assemble | ruby | stephenfewer/grinder | node/lib/metasm/metasm/exe_format/shellcode_rwx.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/shellcode_rwx.rb | BSD-3-Clause |
def fixup_check(base_r=nil, base_w=nil, base_x=nil, bd={})
if base_r.kind_of?(Hash)
bd = base_r
base_r = nil
end
@base_r = base_r if base_r
@base_w = base_w if base_w
@base_x = base_x if base_x
fixup bd
ed = EncodedData.new << @encoded_r << @encoded_w << @encoded_x
raise ["Unresolved relocations:", ed.reloc.map { |o, r| "#{r.target} " + (Backtrace.backtrace_str(r.backtrace) if r.backtrace).to_s }].join("\n") if not ed.reloc.empty?
self
end | resolve inter-section xrefs, raise if unresolved relocations remain
call this when you have assembled+allocated memory for every section | fixup_check | ruby | stephenfewer/grinder | node/lib/metasm/metasm/exe_format/shellcode_rwx.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/shellcode_rwx.rb | BSD-3-Clause |
def file_data(zip)
return @data if data
zip.encoded.ptr = @localhdr_off
LocalHeader.decode(zip)
raw = zip.encoded.read(@compressed_sz)
@data = case @compress_method
when 'NONE'
raw
when 'DEFLATE'
z = Zlib::Inflate.new(-Zlib::MAX_WBITS)
z.inflate(raw)
else
raise "Unsupported zip compress method #@compress_method"
end
end | reads the raw file data from the archive | file_data | ruby | stephenfewer/grinder | node/lib/metasm/metasm/exe_format/zip.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/zip.rb | BSD-3-Clause |
def encode_data(zip)
data = file_data(zip)
@compress_method = 'NONE' if data == ''
@crc32 = Zlib.crc32(data)
@uncompressed_sz = data.length
case compress_method
when 'NONE'
when 'DEFLATE'
data = zlib_deflate(data)
when nil
# autodetect compression method
# compress if we win more than 10% space
cdata = zlib_deflate(data)
ratio = cdata.length * 100 / data.length
if ratio < 90
@compress_method = 'DEFLATE'
data = cdata
else
@compress_method = 'NONE'
end
end
@compressed_sz = data.length
data
end | encode the data, fixup related fields | encode_data | ruby | stephenfewer/grinder | node/lib/metasm/metasm/exe_format/zip.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/zip.rb | BSD-3-Clause |
def decode_header
if not @encoded.ptr = @encoded.data.rindex([MAGIC_ENDCENTRALDIRECTORY].pack('V'))
raise "ZIP: no end of central directory record"
end
@header = EndCentralDirectory.decode(self)
end | scan and decode the 'end of central directory' header | decode_header | ruby | stephenfewer/grinder | node/lib/metasm/metasm/exe_format/zip.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/zip.rb | BSD-3-Clause |
def decode
decode_header
@encoded.ptr = @header.directory_off
while @encoded.ptr < @header.directory_off + @header.directory_sz
@files << CentralHeader.decode(self)
end
end | read the whole central directory file descriptors | decode | ruby | stephenfewer/grinder | node/lib/metasm/metasm/exe_format/zip.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/zip.rb | BSD-3-Clause |
def has_file(fname, lcase=true)
decode if @files.empty?
if lcase
@files.find { |f| f.fname == fname }
else
fname = fname.downcase
@files.find { |f| f.fname.downcase == fname }
end
end | checks if a given file name exists in the archive
returns the CentralHeader or nil
case-insensitive if lcase is false | has_file | ruby | stephenfewer/grinder | node/lib/metasm/metasm/exe_format/zip.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/zip.rb | BSD-3-Clause |
def file_data(fname, lcase=true)
if f = has_file(fname, lcase)
f.file_data(self)
end
end | returns the uncompressed raw file content from a given name
nil if name not found
case-insensitive if lcase is false | file_data | ruby | stephenfewer/grinder | node/lib/metasm/metasm/exe_format/zip.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/zip.rb | BSD-3-Clause |
def add_file(fname, data, compress=:auto)
f = CentralHeader.new
case compress
when 'NONE', false; f.compress_method = 'NONE'
when 'DEFLATE', true; f.compress_method = 'DEFLATE'
end
f.fname = fname
f.data = data
@files << f
f
end | add a new file to the zip archive | add_file | ruby | stephenfewer/grinder | node/lib/metasm/metasm/exe_format/zip.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/zip.rb | BSD-3-Clause |
def encode_entry(f, edata, central_dir)
f.localhdr_off = edata.length
# may autodetect compression method
raw = f.encode_data(self)
zipalign(f, edata)
central_dir << f.encode(self) # calls f.set_default_values
l = LocalHeader.from_central(f)
edata << l.encode(self)
edata << raw
end | add one file to the zip stream | encode_entry | ruby | stephenfewer/grinder | node/lib/metasm/metasm/exe_format/zip.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/zip.rb | BSD-3-Clause |
def zipalign(f, edata)
if f.compress_method == 'NONE' and not f.extra
o = (edata.length + f.fname.length + 2) & 3
f.extra = " "*(4-o) if o > 0
end
end | zipalign: ensure uncompressed data starts on a 4-aligned offset | zipalign | ruby | stephenfewer/grinder | node/lib/metasm/metasm/exe_format/zip.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/exe_format/zip.rb | BSD-3-Clause |
def focus_struct_byname(n, addr=@curaddr)
lst = @dasm.c_parser.toplevel.struct.keys.grep(String)
if fn = lst.find { |ln| ln == n } || lst.find { |ln| ln.downcase == n.downcase }
focus_addr(addr, @dasm.c_parser.toplevel.struct[fn])
else
lst = @dasm.c_parser.toplevel.symbol.keys.grep(String).find_all { |ln|
s = @dasm.c_parser.toplevel.symbol[ln]
s.kind_of?(C::TypeDef) and s.untypedef.kind_of?(C::Union)
}
if fn = lst.find { |ln| ln == n } || lst.find { |ln| ln.downcase == n.downcase }
focus_addr(addr, @dasm.c_parser.toplevel.symbol[fn].untypedef)
else
liststructs(n, addr)
end
end
end | display the struct or pop a list of matching struct names if ambiguous | focus_struct_byname | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/cstruct.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/cstruct.rb | BSD-3-Clause |
def update_caret
if @caret_x < @view_x or @caret_x >= @view_x + @cwidth or @caret_y < @view_y or @caret_y >= @view_y + @cheight
redraw
elsif update_hl_word(@line_text[@caret_y], @caret_x, :c)
redraw
else
invalidate_caret(@oldcaret_x-@view_x, @oldcaret_y-@view_y)
invalidate_caret(@caret_x-@view_x, @caret_y-@view_y)
end
@oldcaret_x, @oldcaret_y = @caret_x, @caret_y
end | hint that the caret moved
redraws the caret, change the hilighted word, redraw if needed | update_caret | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/cstruct.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/cstruct.rb | BSD-3-Clause |
def focus_addr(addr, struct=@curstruct)
return if @parent_widget and not addr = @parent_widget.normalize(addr)
@curaddr = addr
@caret_x = @caret_y = 0
if struct.kind_of? String
@curstruct = nil
focus_struct_byname(struct)
else
@curstruct = struct
gui_update
end
true
end | focus on addr
returns true on success | focus_addr | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/cstruct.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/cstruct.rb | BSD-3-Clause |
def initialize_widget(dasm, parent_widget)
@dasm = dasm
@parent_widget = parent_widget
@curaddr = 0
@pixel_w = @pixel_h = 2 # use a font ?
@sections = []
@section_x = []
@slave = nil # another dasmwidget whose curaddr is kept sync
@default_color_association = ColorTheme.merge :caret => :yellow, :caret_col => :darkyellow,
:background => :palegrey, :code => :red, :data => :blue
end | TODO wheel -> zoom, dragdrop -> scroll?(zoomed) | initialize_widget | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_coverage.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_coverage.rb | BSD-3-Clause |
def focus_addr(addr)
return if not addr = @parent_widget.normalize(addr) or not @dasm.get_section_at(addr)
@curaddr = addr
@slave.focus_addr(@curaddr) if @slave rescue @slave=nil
gui_update
true
end | focus on addr
returns true on success (address exists) | focus_addr | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_coverage.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_coverage.rb | BSD-3-Clause |
def update_caret
redraw if @caret_x < @view_x or @caret_x >= @view_x + @cwidth or @caret_y < @view_y or @caret_y >= @view_y + @cheight
invalidate_caret(@oldcaret_x-@view_x, @oldcaret_y-@view_y)
invalidate_caret(@caret_x-@view_x, @caret_y-@view_y)
@oldcaret_x, @oldcaret_y = @caret_x, @caret_y
redraw if update_hl_word(@line_text[@caret_y], @caret_x, :c)
end | hint that the caret moved
redraws the caret, change the hilighted word, redraw if needed | update_caret | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_decomp.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_decomp.rb | BSD-3-Clause |
def focus_addr(addr)
if @dasm.c_parser and (@dasm.c_parser.toplevel.symbol[addr] or @dasm.c_parser.toplevel.struct[addr].kind_of?(C::Union))
@curaddr = addr
@caret_x = @caret_y = 0
gui_update
return true
end
return if not addr = @parent_widget.normalize(addr)
# scan up to func start/entrypoint
todo = [addr]
done = []
ep = @dasm.entrypoints.to_a.inject({}) { |h, e| h.update @dasm.normalize(e) => true }
while addr = todo.pop
next if not di = @dasm.di_at(addr)
addr = di.block.address
next if done.include?(addr) or not @dasm.di_at(addr)
done << addr
break if @dasm.function[addr] or ep[addr]
empty = true
@dasm.decoded[addr].block.each_from_samefunc(@dasm) { |na| empty = false ; todo << na }
break if empty
end
@dasm.auto_label_at(addr, 'loc') if @dasm.get_section_at(addr) and not @dasm.get_label_at(addr)
return if not l = @dasm.get_label_at(addr)
@curaddr = l
@caret_x = @caret_y = 0
gui_update
true
end | focus on addr
returns true on success (address exists & decompiled) | focus_addr | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_decomp.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_decomp.rb | BSD-3-Clause |
def link_boxes(id1, id2)
raise "unknown index 1 #{id1}" if not b1 = @box_id[id1]
raise "unknown index 2 #{id2}" if not b2 = @box_id[id2]
b1.to |= [b2]
b2.from |= [b1]
end | link the two boxes (by id) | link_boxes | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_graph.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_graph.rb | BSD-3-Clause |
def new_box(id, content=nil)
raise "duplicate id #{id}" if @box_id[id]
b = Box.new(id, content)
@box << b
@box_id[id] = b
b
end | creates a new box, ensures id is not already taken | new_box | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_graph.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_graph.rb | BSD-3-Clause |
def boundingbox
minx = @box.map { |b| b.x }.min.to_i
miny = @box.map { |b| b.y }.min.to_i
maxx = @box.map { |b| b.x + b.w }.max.to_i
maxy = @box.map { |b| b.y + b.h }.max.to_i
[minx, miny, maxx, maxy]
end | returns the [x1, y1, x2, y2] of the rectangle encompassing all boxes | boundingbox | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_graph.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_graph.rb | BSD-3-Clause |
def group_remove_hz_margin(g, maxw=16)
if g.content.empty?
g.x = -maxw/2 if g.x < -maxw/2
g.w = maxw if g.w > maxw
return
end
margin_left = g.content.map { |b| b.x }.min - g.x
margin_right = g.x+g.w - g.content.map { |b| b.x+b.w }.max
if margin_left + margin_right > maxw
g.w -= margin_left + margin_right - maxw
dx = (maxw/2 + margin_right - margin_left)/2
g.content.each { |b| b.x += dx }
g.x = -g.w/2
end
end | if a group has no content close to its x/x+w borders, shrink it | group_remove_hz_margin | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_graph.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_graph.rb | BSD-3-Clause |
def order_graph(groups)
roots = groups.find_all { |g| g.from.empty? }
o = {} # tentative order
todo = []
loop do
roots.each { |g|
o[g] ||= 0
todo |= g.to.find_all { |gg| not o[gg] }
}
# order nodes from the tentative roots
until todo.empty?
n = todo.find { |g| g.from.all? { |gg| o[gg] } } || order_solve_cycle(todo, o)
todo.delete n
o[n] = n.from.map { |g| o[g] }.compact.max + 1
todo |= n.to.find_all { |g| not o[g] }
end
break if o.length >= groups.length
# pathological cases
if noroot = groups.find_all { |g| o[g] and g.from.find { |gg| not o[gg] } }.sort_by { |g| o[g] }.first
# we picked a root in the middle of the graph, walk up
todo |= noroot.from.find_all { |g| not o[g] }
until todo.empty?
n = todo.find { |g| g.to.all? { |gg| o[gg] } } ||
todo.sort_by { |g| g.to.map { |gg| o[gg] }.compact.min }.first
todo.delete n
o[n] = n.to.map { |g| o[g] }.compact.min - 1
todo |= n.from.find_all { |g| not o[g] }
end
# setup todo for next fwd iteration
todo |= groups.find_all { |g| not o[g] and g.from.find { |gg| o[gg] } }
else
# disjoint graph, start over from one other random node
roots << groups.find { |g| not o[g] }
end
end
if o.values.find { |rank| rank < 0 }
# did hit a pathological case, restart with found real roots
roots = groups.find_all { |g| not g.from.find { |gg| o[gg] < o[g] } }
o = {}
todo = []
roots.each { |g|
o[g] ||= 0
todo |= g.to.find_all { |gg| not o[gg] }
}
until todo.empty?
n = todo.find { |g| g.from.all? { |gg| o[gg] } } || order_solve_cycle(todo, o)
todo.delete n
o[n] = n.from.map { |g| o[g] }.compact.max + 1
todo |= n.to.find_all { |g| not o[g] }
end
# there's something screwy around here !
raise "moo" if o.length < groups.length
end
o
end | find the minimal set of nodes from which we can reach all others
this is done *before* removing cycles in the graph
returns the order (Hash group => group_order)
roots have an order of 0 | order_graph | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_graph.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_graph.rb | BSD-3-Clause |
def can_find_path(src, dst, done={})
todo = [src]
while g = todo.pop
next if done[g]
return true if g == dst
done[g] = true
todo.concat g.to
end
false
end | checks if there is a path from src to dst avoiding stuff in 'done' | can_find_path | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_graph.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_graph.rb | BSD-3-Clause |
def list_reachable(src, done={})
todo = [src]
while g = todo.pop
next if done[g]
done[g] = true
todo.concat g.to
end
done
end | returns a hash with true for every node reachable from src (included) | list_reachable | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_graph.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_graph.rb | BSD-3-Clause |
def create_layers(groups, order)
newemptybox = lambda {
b = Box.new(nil, [])
b.x = -8
b.y = -9
b.w = 16
b.h = 18
groups << b
b
}
newboxo = {}
order.each_key { |g|
og = order[g] || newboxo[g]
g.to.dup.each { |gg|
ogg = order[gg] || newboxo[gg]
if ogg > og+1
# long edge, expand
sq = [g]
(ogg - 1 - og).times { |i| sq << newemptybox[] }
sq << gg
gg.from.delete g
g.to.delete gg
newboxo[g] ||= order[g]
sq.inject { |g1, g2|
g1.to |= [g2]
g2.from |= [g1]
newboxo[g2] = newboxo[g1]+1
g2
}
raise if newboxo[gg] != ogg
end
}
}
order.update newboxo
# layers[o] = [list of nodes of order o]
layers = []
groups.each { |g|
(layers[order[g]] ||= []) << g
}
layers
end | group groups in layers of same order
create dummy groups along long edges so that no path exists between non-contiguous layers | create_layers | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_graph.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_graph.rb | BSD-3-Clause |
def layout_layers(groups)
order = order_graph(groups)
# already a tree
layers = create_layers(groups, order)
return if layers.empty?
layers.each { |l| l.each { |g| group_remove_hz_margin(g) } }
# widest layer width
maxlw = layers.map { |l| l.inject(0) { |ll, g| ll + g.w } }.max
# center the 1st layer boxes on a segment that large
x0 = -maxlw/2.0
curlw = layers[0].inject(0) { |ll, g| ll + g.w }
dx0 = (maxlw - curlw) / (2.0*layers[0].length)
layers[0].each { |g|
x0 += dx0
g.x = x0
x0 += g.w + dx0
}
# at this point, the goal is to reorder the most populated layer the best we can, and
# move other layers' boxes accordingly
layers[1..-1].each { |l|
# for each subsequent layer, reorder boxes based on their ties with the previous layer
i = 0
l.replace l.sort_by { |g|
# we know g.from is not empty (g would be in @layer[0])
medfrom = g.from.inject(0.0) { |mx, gg| mx + (gg.x + gg.w/2.0) } / g.from.length
# on ties, keep original order
[medfrom, i]
}
# now they are reordered, update their #x accordingly
# evenly distribute them in the layer
x0 = -maxlw/2.0
curlw = l.inject(0) { |ll, g| ll + g.w }
dx0 = (maxlw - curlw) / (2.0*l.length)
l.each { |g|
x0 += dx0
g.x = x0
x0 += g.w + dx0
}
}
layers[0...-1].reverse_each { |l|
# for each subsequent layer, reorder boxes based on their ties with the previous layer
i = 0
l.replace l.sort_by { |g|
if g.to.empty?
# TODO floating end
medfrom = 0
else
medfrom = g.to.inject(0.0) { |mx, gg| mx + (gg.x + gg.w/2.0) } / g.to.length
end
# on ties, keep original order
[medfrom, i]
}
# now they are reordered, update their #x accordingly
x0 = -maxlw/2.0
curlw = l.inject(0) { |ll, g| ll + g.w }
dx0 = (maxlw - curlw) / (2.0*l.length)
l.each { |g|
x0 += dx0
g.x = x0
x0 += g.w + dx0
}
}
# now the boxes are (hopefully) sorted correctly
# position them according to their ties with prev/next layer
# from the maxw layer (positionning = packed), propagate adjacent layers positions
maxidx = (0..layers.length).find { |i| l = layers[i] ; l.inject(0) { |ll, g| ll + g.w } == maxlw }
# list of layer indexes to walk
ilist = [maxidx]
ilist.concat((maxidx+1...layers.length).to_a) if maxidx < layers.length-1
ilist.concat((0..maxidx-1).to_a.reverse) if maxidx > 0
layerbox = []
ilist.each { |i|
l = layers[i]
curlw = l.inject(0) { |ll, g| ll + g.w }
# left/rightmost acceptable position for the current box w/o overflowing on the right side
minx = -maxlw/2.0
maxx = minx + (maxlw-curlw)
# replace whole layer with a box
newg = layerbox[i] = Box.new(nil, l.map { |g| g.content }.flatten)
newg.w = maxlw
newg.h = l.map { |g| g.h }.max
newg.x = -newg.w/2
newg.y = -newg.h/2
# dont care for from/to, we'll return a single box anyway
l.each { |g|
ref = (i < maxidx) ? g.to : g.from
# TODO elastic positionning around the ideal position
# (g and g+1 may have the same med, then center both on it)
if i == maxidx
nx = minx
elsif ref.empty?
nx = (minx+maxx)/2
else
# center on the outline of rx
# may want to center on rx center's center ?
rx = ref.sort_by { |gg| gg.x }
med = (rx.first.x + rx.last.x + rx.last.w - g.w) / 2.0
nx = [[med, minx].max, maxx].min
end
dx = nx+g.w/2
g.content.each { |b| b.x += dx }
minx = nx+g.w
maxx += g.w
}
}
newg = Box.new(nil, layerbox.map { |g| g.content }.flatten)
newg.w = layerbox.map { |g| g.w }.max
newg.h = layerbox.inject(0) { |h, g| h + g.h }
newg.x = -newg.w/2
newg.y = -newg.h/2
# vertical: just center each box on its layer
y0 = newg.y
layerbox.each { |lg|
lg.content.each { |b|
b.y += y0-lg.y
}
y0 += lg.h
}
groups.replace [newg]
end | take all groups, order them by order, layout as layers
always return a single group holding everything | layout_layers | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_graph.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_graph.rb | BSD-3-Clause |
def auto_arrange_init
# 'group' is an array of boxes
# all groups are centered on the origin
h = {} # { box => group }
@groups = @box.map { |b|
b.x = -b.w/2
b.y = -b.h/2
g = Box.new(nil, [b])
g.x = b.x - 8
g.y = b.y - 9
g.w = b.w + 16
g.h = b.h + 18
h[b] = g
g
}
# init group.to/from
# must always point to something that is in the 'groups' array
# no self references
# a box is in one and only one group in 'groups'
@groups.each { |g|
g.to = g.content.first.to.map { |t| h[t] if t != g }.compact
g.from = g.content.first.from.map { |f| h[f] if f != g }.compact
}
# order boxes
order = order_graph(@groups)
# remove cycles from the graph
make_tree(@groups, order)
end | place boxes in a good-looking layout
create artificial 'group' container for boxes, that will later be merged in geometrical patterns | auto_arrange_init | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_graph.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_graph.rb | BSD-3-Clause |
def auto_arrange_movebox
@groups.each { |g|
dx = (g.x + g.w/2).to_i
dy = (g.y + g.h/2).to_i
g.content.each { |b|
b.x += dx
b.y += dy
}
}
end | actually move boxes inside the groups | auto_arrange_movebox | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_graph.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_graph.rb | BSD-3-Clause |
def dump_layout(groups=@groups)
groups.map { |g| "#{groups.index(g)} -> #{g.to.map { |t| groups.index(t) }.sort.inspect}" }
end | gives a text representation of the current graph state | dump_layout | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_graph.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_graph.rb | BSD-3-Clause |
def rightclick(x, y)
if b = find_box_xy(x, y) and @zoom >= 0.90 and @zoom <= 1.1
click(x, y)
@mousemove_origin = nil
m = new_menu
setup_contextmenu(b, m)
if @parent_widget.respond_to?(:extend_contextmenu)
@parent_widget.extend_contextmenu(self, m, @caret_box[:line_address][@caret_y])
end
popupmenu(m, x, y)
end
end | if the target is a call to a subfunction, open a new window with the graph of this function (popup) | rightclick | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_graph.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_graph.rb | BSD-3-Clause |
def doubleclick_check_arrow(x, y)
return if @margin*@zoom < 2
x = view_x+x/@zoom
y = view_y+y/@zoom
sx = nil
if bt = @shown_boxes.to_a.reverse.find { |b|
y >= b.y+b.h-1 and y <= b.y+b.h-1+@margin+2 and
sx = b.x+b.w/2 - b.to.length/2 * @margin/2 and
x >= sx-@margin/2 and x <= sx+b.to.length*@margin/2 # should be margin/4, but add a little comfort margin
}
idx = (x-sx+@margin/4).to_i / (@margin/2)
idx = 0 if idx < 0
idx = bt.to.length-1 if idx >= bt.to.length
if bt.to[idx]
if @parent_widget
@caret_box, @caret_y = bt, bt[:line_address].length-1
@parent_widget.focus_addr bt.to[idx][:line_address][0]
else
focus_xy(bt.to[idx].x, bt.to[idx].y)
end
end
true
elsif bf = @shown_boxes.to_a.reverse.find { |b|
y >= b.y-@margin-2 and y <= b.y and
sx = b.x+b.w/2 - b.from.length/2 * @margin/2 and
x >= sx-@margin/2 and x <= sx+b.from.length*@margin/2
}
idx = (x-sx+@margin/4).to_i / (@margin/2)
idx = 0 if idx < 0
idx = bf.from.length-1 if idx >= bf.from.length
if bf.from[idx]
if @parent_widget
@caret_box, @caret_y = bf, bf[:line_address].length-1
@parent_widget.focus_addr bf.from[idx][:line_address][-1]
else
focus_xy(bt.from[idx].x, bt.from[idx].y)
end
end
true
end
end | check if the user clicked on the beginning/end of an arrow, if so focus on the other end | doubleclick_check_arrow | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_graph.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_graph.rb | BSD-3-Clause |
def zoom_all
minx, miny, maxx, maxy = @curcontext.boundingbox
minx -= @margin
miny -= @margin
maxx += @margin
maxy += @margin
@zoom = [width.to_f/(maxx-minx), height.to_f/(maxy-miny)].min
@zoom = 1.0 if @zoom > 1.0 or (@zoom-1.0).abs < 0.1
@curcontext.view_x = minx + (maxx-minx-width/@zoom)/2
@curcontext.view_y = miny + (maxy-miny-height/@zoom)/2
redraw
end | update the zoom & view_xy to show the whole graph in the window | zoom_all | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_graph.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_graph.rb | BSD-3-Clause |
def update_graph
@want_update_graph = false
ctx = @curcontext
boxcnt = ctx.box.length
arrcnt = ctx.box.inject(0) { |s, b| s + b.to.length + b.from.length }
ctx.clear
build_ctx(ctx)
ctx.auto_arrange_boxes
return if ctx != @curcontext
if boxcnt != ctx.box.length or arrcnt != ctx.box.inject(0) { |s, b| s + b.to.length + b.from.length }
zoom_all
elsif @caret_box # update @caret_box with a box at the same place
bx = @caret_box.x + @caret_box.w/2
by = @caret_box.y + @caret_box.h/2
@caret_box = ctx.box.find { |cb| cb.x < bx and cb.x+cb.w > bx and cb.y < by and cb.y+cb.h > by }
end
end | rebuild the code flow graph from @curcontext.roots
recalc the boxes w/h | update_graph | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_graph.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_graph.rb | BSD-3-Clause |
def build_ctx(ctx)
# graph : block -> following blocks in same function
block_rel = {}
todo = ctx.root_addrs.dup
done = [:default, Expression::Unknown]
while a = todo.shift
a = @dasm.normalize a
next if done.include? a
done << a
next if not di = @dasm.di_at(a)
if not di.block_head?
block_rel[di.block.address] = [a]
@dasm.split_block(a)
end
block_rel[a] = []
di.block.each_to_samefunc(@dasm) { |t|
t = @dasm.normalize t
next if not @dasm.di_at(t)
todo << t
block_rel[a] << t
}
block_rel[a].uniq!
end
# populate boxes
addr2box = {}
todo = ctx.root_addrs.dup
todo.delete_if { |t| not @dasm.di_at(t) } # undefined func start
done = []
while a = todo.shift
next if done.include? a
done << a
if not ctx.keep_split.to_a.include?(a) and from = block_rel.keys.find_all { |ba| block_rel[ba].include? a } and
from.length == 1 and block_rel[from.first].length == 1 and
addr2box[from.first] and lst = @dasm.decoded[from.first].block.list.last and
lst.next_addr == a and (not lst.opcode.props[:saveip] or lst.block.to_subfuncret)
box = addr2box[from.first]
else
box = ctx.new_box a, :addresses => [], :line_text_col => [], :line_address => []
end
@dasm.decoded[a].block.list.each { |di_|
box[:addresses] << di_.address
addr2box[di_.address] = box
}
todo.concat block_rel[a]
end
# link boxes
ctx.box.each { |b|
next if not di = @dasm.decoded[b[:addresses].last]
a = di.block.address
next if not block_rel[a]
block_rel[a].each { |t|
ctx.link_boxes(b.id, t)
b.direct_to = t if t == di.next_addr
}
}
# calc box dimensions/text
ctx.box.each { |b|
colstr = []
curaddr = nil
line = 0
render = lambda { |str, col| colstr << [str, col] }
nl = lambda {
b[:line_address][line] = curaddr
b[:line_text_col][line] = colstr
colstr = []
line += 1
}
b[:addresses].each { |addr|
curaddr = addr
if di = @dasm.di_at(curaddr)
if di.block_head?
# render dump_block_header, add a few colors
b_header = '' ; @dasm.dump_block_header(di.block) { |l| b_header << l ; b_header << ?\n if b_header[-1] != ?\n }
b_header.strip.each_line { |l| l.chomp!
col = :comment
col = :label if l[0, 2] != '//' and l[-1] == ?:
render[l, col]
nl[]
}
end
render["#{Expression[curaddr]} ", :address] if @show_addresses
render[di.instruction.to_s.ljust(di.comment ? 18 : 0), :instruction]
render[' ; ' + di.comment.join(' ')[0, 64], :comment] if di.comment
nl[]
else
# TODO real data display (dwords, xrefs, strings..)
if label = @dasm.get_label_at(curaddr)
render[label + ' ', :label]
end
s = @dasm.get_section_at(curaddr)
render['db '+((s and s[0].data.length > s[0].ptr) ? Expression[s[0].read(1)[0]].to_s : '?'), :text]
nl[]
end
}
b.w = b[:line_text_col].map { |strc| strc.map { |s, c| s }.join.length }.max.to_i * @font_width + 2
b.w += 1 if b.w % 2 == 0 # ensure boxes have odd width -> vertical arrows are straight
b.h = line * @font_height
}
end | create the graph objects in ctx | build_ctx | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_graph.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_graph.rb | BSD-3-Clause |
def dasm_find_roots(addr)
todo = [addr]
done = []
roots = []
default_root = nil
while a = todo.shift
next if not di = @dasm.di_at(a)
b = di.block
a = b.address
if done.include? a
default_root ||= a
next
end
done << a
newf = []
b.each_from_samefunc(@dasm) { |f| newf << f }
if newf.empty?
roots << b.address
else
todo.concat newf
end
end
roots << default_root if roots.empty? and default_root
roots
end | find a suitable array of graph roots, walking up from a block (function start/entrypoint) | dasm_find_roots | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_graph.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_graph.rb | BSD-3-Clause |
def focus_addr(addr, can_update_context=true)
return if @parent_widget and not addr = @parent_widget.normalize(addr)
return if not @dasm.di_at(addr)
# move window / change curcontext
if b = @curcontext.box.find { |b_| b_[:line_address].index(addr) }
@caret_box, @caret_x, @caret_y = b, 0, b[:line_address].rindex(addr)
@curcontext.view_x += (width/2 / @zoom - width/2)
@curcontext.view_y += (height/2 / @zoom - height/2)
@zoom = 1.0
update_caret
elsif can_update_context
@curcontext = Graph.new 'testic'
@curcontext.root_addrs = dasm_find_roots(addr)
@want_focus_addr = addr
gui_update
else
return
end
true
end | focus on addr
addr may be a dasm label, dasm address, dasm address in string form (eg "0DEADBEEFh")
addr must point to a decodedinstruction
if the addr is not found in curcontext, the code flow is walked up until a function
start or an entrypoint is found, then the graph is created from there
will call gui_update then | focus_addr | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_graph.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_graph.rb | BSD-3-Clause |
def update_caret(update_hlword = true)
return if not b = @caret_box or not @caret_x or not l = @caret_box[:line_text_col][@caret_y]
if update_hlword
l = l.map { |s, c| s }.join
@parent_widget.focus_changed_callback[] if @parent_widget and @parent_widget.focus_changed_callback and @oldcaret_y != @caret_y
update_hl_word(l, @caret_x)
end
focus_xy(b.x + @caret_x*@font_width, b.y + @caret_y*@font_height)
redraw
end | hint that the caret moved
redraw, change the hilighted word | update_caret | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_graph.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_graph.rb | BSD-3-Clause |
def chroff_to_caretx(x)
if x < x_data
[0, 0, (@show_data ? :hex : :ascii)]
elsif x < x_ascii
x -= x_data
x -= x/(4*(2*@data_size+1)+1) # remove space after each 4*@data_size
x -= x/(2*@data_size+1) # remove space after each @data_size
x = 2*@line_size-1 if x >= 2*@line_size # between hex & ascii
cx = x/(2*@data_size)*@data_size
cxd = x-2*cx
[cx, cxd, :hex]
elsif x < x_ascii+@line_size
x -= x_ascii
[x, 0, :ascii]
else
[@line_size-1, 0, (@show_ascii ? :ascii : :hex)]
end
end | converts a screen x coord (in characters) to a [@caret_x, @caret_x_data, @focus_zone] | chroff_to_caretx | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_hex.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_hex.rb | BSD-3-Clause |
def x_data
@show_address ? @x_data : 0
end | char x of start of data zone | x_data | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_hex.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_hex.rb | BSD-3-Clause |
def x_ascii
x_data + (@show_data ? @line_size*2 + @line_size/@data_size + @line_size/@data_size/4 : 0)
end | char x of start of ascii zone | x_ascii | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_hex.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_hex.rb | BSD-3-Clause |
def x_data_cur(cx = @caret_x, cxd = @caret_x_data)
x = (cx/@data_size)*@data_size
2*x + x/@data_size + x/@data_size/4 + cxd
end | current offset in data zone of caret | x_data_cur | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_hex.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_hex.rb | BSD-3-Clause |
def prompt_search_hex
text = ''
if current_address.kind_of?(::Integer)
text = Expression.encode_imm(current_address, "u#{@dasm.cpu.size}".to_sym, @dasm.cpu).unpack('H*').first
end
inputbox('hex pattern to search (hex regexp, use .. for wildcard)', :text => text) { |pat|
pat = pat.gsub(' ', '').gsub('..', '.').gsub(/[0-9a-f][0-9a-f]/i) { |o| "\\x#{o}" }
pat = Regexp.new(pat, Regexp::MULTILINE, 'n') # 'n' = force ascii-8bit
list = [['addr']] + @dasm.pattern_scan(pat).map { |a| [Expression[a]] }
listwindow("hex search #{pat}", list) { |i| @parent_widget.focus_addr i[0] }
}
end | pop a dialog, scans the sections for a hex pattern | prompt_search_hex | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_hex.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_hex.rb | BSD-3-Clause |
def prompt_search_ascii
inputbox('data pattern to search (regexp)') { |pat|
list = [['addr']] + @dasm.pattern_scan(/#{pat}/).map { |a| [Expression[a]] }
listwindow("data search #{pat}", list) { |i| @parent_widget.focus_addr i[0] }
}
end | pop a dialog, scans the sections for a regex | prompt_search_ascii | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_hex.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_hex.rb | BSD-3-Clause |
def focus_addr(addr)
return if not addr = @parent_widget.normalize(addr)
if addr.kind_of? Integer
return if @addr_min and (addr < @addr_min or addr > @addr_max)
addr &= -@line_size if @keep_aligned
@view_addr = addr if addr < @view_addr or addr >= @view_addr+(@num_lines-2)*@line_size
elsif s = @dasm.get_section_at(addr)
@view_addr = Expression[s[1]]
else return
end
@caret_x = (addr-@view_addr) % @line_size
@caret_x_data = 0
@caret_y = (addr-@view_addr) / @line_size
@focus_zone = :ascii
redraw
update_caret
true
end | focus on addr
returns true on success (address exists) | focus_addr | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_hex.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_hex.rb | BSD-3-Clause |
def current_address
@view_addr + @caret_y.to_i*@line_size + @caret_x.to_i
end | returns the address of the data under the cursor | current_address | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_hex.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_hex.rb | BSD-3-Clause |
def move_to_next
a = current_address
if not @dasm.get_section_at(a)
a = @dasm.sections.map { |k, e| k }.find_all { |k| k > a }.min
elsif @dasm.di_at(a)
while di = @dasm.di_at(a)
a = di.block.list.last.next_addr
end
else
a = @dasm.decoded.keys.find_all { |k| k > a }.min
end
@parent_widget.focus_addr(a) if a
end | if curaddr points to an instruction, find the next data, else find the next instruction | move_to_next | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_listing.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_listing.rb | BSD-3-Clause |
def update_caret
if @want_update_line_text
@want_update_caret = true
return
end
return if not @line_text[@caret_y]
@want_update_caret = false
if update_hl_word(@line_text[@caret_y], @caret_x) or @oldcaret_y != @caret_y or true
redraw
else
return if @oldcaret_x == @caret_x and @oldcaret_y == @caret_y
invalidate_caret(@oldcaret_x, @oldcaret_y, @arrow_zone_w, 0)
invalidate_caret(@caret_x, @caret_y, @arrow_zone_w, 0)
if @arrows.find { |f, t| f == @caret_y or t == @caret_y or f == @oldcaret_y or t == @oldcaret_y }
invalidate(0, 0, @arrow_zone_w, 1000000)
end
end
@parent_widget.focus_changed_callback[] if @parent_widget.focus_changed_callback and @oldcaret_y != @caret_y
@oldcaret_x = @caret_x
@oldcaret_y = @caret_y
end | hint that the caret moved
redraws the caret, change the hilighted word, redraw if needed | update_caret | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_listing.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_listing.rb | BSD-3-Clause |
def focus_addr(addr)
return if not addr = @parent_widget.normalize(addr)
if l = @line_address.index(addr) and l < @line_address.length - 4
@caret_y, @caret_x = @line_address.rindex(addr), 0
elsif addr.kind_of?(Integer) ? (addr >= @minaddr and addr <= @maxaddr) : @dasm.get_section_at(addr)
@startaddr, @caret_x, @caret_y = addr, 0, 0
adjust_startaddr
@wantaddr = @startaddr
@line_address[@caret_y] = @startaddr # so that right after focus_addr(42) ; self.current_address => 42 (coverage sync)
else
return
end
update_caret
true
end | focus on addr
addr may be a dasm label, dasm address, dasm address in string form (eg "0DEADBEEFh")
may scroll the window
returns true on success (address exists) | focus_addr | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_listing.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_listing.rb | BSD-3-Clause |
def current_address
@line_address[@caret_y] || -1
end | returns the address of the data under the cursor | current_address | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_listing.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_listing.rb | BSD-3-Clause |
def start_disassemble_bg
return if @dasm.addrs_todo.empty? and @entrypoints.all? { |ep| @dasm.decoded[ep] }
gui_update_counter = 0
run = false
Gui.idle_add {
# metasm disassembler loop
# update gui once in a while
if run or not @entrypoints.empty? or not @dasm.addrs_todo.empty?
protect { run = @dasm.disassemble_mainiter(@entrypoints) }
gui_update_counter += 1
if gui_update_counter > @gui_update_counter_max
gui_update_counter = 0
gui_update
end
true
else
gui_update
false
end
}
end | start an idle callback that will run one round of @dasm.disassemble_mainiter | start_disassemble_bg | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_main.rb | BSD-3-Clause |
def pointed_addr
hl = curview.hl_word
if hl =~ /^[0-9].*h$/ and a = hl.to_i(16) and @dasm.get_section_at(a)
return a
end
@dasm.prog_binding[hl] || curview.current_address
end | returns the address of the label under the cursor or the address of the line of the cursor | pointed_addr | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_main.rb | BSD-3-Clause |
def pointed_localvar(obj=curobj, hl=curview.hl_word)
return if not obj.kind_of?(Renderable)
localvar = nil
obj.each_expr { |e|
next unless e.kind_of?(ExpressionString)
localvar = e if e.type == :stackvar and e.str == hl
}
localvar
end | returns the ExpressionString if the currently hilighted word is a :stackvar | pointed_localvar | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_main.rb | BSD-3-Clause |
def normalize(addr)
case addr
when ::String
if @dasm.prog_binding[addr]
addr = @dasm.prog_binding[addr]
elsif (?0..?9).include? addr[0] or (?a..?f).include? addr.downcase[0]
case addr
when /^0x/i
when /h$/i; addr = '0x' + addr[0...-1]
when /[a-f]/i; addr = '0x' + addr
when /^[0-9]+$/
addr = '0x' + addr if not @dasm.get_section_at(addr.to_i) and
@dasm.get_section_at(addr.to_i(16))
end
begin
addr = Integer(addr)
rescue ::ArgumentError
return
end
else
return
end
end
addr
end | parse an address and change it to a canonical address form
supported formats: label names, or string with numerical value, incl hex (0x42 and 42h)
if the string is full decimal, a check against mapped space is done to find if it is
hexadecimal (eg 08048000) | normalize | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_main.rb | BSD-3-Clause |
def focus_addr(addr, viewidx=nil, quiet=false, *a)
viewidx ||= curview_index || :listing
return if not addr
return if viewidx == curview_index and addr == curaddr and a.empty?
oldpos = [curview_index, (curview.get_cursor_pos if curview)]
views = [viewidx, oldpos[0]]
views += [:listing, :graph, :decompile] & view_indexes
if views.compact.uniq.find { |i|
o_p = view(i).get_cursor_pos
if (view(i).focus_addr(addr, *a) rescue nil)
view(i).gui_update if i != oldpos[0]
showview(i)
true
else
view(i).set_cursor_pos o_p
a.clear
false
end
}
@pos_history << oldpos if oldpos[0] # ignore start focus_addr
@pos_history_redo.clear
session_append "@session_focus_addr = #{addr.inspect} ; @pos_history = #{@pos_history.inspect}"
true
else
messagebox "Invalid address #{addr}" if not quiet
if oldpos[0]
showview oldpos[0]
curview.set_cursor_pos oldpos[1]
end
false
end
end | display the specified address
the display first searches in the current view
if it cannot display the address, the listing, graph and decompile views are tried (in that order)
the current focus address is saved in @pos_history (see focus_addr_back/redo)
if quiet is false, a messagebox is popped if no view can display the address | focus_addr | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_main.rb | BSD-3-Clause |
def focus_addr_back(val = @pos_history.pop)
return if not val
@pos_history_redo << [curview_index, curview.get_cursor_pos]
showview val[0]
curview.set_cursor_pos val[1]
true
end | focus on the last address seen before the last focus_addr | focus_addr_back | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_main.rb | BSD-3-Clause |
def gui_update
@clones.each { |c| c.do_gui_update }
end | ask the current view to update itself and redraw (incl all cloned widgets) | gui_update | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_main.rb | BSD-3-Clause |
def do_gui_update
curview.gui_update if curview # invalidate all views ?
end | ask the current view to update itself | do_gui_update | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_main.rb | BSD-3-Clause |
def list_bghilight(title, list, a={}, &b)
prev_colorcb = bg_color_callback
hash = list[1..-1].inject({}) { |h, l| h.update Expression[l[0] || :unknown].reduce => true }
@bg_color_callback = lambda { |addr| hash[addr] ? '0f0' : prev_colorcb ? prev_colorcb[addr] : nil }
redraw
popupend = lambda { @bg_color_callback = prev_colorcb ; redraw }
listwindow(title, list, a.merge(:ondestroy => popupend), &b)
end | calls listwindow with the same argument, but also creates a new bg_color_callback
that will color lines whose address is to be found in list[0] in green
the callback is put only for the duration of the listwindow, and is not reentrant. | list_bghilight | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_main.rb | BSD-3-Clause |
def disassemble(addr)
session_append "disassemble(#{addr.inspect}) ; wait_disassemble_bg"
if di = @dasm.di_at(addr) and di.opcode.props[:saveip]
di.block.each_to_normal { |t|
t = @dasm.normalize t
next if not @dasm.decoded[t]
@dasm.function[t] ||= @dasm.function[:default] ? @dasm.function[:default].dup : DecodedFunction.new
}
di.block.add_to_subfuncret(di.next_addr)
@dasm.addrs_todo << [di.next_addr, addr, true]
elsif addr
@dasm.addrs_todo << [addr]
end
start_disassemble_bg
end | disassemble from this point
if points to a call, make it return | disassemble | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_main.rb | BSD-3-Clause |
def disassemble_fast(addr)
@dasm.disassemble_fast(addr)
session_append "dasm.disassemble_fast(#{addr.inspect})"
gui_update
end | disassemble fast from this point (don't dasm subfunctions, don't backtrace) | disassemble_fast | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_main.rb | BSD-3-Clause |
def disassemble_fast_deep(addr)
@dasm.disassemble_fast_deep(addr)
session_append "dasm.disassemble_fast_deep(#{addr.inspect})"
gui_update
end | disassemble fast & deep from this point (don't backtrace, but still dasm subfuncs) | disassemble_fast_deep | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_main.rb | BSD-3-Clause |
def toggle_data(addr)
session_append "toggle_data(#{addr.inspect})"
return if @dasm.decoded[addr] or not @dasm.get_section_at(addr)
@dasm.add_xref(addr, Xref.new(nil, nil, 1)) if not @dasm.xrefs[addr]
@dasm.each_xref(addr) { |x|
x.len = {1 => 2, 2 => 4, 4 => 8}[x.len] || 1
break
}
gui_update
end | change the format of displayed data under addr (byte, word, dword, qword)
currently this is done using a fake empty xref | toggle_data | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_main.rb | BSD-3-Clause |
def prompt_constant(di=curobj)
return if not di.kind_of?(DecodedInstruction)
di.each_expr { |e|
next unless e.kind_of?(Expression)
if (e.lexpr.kind_of?(Integer) or e.lexpr.kind_of?(ExpressionString)) and
(!curview.hl_word or curview.hl_word == Expression[e.lexpr].to_s)
v = Expression[e.lexpr].reduce
lst = []
dasm.c_constants.each { |cn, cv, fm| lst << [cn, fm] if v == cv }
if not lst.empty?
default = Expression[v].to_s
lst << [default]
listwindow("constant for #{Expression[v]}", [['name', 'enum']] + lst) { |a|
if a[0] == default
e.lexpr = v
else
e.lexpr = ExpressionString.new(v, a[0], :constant)
end
session_append "if di = dasm.di_at(#{di.address.inspect}) ; di.each_expr { |e| e.lexpr = #{e.lexpr.inspect} if e.kind_of?(Expression) and e.lexpr and Expression[e.lexpr].reduce == #{v.inspect} } ; end"
gui_update
}
end
end
if (e.rexpr.kind_of? Integer or e.rexpr.kind_of?(ExpressionString)) and
(!curview.hl_word or curview.hl_word == Expression[e.rexpr].to_s)
v = Expression[e.rexpr].reduce
lst = []
dasm.c_constants.each { |cn, cv, fm| lst << [cn, fm] if v == cv }
if not lst.empty?
default = Expression[v].to_s
lst << [default]
listwindow("constant for #{Expression[v]}", [['name', 'enum']] + lst) { |a|
if a[0] == default
e.rexpr = v
else
e.rexpr = ExpressionString.new(v, a[0], :constant)
end
session_append "if di = dasm.di_at(#{di.address.inspect}) ; di.each_expr { |e| e.rexpr = #{e.rexpr.inspect} if e.kind_of?(Expression) and e.rexpr and Expression[e.rexpr].reduce == #{v.inspect} } ; end"
gui_update
}
end
end
}
end | prompt the contant to use in place of some numeric value | prompt_constant | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_main.rb | BSD-3-Clause |
def prompt_c_struct(prompt, opts={})
inputbox(prompt, opts) { |st_name|
stars = ''
if opts[:allow_stars]
stars = st_name[/\**$/]
st_name[stars] = ''
end
# TODO propose typedef struct {} moo; too
sh = @dasm.c_parser.toplevel.struct
if sh[st_name].kind_of?(C::Union)
stn_list = [st_name]
else
stn_list = sh.keys.grep(String).find_all { |k| sh[k].kind_of?(C::Union) }
end
if name = stn_list.find { |n| n == st_name } || stn_list.find { |n| n.downcase == st_name.downcase }
# single match
yield(name+stars)
else
# try autocomplete
list = [['name']]
list += stn_list.sort.grep(/#{st_name}/i).map { |stn| [stn+stars] }
if list.length == 2
# single autocompletion
yield(list[1][0])
else
listwindow(prompt, list) { |ans|
yield(ans[0])
}
end
end
}
end | prompts for a structure name, autocompletes to known structures, and/or display a listwindow with
possible completions, yields the target structure name | prompt_c_struct | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_main.rb | BSD-3-Clause |
def prompt_struct_ptr(reg=curview.hl_word, addr=curaddr)
return if not reg or not @dasm.cpu.register_symbols.find { |rs| rs.to_s == reg.to_s }
reg = reg.to_sym
di = @dasm.di_at(addr)
return if not di.kind_of?(DecodedInstruction)
prompt_c_struct("struct pointed by #{reg}", :allow_stars => true) { |st|
# TODO store that info for the decompiler ?
@dasm.trace_update_reg_structptr(addr, reg, st)
session_append "dasm.trace_update_reg_structptr(#{addr.inspect}, #{reg.inspect}, #{st.inspect})"
gui_update
}
end | prompt the struct to use for offset in a given instr | prompt_struct_ptr | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_main.rb | BSD-3-Clause |
def focus_addr_autocomplete(v, show_alt=true)
if not focus_addr(v, nil, true)
labels = @dasm.prog_binding.map { |k, vv|
[k, Expression[@dasm.normalize(vv)]] if k.downcase.include? v.downcase
}.compact
case labels.length
when 0; focus_addr(v)
when 1; focus_addr(labels[0][0])
else
if labels.all? { |k, vv| vv == labels[0][1] }
focus_addr(labels[0][0])
elsif show_alt
labels.unshift ['name', 'addr']
listwindow("list of labels", labels) { |i| focus_addr i[1] }
end
end
end
end | same as focus_addr, also understands partial label names
if the partial part is ambiguous, show a listwindow with all matches (if show_alt) | focus_addr_autocomplete | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_main.rb | BSD-3-Clause |
def prompt_search_decoded
inputbox('text to search in instrs (regex)', :text => curview.hl_word) { |pat|
re = /#{pat}/i
found = []
@dasm.decoded.each { |k, v|
found << k if v.to_s =~ re
}
list = [['addr', 'str']] + found.map { |a| [Expression[a], @dasm.decoded[a].to_s] }
list_bghilight("search result for /#{pat}/i", list) { |i| focus_addr i[0] }
}
end | search for a regexp in #dasm.decoded.to_s | prompt_search_decoded | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_main.rb | BSD-3-Clause |
def rebase(addr=nil)
if not addr
inputbox('rebase address') { |a| rebase(Integer(a)) }
else
na = curaddr + dasm.rebase(addr)
gui_update
focus_addr na
end
end | calls the @dasm.rebase method to change the load base address of the current program | rebase | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_main.rb | BSD-3-Clause |
def rename(what=nil)
if not what and localvar = pointed_localvar
addr = curaddr
str = localvar.str.dup
inputbox("new name for #{localvar}", :text => localvar.to_s) { |v|
if v =~ /^[a-z_][a-z0-9_]*$/i
localvar.str.replace v
session_append "pointed_localvar(dasm.decoded[#{addr.inspect}], #{str.inspect}).str.replace(#{v.inspect})"
gui_update
else messagebox("invalid local var name #{v.inspect}")
end
}
return
end
what ||= pointed_addr
if @dasm.prog_binding[what] or old = @dasm.get_label_at(what)
old ||= what
inputbox("new name for #{old}", :text => old) { |v|
if v == ''
@dasm.del_label_at(what)
session_append "dasm.del_label_at(#{what.inspect})"
else
@dasm.rename_label(old, v)
session_append "dasm.rename_label(#{old.inspect}, #{v.inspect})"
end
gui_update
}
else
inputbox("label name for #{Expression[what]}", :text => Expression[what]) { |v|
next if v == ''
@dasm.set_label_at(what, v)
@dasm.split_block(what)
session_append "dasm.set_label_at(#{what.inspect}, #{v.inspect}) ; dasm.split_block(#{what.inspect})"
gui_update
}
end
end | prompts for a new name for what is under the cursor (or the current address) | rename | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_main.rb | BSD-3-Clause |
def playpause_dasm
@dasm_pause ||= []
if @dasm_pause.empty? and @dasm.addrs_todo.empty?
true
elsif @dasm_pause.empty?
@dasm_pause = @dasm.addrs_todo.dup
@dasm.addrs_todo.replace @dasm_pause.find_all { |a, *b| @dasm.decoded[@dasm.normalize(a)] }
@dasm_pause -= @dasm.addrs_todo
puts "dasm paused (#{@dasm_pause.length})"
else
@dasm.addrs_todo.concat @dasm_pause
@dasm_pause.clear
puts "dasm restarted (#{@dasm.addrs_todo.length})"
start_disassemble_bg
true
end
end | pause/play disassembler
returns true if playing
this empties @dasm.addrs_todo, the dasm may still continue to work if this msg is
handled during an instr decoding/backtrace (the backtrace may generate new addrs_todo)
addresses in addrs_todo pointing to existing decoded instructions are left to create a prettier graph | playpause_dasm | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_main.rb | BSD-3-Clause |
def toggle_expr_offset(o)
@dasm.toggle_expr_offset(o)
session_append "dasm.toggle_expr_offset(dasm.decoded[#{curaddr.inspect}])"
gui_update
end | toggle <401000h> vs <'sub_fancyname'> in the current instr display | toggle_expr_offset | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_main.rb | BSD-3-Clause |
def toggle_expr_str(o)
@dasm.toggle_expr_str(o)
session_append "dasm.toggle_expr_str(dasm.decoded[#{curaddr.inspect}])"
gui_update
end | toggle constant/localvar names with raw value | toggle_expr_str | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_main.rb | BSD-3-Clause |
def session_append(str)
return if not session_file
# convert decimal addrs to hex
str = str.sub(/(\(|\[|= )(\d\d\d\d\d\d+)/) { $1 + ('0x%x' % $2.to_i) }
@session_lastsz_setfocus ||= nil # prevent warning
if str =~ /^@session_focus_addr = / and @session_lastsz_setfocus
# overwrite previous set_focus
File.truncate(session_file, @session_lastsz_setfocus) if File.size(session_file) == @session_lastsz
is_setfocus = true
end
File.open(session_file, 'a') { |fd| fd.puts str }
@session_lastsz = File.size(session_file)
@session_lastsz_setfocus = @session_lastsz if not is_setfocus
rescue
@session_file = nil
puts "Failed to save session, disabling (#{$!.class} #{$!})"
end | append one line to the session file
converts addresses to hex, deletes consecutive set_focus lines | session_append | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_main.rb | BSD-3-Clause |
def clone_window(*focus)
return if not popup = DasmWindow.new
popup.display(@dasm, @entrypoints)
w = popup.dasm_widget
w.bg_color_callback = @bg_color_callback if bg_color_callback
w.keyboard_callback = @keyboard_callback
w.keyboard_callback_ctrl = @keyboard_callback_ctrl
w.clones = @clones.concat w.clones
w.focus_addr(*focus)
popup
end | creates a new dasm window with the same disassembler object, focus it on addr#win | clone_window | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_main.rb | BSD-3-Clause |
def display(dasm, ep=[])
@dasm_widget.terminate if @dasm_widget
ep = [ep] if not ep.kind_of? Array
@dasm_widget = DisasmWidget.new(dasm, ep)
self.widget = @dasm_widget
@dasm_widget.focus_addr(ep.first) if ep.first
@dasm_widget
end | sets up a DisasmWidget as main widget of the window, replaces the current if it exists
returns the widget | display | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_main.rb | BSD-3-Clause |
def widget(idx=nil)
idx && @dasm_widget ? @dasm_widget.view(idx) : @dasm_widget
end | returns the specified widget from the @dasm_widget (idx in :hex, :listing, :graph etc) | widget | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_main.rb | BSD-3-Clause |
def promptsave
return if not @dasm_widget
if @savefile ||= nil
@dasm_widget.dasm.save_file @savefile
return
end
openfile('chose save file') { |file|
@savefile = file
@dasm_widget.dasm.save_file(file)
}
end | reuse last @savefile to save dasm, prompt for file if undefined | promptsave | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_main.rb | BSD-3-Clause |
def promptsaveas
@savefile = nil
promptsave
end | same as promptsave, but always prompt | promptsaveas | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_main.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_main.rb | BSD-3-Clause |
def update_caret
if update_hl_word(@line_text[@caret_y], @caret_x) or @caret_y != @oldcaret_y
redraw
elsif @oldcaret_x != @caret_x
invalidate_caret(@oldcaret_x, @oldcaret_y)
invalidate_caret(@caret_x, @caret_y)
end
@oldcaret_x, @oldcaret_y = @caret_x, @caret_y
end | hint that the caret moved
redraws the caret, change the hilighted word, redraw if needed | update_caret | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_opcodes.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_opcodes.rb | BSD-3-Clause |
def focus_addr(addr)
return if not addr = @parent_widget.normalize(addr)
if l = @line_address.index(addr) and l < @line_address.keys.max - 4
@caret_y, @caret_x = @line_address.keys.find_all { |k| @line_address[k] == addr }.max, 0
elsif @dasm.get_section_at(addr)
@view_addr, @caret_x, @caret_y = addr, 0, 0
redraw
else
return
end
update_caret
true
end | focus on addr
returns true on success (address exists) | focus_addr | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/dasm_opcodes.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/dasm_opcodes.rb | BSD-3-Clause |
def keypress(key)
case key
when :left
if @caret_x > 0
@caret_x -= 1
update_caret
end
when :right
if @caret_x < @register_size[@registers[@caret_reg]]-1
@caret_x += 1
update_caret
end
when :up
if @caret_reg > 0
@caret_reg -= 1
else
@caret_reg = @[email protected]
end
@caret_x = 0
update_caret
when :down
if @caret_reg < @[email protected]
@caret_reg += 1
else
@caret_reg = 0
end
@caret_x = 0
update_caret
when :home
@caret_x = 0
update_caret
when :end
@caret_x = @register_size[@registers[@caret_reg]]-1
update_caret
when :tab
if @caret_reg < @[email protected]
@caret_reg += 1
else
@caret_reg = 0
end
@caret_x = 0
update_caret
when :backspace
# TODO
when :enter
commit_writes
redraw
when :esc
@write_pending.clear
redraw
when ?\x20..?\x7e
if ?a.kind_of?(String)
v = key.ord
case key
when ?\x20; v = nil # keep current value
when ?0..?9; v -= ?0.ord
when ?a..?f; v -= ?a.ord-10
when ?A..?F; v -= ?A.ord-10
else return false
end
else
case v = key
when ?\x20; v = nil
when ?0..?9; v -= ?0
when ?a..?f; v -= ?a-10
when ?A..?F; v -= ?A-10
else return false
end
end
reg = @registers[@caret_reg] || @flags[@[email protected]]
rsz = @register_size[reg]
if v and rsz != 1
oo = 4*(rsz-@caret_x-1)
ov = @write_pending[reg] || @reg_cache[reg]
ov &= ~(0xf << oo)
ov |= v << oo
@write_pending[reg] = ov
elsif v and (v == 0 or v == 1) # TODO change z flag by typing 'z' or 'Z'
@write_pending[reg] = v
rsz = 1
end
if rsz == 1
@caret_reg += 1
@caret_reg = @registers.length if @caret_reg >= @registers.length + @flags.length
elsif @caret_x < rsz-1
@caret_x += 1
else
@caret_x = 0
end
redraw
else return false
end
true
end | keyboard binding
basic navigation (arrows, pgup etc) | keypress | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/debug.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/debug.rb | BSD-3-Clause |
def rightclick(x, y)
y -= height % @font_height
y = y.to_i / @font_height
hc = height / @font_height
x /= @font_width
if y >= hc - 2
keypress_ctrl ?v
else
txt = @log.reverse[@log_offset + hc - y - 3].to_s
word = txt[0...x].to_s[/\w*$/] << txt[x..-1].to_s[/^\w*/]
clipboard_copy(word)
end
end | copy/paste word under cursor (paste when on last line) | rightclick | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/debug.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/debug.rb | BSD-3-Clause |
def cmd_dd(addr, dlen=nil, len=nil)
if addr.kind_of? String
s = addr.strip
addr = solve_expr!(s) || @parent_widget.mem.curaddr
if not s.empty?
s = s[1..-1] if s[0] == ?,
len ||= solve_expr(s)
end
end
if len
while len > 0
data = @dbg.memory[addr, [len, 16].min]
le = (@dbg.cpu.endianness == :little)
data = '' if @dbg.memory.page_invalid?(addr)
case dlen
when nil; add_log "#{Expression[addr]} #{data.unpack('C*').map { |c| '%02X' % c }.join(' ').ljust(2*16+15)} #{data.tr("^\x20-\x7e", '.')}"
when 1; add_log "#{Expression[addr]} #{data.unpack('C*').map { |c| '%02X' % c }.join(' ')}"
when 2; add_log "#{Expression[addr]} #{data.unpack(le ? 'v*' : 'n*').map { |c| '%04X' % c }.join(' ')}"
when 4; add_log "#{Expression[addr]} #{data.unpack(le ? 'V*' : 'N*').map { |c| '%08X' % c }.join(' ')}"
when 8; add_log "#{Expression[addr]} #{data.unpack('Q*').map { |c| '%016X' % c }.join(' ')}"
end
addr += 16
len -= 16
end
else
if dlen
@parent_widget.mem.view(:hex).data_size = dlen
@parent_widget.mem.view(:hex).resized
@parent_widget.mem.showview(:hex)
end
@parent_widget.mem.focus_addr(solve_expr(addr))
@parent_widget.mem.gui_update
end
end | update the data window, or dump data to console if len given | cmd_dd | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/debug.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/debug.rb | BSD-3-Clause |
def messagebox(*a)
MessageBox.new(toplevel, *a)
end | shows a message box (non-modal)
args: message, title/optionhash | messagebox | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/gtk.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/gtk.rb | BSD-3-Clause |
def inputbox(*a)
InputBox.new(toplevel, *a) { |*ya| protect { yield(*ya) } }
end | asks for user input, yields the result (unless 'cancel' clicked)
args: prompt, :text => default text, :title => title | inputbox | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/gtk.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/gtk.rb | BSD-3-Clause |
def openfile(*a)
OpenFile.new(toplevel, *a) { |*ya| protect { yield(*ya) } }
end | asks to chose a file to open, yields filename
args: title, :path => path | openfile | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/gtk.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/gtk.rb | BSD-3-Clause |
def savefile(*a)
SaveFile.new(toplevel, *a) { |*ya| protect { yield(*ya) } }
end | same as openfile, but for writing a (new) file | savefile | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/gtk.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/gtk.rb | BSD-3-Clause |
def listwindow(*a)
ListWindow.new(toplevel, *a) { |*ya| protect { yield(*ya) } }
end | displays a popup showing a table, yields the selected row
args: title, [[col0 title, col1 title...], [col0 val0, col1 val0...], [val1], [val2]...] | listwindow | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/gtk.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/gtk.rb | BSD-3-Clause |
def set_font(descr)
@layout.font_description = Pango::FontDescription.new(descr)
@layout.text = 'x'
@font_width, @font_height = @layout.pixel_size
gui_update
end | change the font of the widget
arg is a Gtk Fontdescription string (eg 'courier 10') | set_font | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/gtk.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/gtk.rb | BSD-3-Clause |
def set_color_association(hash)
if not realized?
sid = signal_connect('realize') {
signal_handler_disconnect(sid)
set_color_association(hash)
}
else
hord = Hash.new { |h, k| h[k] = (hash[k] ? h[hash[k]] + 1 : 0) }
hash.sort_by { |k, v| hord[k] }.each { |k, v| @color[k] = color(v) }
modify_bg Gtk::STATE_NORMAL, @color[:background]
gui_update
end
end | change the color association
arg is a hash function symbol => color symbol
check #initialize/sig('realize') for initial function/color list
if called before the widget is first displayed onscreen, will register a hook to re-call itself later | set_color_association | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/gtk.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/gtk.rb | BSD-3-Clause |
def update_hl_word(line, offset, mode=:asm)
return if not line
word = line[0...offset].to_s[/\w*$/] << line[offset..-1].to_s[/^\w*/]
word = nil if word == ''
if @hl_word != word
if word
if mode == :asm and defined?(@dasm) and @dasm
re = @dasm.gui_hilight_word_regexp(word)
else
re = Regexp.escape word
end
@hl_word_re = /^(.*?)(\b(?:#{re})\b)/
end
@hl_word = word
end
end | update @hl_word from a line & offset, return nil if unchanged | update_hl_word | ruby | stephenfewer/grinder | node/lib/metasm/metasm/gui/gtk.rb | https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/gui/gtk.rb | BSD-3-Clause |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.