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 clip_lines(ymin, ymax) ymin, ymax = ymax, ymin if ymin > ymax @lines.each { |la| la.delete_if { |l| l.y < ymin or l.y > ymax } } @lines.delete_if { |la| la.empty? } self end
remove lines not within ymin and ymax
clip_lines
ruby
stephenfewer/grinder
node/lib/metasm/misc/pdfparse.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/misc/pdfparse.rb
BSD-3-Clause
def parse(str) @lines = [] curx = cury = 0 fontx = fonty = 12 charspc = wordspc = 0 stack = [] linelead = -12 ps2tok(str) { |t| case t when Float, String; print "#{t} " else puts t end if $VERBOSE case t when Float, String; stack << t # be postfix ! when :BT; intext = true ; @lines << [] # begin text when :ET; intext = false # end text when :Tj, :TJ # print line @lines.last << Line.new(stack.pop, curx, cury, fontx, fonty, charspc, wordspc) when :Td, :TD # move cursor linelead = stack.last*fonty if t == :TD cury += stack.pop*fonty curx += stack.pop*fontx when :'T*' # new line cury += linelead when :Tc # character spacing # RHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA #3.17731 Tc 9 0 0 9 343.41 653.84998 Tm #[(3T)3202(O)729(R)3179(A)-3689(S)3178(I)]TJ # => 3 TO RA SI charspc = stack.pop when :Tw wordspc = stack.pop when :Tm # set transform matrix (scale, rotate, translate) params = Array.new(6) { stack.pop }.reverse next if params[0] == 0.0 # rotated text fontx, _, _, fonty, curx, cury = params end } end
parse a postscript string to an array of paragraph (itself an array of lines) handles text strings and basic cursor position updates
parse
ruby
stephenfewer/grinder
node/lib/metasm/misc/pdfparse.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/misc/pdfparse.rb
BSD-3-Clause
def ps2tok(str) loop do case str when ''; break when /\A-?\d+(?:\.\d+)?/; tok = $&.to_f when /\A\((?:\\.|[^\\)])*\)/; tok = $& when /\A\[(?:[^\](]*\((?:\\.|[^\\)])*\))*[^\]]*\]/; tok = $& when /\A[a-zA-Z0-9_*]+/; tok = $&.to_sym rescue nil when /\A\S+/, /\A\s+/ end str = str[$&.length..-1] yield tok if tok end end
yields PS tokens: floats, commands, and strings
ps2tok
ruby
stephenfewer/grinder
node/lib/metasm/misc/pdfparse.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/misc/pdfparse.rb
BSD-3-Clause
def to_s mx = @lines.flatten.map { |l| l.x }.min py = nil strs = [''] @lines.sort_by { |la| -la.map { |l| l.y }.max.to_i }.each { |la| y = la.map { |l| l.y }.max strs.concat ['']*((py-y)/12) if py and py > y la.sort_by { |l| [-l.y, l.x] }.each { |l| # 9 == base font size strs << '' if y > l.y+l.fonty*0.9 or strs.last.length*1000/Line::CHARWIDTH/9 > l.x-mx strs[-1] = strs.last.ljust((l.x-mx)*1000/Line::CHARWIDTH/9-1) << ' ' << l.str y = l.y } py = y if not py or py > y } strs.join("\n") end
renders the lines, according to the layout (almost ;) )
to_s
ruby
stephenfewer/grinder
node/lib/metasm/misc/pdfparse.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/misc/pdfparse.rb
BSD-3-Clause
def make_alias(newop, newargs, oldop, oldargs) raise "unknown alias #{newop} => #{oldop}" if not op = $opcodes.reverse.find { |op_| op_[0] == oldop } op2 = op.dup op2[0] = newop oldargs.each_with_index { |oa, i| # XXX bcctr 4, 6 -> bcctr 4, 6, 0 => not the work if oa =~ /^[0-9]+$/ or oa =~ /^0x[0-9a-f]+$/i fld = op[2][i] op2[1] |= Integer(oa) << $field_shift[fld] end } puts "#\talias #{newop} #{newargs.join(', ')} -> #{oldop} #{oldargs.join(', ')}".downcase end
handle instruction aliases NOT WORKING should be implemented in the parser/displayer instead of opcode list manual work needed for eg conditionnal jumps
make_alias
ruby
stephenfewer/grinder
node/lib/metasm/misc/ppc_pdf2oplist.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/misc/ppc_pdf2oplist.rb
BSD-3-Clause
def create_funcs(dasm) f = {} dasm.entrypoints.to_a.each { |ep| dasm.function[ep] ||= DecodedFunction.new } dasm.function.each_key { |a| next if not dasm.di_at(a) f[a] = create_func(dasm, a) Gui.main_iter } f end
func addr => { funcblock => list of funcblock to }
create_funcs
ruby
stephenfewer/grinder
node/lib/metasm/samples/bindiff.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/bindiff.rb
BSD-3-Clause
def match_func(a1, a2, do_colorize=true, verb=true) f1 = func1[a1] f2 = func2[a2] raise "dasm1 has no function at #{Expression[a1]}" if not f1 raise "dasm2 has no function at #{Expression[a2]}" if not f2 todo1 = [a1] todo2 = [a2] done1 = [] done2 = [] score = 0.0 # average of the (local best) match_block scores score += 0.01 if @dasm1.get_label_at(a1) != @dasm2.get_label_at(a2) # for thunks score_div = [f1.length, f2.length].max.to_f # XXX this is stupid and only good for perfect matches (and even then it may fail) # TODO handle block split etc (eg instr-level diff VS block-level) while a1 = todo1.shift next if done1.include? a1 t = todo2.map { |a| [a, match_block(@dasm1.decoded[a1].block, @dasm2.decoded[a].block)] } a2 = t.sort_by { |a, s| s }.first if not a2 break end score += a2[1] / score_div a2 = a2[0] done1 << a1 done2 << a2 todo1.concat f1[a1] todo2.concat f2[a2] todo2 -= done2 colorize_blocks(a1, a2) if do_colorize end score += (f1.length - f2.length).abs * 3 / score_div # block count difference -> +3 per block score end
return how much match a func in d1 and a func in d2
match_func
ruby
stephenfewer/grinder
node/lib/metasm/samples/bindiff.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/bindiff.rb
BSD-3-Clause
def sync1 c2 = curfunc2 if a1 = match_funcs.find_key { |k| match_funcs[k][0] == c2 } @dasm1.gui.focus_addr(a1) end end
show in window 1 the match of the function found in win 2
sync1
ruby
stephenfewer/grinder
node/lib/metasm/samples/bindiff.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/bindiff.rb
BSD-3-Clause
def initialize(dbg) if not dbg.kind_of? Metasm::Debugger process = Metasm::OS.current.find_process(dbg) raise 'no such process' if not process dbg = process.debugger end @dbg = dbg begin setup.each { |h| setup_hook(h) } init_prerun if respond_to?(:init_prerun) # allow subclass to do stuff before main loop @dbg.run_forever rescue Interrupt @dbg.detach #rescue nil end end
initialized from a Debugger or a process description that will be debugged sets the hooks up, then run_forever
initialize
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-apihook.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-apihook.rb
BSD-3-Clause
def read_arglist nr = @nargs args = [] if (@cur_abi == :fastcall or @cur_abi == :thiscall) and nr > 0 args << @dbg.get_reg_value(:ecx) nr -= 1 end if @cur_abi == :fastcall and nr > 0 args << @dbg.get_reg_value(:edx) nr -= 1 end nr.times { |i| args << @dbg.func_arg(i) } args end
retrieve the arglist at func entry, from @nargs & @cur_abi
read_arglist
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-apihook.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-apihook.rb
BSD-3-Clause
def patch_arg(nr, value) case @cur_abi when :fastcall case nr when 0 @dbg.set_reg_value(:ecx, value) return when 1 @dbg.set_reg_value(:edx, value) return else nr -= 2 end when :thiscall case nr when 0 @dbg.set_reg_value(:ecx, value) return else nr -= 1 end end @dbg.func_arg_set(nr, value) end
patch the value of an argument only valid in pre_hook nr starts at 0
patch_arg
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-apihook.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-apihook.rb
BSD-3-Clause
def patch_ret(val) if @ret_longlong @dbg.set_reg_value(:edx, (val >> 32) & 0xffffffff) val &= 0xffffffff end @dbg.func_retval_set(val) end
patch the function return value only valid post_hook
patch_ret
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-apihook.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-apihook.rb
BSD-3-Clause
def finish(retval) patch_ret(retval) @dbg.ip = @dbg.func_retaddr case @cur_abi when :fastcall @dbg[:esp] += 4*(@nargs-2) if @nargs > 2 when :thiscall @dbg[:esp] += 4*(@nargs-1) if @nargs > 1 when :stdcall @dbg[:esp] += 4*@nargs end @dbg.sp += @dbg.cpu.size/8 throw :finish end
skip the function call only valid in pre_hook
finish
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-apihook.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-apihook.rb
BSD-3-Clause
def initialize(file, oep, iat, dumpfile) @dumpfile = dumpfile @dumpfile ||= file.chomp('.exe') + '.dump.exe' puts 'disassembling UPX loader...' pe = PE.decode_file(file) @baseaddr = pe.optheader.image_base @oep = oep @oep -= @baseaddr if @oep and @oep > @baseaddr # va => rva @oep ||= find_oep(pe) raise 'cant find oep...' if not @oep puts "oep found at #{Expression[@oep]}" if not oep @iat = iat @iat -= @baseaddr if @iat and @iat > @baseaddr @dbg = OS.current.create_process(file).debugger puts 'running...' debugloop end
loads the file find the oep by disassembling run it until the oep dump the memory image
initialize
ruby
stephenfewer/grinder
node/lib/metasm/samples/dump_upx.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dump_upx.rb
BSD-3-Clause
def find_oep(pe) dasm = pe.disassemble_fast_deep 'entrypoint' return if not jmp = dasm.decoded.find { |addr, di| # check only once per basic block next if not di.block_head? b = di.block # our target has only one follower next if b.to_subfuncret.to_a.length != 0 or b.to_normal.to_a.length != 1 to = b.to_normal.first # ignore jump to unmmaped address next if not s = dasm.get_section_at(to) # ignore jump to same section next if dasm.get_section_at(di.address) == s # gotcha ! true } # now jmp is a couple [addr, di], we extract and normalize the oep from there dasm.normalize(jmp[1].block.to_normal.first) end
disassemble the upx stub to find a cross-section jump (to the real entrypoint)
find_oep
ruby
stephenfewer/grinder
node/lib/metasm/samples/dump_upx.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dump_upx.rb
BSD-3-Clause
def set_method_binary(klass, methodname, raw, nargs=nil) nargs ||= klass.instance_method(methodname).arity if raw.kind_of? EncodedData baseaddr = str_ptr(raw.data) bd = raw.binding(baseaddr) raw.reloc_externals.uniq.each { |ext| bd[ext] = sym_addr(0, ext) or raise "unknown symbol #{ext}" } raw.fixup(bd) raw = raw.data end (@@prevent_gc ||= {})[[klass, methodname]] = raw set_class_method_raw(klass, methodname.to_s, raw, nargs) end
sets up rawopcodes as the method implementation for class klass rawopcodes must implement the expected ABI or things will break horribly this method is VERY UNSAFE, and breaks everything put in place by the ruby interpreter use with EXTREME CAUTION nargs arglist -2 self, arg_ary -1 argc, VALUE*argv, self >=0 self, arg0, arg1..
set_method_binary
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def set_singleton_method_binary(obj, *a) set_method_binary((class << obj ; self ; end), *a) end
same as load_binary_method but with an object and not a class
set_singleton_method_binary
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def compile(ast, klass, meth, singleton=false) return if not ast # TODO handle arbitrary block/yield constructs # TODO analyse to find/optimize numeric locals that never need a ruby VALUE (ie native int vs INT2FIX) # TODO detect block/closure exported out of the func & abort compilation @klass = klass @meth = meth @meth_singleton = singleton mname = escape_varname("m_#{@klass}#{singleton ? '.' : '#'}#{@meth}".gsub('::', '_')) @cp.parse "static void #{mname}(VALUE self) { }" @cur_cfunc = @cp.toplevel.symbol[mname] @cur_cfunc.type.type = value # return type = VALUE, w/o 'missing return statement' warning @scope = @cur_cfunc.initializer case ast[0] when :ivar # attr_reader ret = fcall('rb_ivar_get', rb_self, rb_intern(ast[1])) when :attrset # attr_writer compile_args(@cur_cfunc, [nil, 1]) ret = fcall('rb_ivar_set', rb_self, rb_intern(ast[1]), local(2)) when :scope # standard ruby function @cref = ast[1][:cref] if ast[2] and ast[2][0] == :block and ast[2][1] and ast[2][1][0] == :args compile_args(@cur_cfunc, ast[2][1]) end want_value = true if meth.to_s == 'initialize' and not singleton want_value = false end ret = ast_to_c(ast[2], @scope, want_value) ret = rb_nil if not want_value #when :cfunc # native ruby extension else raise "unhandled function ast #{ast.inspect}" end @scope.statements << C::Return.new(ret) mname end
convert a ruby AST to a new C function returns the new function name
compile
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def method_arity(name=@meth) @meth_singleton ? @klass.method(name).arity : @klass.instance_method(name).arity end
return the arity of method 'name' on self
method_arity
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def resolve_const_owner(constname) @cref.find { |cr| cr.constants.map { |c| c.to_s }.include? constname.to_s } end
find the scope where constname is defined from @cref
resolve_const_owner
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def check_const(ast) case ast[0] when :const resolve_const_owner(ast[1]) when :colon2 if cst = check_const(ast[1]) cst.const_get(ast[2]) end when :colon3 ::Object.const_get(ast[2]) end end
checks if ast maps to a constant, returns it if it does
check_const
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def compile_args_m1(func, args) c = C::Variable.new("arg_c", C::BaseType.new(:int, :unsigned)) v = C::Variable.new("arg_v", C::Pointer.new(value)) @scope.symbol[c.name] = c @scope.symbol[v.name] = v func.type.args.unshift v func.type.args.unshift c args[1].times { |i| local(i+2, C::CExpression[v, :'[]', [i]]) } if args[2] # [:block, [:lasgn, 2, [:lit, 4]]] raise Fail, "unhandled vararglist #{args.inspect}" if args[2][0] != :block args[2][1..-1].each_with_index { |a, i| raise Fail, "unhandled arg #{a.inspect}" if a[0] != :lasgn cnd = C::CExpression[c, :>, i] thn = C::CExpression[local(a[1], :none), :'=', [v, :'[]', [i]]] els = C::Block.new(@scope) ast_to_c(a, els, false) @scope.statements << C::If.new(cnd, thn, els) } end if args[3] raise Fail, "unhandled vararglist3 #{args.inspect}" if args[3][0] != :lasgn skiplen = args[1] + args[2].length - 1 alloc = fcall('rb_ary_new4', [c, :-, [skiplen]], [v, :+, [skiplen]]) local(args[3][1], C::CExpression[[c, :>, skiplen], :'?:', [alloc, fcall('rb_ary_new')]]) end end
update func prototype to reflect arity -1 VALUE func(int argc, VALUE *argv, VALUE self)
compile_args_m1
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def compile_args_m2(func, args) v = C::Variable.new("arglist", value) @scope.symbol[v.name] = v func.type.args << v args[1].times { |i| local(i+2, fcall('rb_ary_shift', v)) } # populate arguments with default values if args[2] # [:block, [:lasgn, 2, [:lit, 4]]] raise Fail, "unhandled vararglist #{args.inspect}" if args[2][0] != :block args[2][1..-1].each { |a| raise Fail, "unhandled arg #{a.inspect}" if a[0] != :lasgn t = C::CExpression[local(a[1], :none), :'=', fcall('rb_ary_shift', v)] e = C::Block.new(@scope) ast_to_c([:lasgn, a[1], a[2]], e, false) @scope.statements << C::If.new(rb_ary_len(v), t, e) } end if args[3] raise Fail, "unhandled vararglist3 #{args.inspect}" if args[3][0] != :lasgn local(args[3][1], C::CExpression[v]) end end
update func prototype to reflect arity -2 VALUE func(VALUE self, VALUE arg_array)
compile_args_m2
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def compile_case(ast, scope, want_value) # this generates # var = stuff_to_test() # if (var & 1) # switch (var >> 1) { # case 12: # stuff(); # break; # default: # goto default_case; # } # else # default_case: # if (var == true.object_id || rb_test(rb_funcall(bla, '===', var))) # foo(); # else { # default(); # } # if want_value == true ret = get_new_tmp_var('case', want_value) want_value = ret elsif want_value ret = want_value end var = ast_to_c(ast[1], scope, want_value || true) if not var.kind_of? C::Variable ret ||= get_new_tmp_var('case', want_value) scope.statements << C::CExpression[ret, :'=', var] var = ret end # the scope to put all case int in body_int = C::Block.new(scope) # the scope to put the if (cs === var) cascade body_other_head = body_other = nil default = nil ast[2..-1].each { |cs| if cs[0] == :when raise Fail if cs[1][0] != :array # numeric case, add a case to body_int if cs[1][1..-1].all? { |cd| cd[0] == :lit and (cd[1].kind_of? Fixnum or cd[1].kind_of? Range) } cs[1][1..-1].each { |cd| if cd[1].kind_of? Range b = cd[1].begin e = cd[1].end e -= 1 if cd[1].exclude_end? raise Fail unless b.kind_of? Integer and e.kind_of? Integer body_int.statements << C::Case.new(b, e, nil) else body_int.statements << C::Case.new(cd[1], nil, nil) end } cb = C::Block.new(scope) v = ast_to_c(cs[2], cb, want_value) cb.statements << C::CExpression[ret, :'=', v] if want_value and v != ret cb.statements << C::Break.new body_int.statements << cb # non-numeric (or mixed) case, add if ( cs === var ) else cnd = nil cs[1][1..-1].each { |cd| if (cd[0] == :lit and (cd[1].kind_of?(Fixnum) or cd[1].kind_of?(Symbol))) or [:nil, :true, :false].include?(cd[0]) # true C equality cd = C::CExpression[var, :==, ast_to_c(cd, scope)] else # own block for ast_to_c to honor lazy evaluation tb = C::Block.new(scope) test = rb_test(rb_funcall(ast_to_c(cd, tb), '===', var), tb) # discard own block unless needed if tb.statements.empty? cd = test else tb.statements << test cd = C::CExpression[tb, value] end end cnd = (cnd ? C::CExpression[cnd, :'||', cd] : cd) } cb = C::Block.new(scope) v = ast_to_c(cs[2], cb, want_value) cb.statements << C::CExpression[ret, :'=', v] if want_value and v != ret fu = C::If.new(cnd, cb, nil) if body_other body_other.belse = fu else body_other_head = fu end body_other = fu end # default case statement else cb = C::Block.new(scope) v = ast_to_c(cs, cb, want_value) cb.statements << C::CExpression[ret, :'=', v] if want_value and v != ret default = cb end } # if we use the value of the case, we must add an 'else: nil' if want_value and not default default = C::Block.new(scope) default.statements << C::CExpression[ret, :'=', rb_nil] end # assemble everything scope.statements << if body_int.statements.empty? if body_other body_other.belse = default body_other_head else raise Fail, "empty case? #{ast.inspect}" if not default default end else if body_other_head @default_label_cnt ||= 0 dfl = "default_label_#{@default_label_cnt += 1}" body_other_head = C::Label.new(dfl, body_other_head) body_int.statements << C::Case.new('default', nil, C::Goto.new(dfl)) body_other.belse = default if default end body_int = C::Switch.new(C::CExpression[var, :>>, 1], body_int) C::If.new(C::CExpression[var, :&, 1], body_int, body_other_head) end ret end
compile a case/when create a real C switch() for Fixnums, and put the others === in the default case XXX will get the wrong order for "case x; when 1; when Fixnum; when 3;" ...
compile_case
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def fcall(fname, *arglist) args = arglist.map { |a| (a.kind_of?(Integer) or a.kind_of?(String)) ? [a] : a } fv = @cp.toplevel.symbol[fname] raise "need prototype for #{fname}!" if not fv C::CExpression[fv, :funcall, args] end
create a C::CExpr[toplevel.symbol[name], :funcall, args] casts int/strings in arglist to CExpr
fcall
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def declare_newvar(name, initializer) v = C::Variable.new(name, value) v.initializer = initializer if initializer != :none @scope.symbol[v.name] = v @scope.statements << C::Declaration.new(v) v end
declare a new function variable no initializer if init == :none
declare_newvar
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def escape_varname(n) n.gsub(/[^\w]/) { |c| c.unpack('H*')[0] } end
return a string suitable for use as a variable name hexencode any char not in [A-z0-9_]
escape_varname
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def get_var(name, initializer=:none) name = escape_varname(name) @scope.symbol[name] ||= declare_newvar(name, initializer || rb_nil) end
retrieve or create a local var pass :none to avoid initializer
get_var
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def local(n, init=nil) get_var "local_#{n}", init end
retrieve/create a new local variable with optionnal initializer
local
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def dvar(n, init=nil) get_var "dvar_#{n}", init end
retrieve/create a new dynamic variable (block argument/variable) pass :none to avoid initializer
dvar
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def rb_cast_pvalue(expr, idx) C::CExpression[[[expr], C::Pointer.new(value)], :'[]', [idx]] end
returns a CExpr casting expr to a VALUE*
rb_cast_pvalue
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def rb_selfclass rb_cast_pvalue(rb_self, 1) end
retrieve the current class, from self->klass XXX will segfault with self.kind_of? Fixnum/true/false/nil/sym
rb_selfclass
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def rb_test(expr, scope) if nil.object_id == 0 or false.object_id == 0 # just to be sure nf = nil.object_id | false.object_id C::CExpression[[expr, :|, nf], :'!=', nf] else if expr.kind_of? C::Variable tmp = expr else tmp = get_new_tmp_var('test') scope.statements << C::CExpression[tmp, :'=', expr] end C::CExpression[[tmp, :'!=', rb_nil], :'&&', [tmp, :'!=', rb_false]] end end
ruby bool test of a var assigns to a temporary var, and check against false/nil
rb_test
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def rb_raise(reason, cls='rb_eRuntimeError') fcall('rb_raise', rb_global(cls), reason) end
generate C code to raise a RuntimeError, reason
rb_raise
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def rb_test_class_type(expr, type) C::CExpression[[[expr, :>, [7]], :'&&', [[expr, :&, [3]], :==, [0]]], :'&&', [[rb_cast_pvalue(expr, 0), :&, [0x3f]], :'==', [type]]] end
return a C expr equivallent to TYPE(expr) == type for non-immediate types XXX expr evaluated 3 times
rb_test_class_type
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def rb_test_class_ary(expr) rb_test_class_type(expr, 9) end
return a C expr equivallent to TYPE(expr) == T_ARRAY
rb_test_class_ary
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def rb_const(constname, owner = resolve_const_owner(constname)) raise Fail, "no dynamic constant resolution #{constname}" if not owner cst = owner.const_get(constname) C::CExpression[[RubyHack.rb_obj_to_value(cst)], value] end
returns a static pointer to the constant
rb_const
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def rb_masgn_optimized(ast, scope) vars = [] ast[2][1..-1].each { |rhs| var = get_new_tmp_var('masgn_opt') vars << var r = ast_to_c(rhs, scope, var) scope.statements << C::CExpression[var, :'=', r] if var != r } ast[1][1..-1].each { |lhs| var = vars.shift lhs = lhs.dup raise Fail, "weird masgn lhs #{lhs.inspect} in #{ast.inspect}" if lhs[-1] != nil lhs[-1] = [:rb2cvar, var.name] ast_to_c(lhs, scope, false) } end
compile an optimized :masgn with rhs.length == lhs.length (no need of a ruby array)
rb_masgn_optimized
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def ast_to_c(ast, scope, want_value = true) ret = case ast.to_a[0] when :block if ast[1] ast[1..-2].each { |a| ast_to_c(a, scope, false) } ast_to_c(ast.last, scope, want_value) end when :lvar local(ast[1]) when :lasgn if scope == @scope l = local(ast[1], :none) else # w = 4 if false ; p w => should be nil l = local(ast[1]) end st = ast_to_c(ast[2], scope, l) scope.statements << C::CExpression[l, :'=', st] if st != l l when :dvar dvar(ast[1]) when :dasgn_curr l = dvar(ast[1]) st = ast_to_c(ast[2], scope, l) scope.statements << C::CExpression[l, :'=', st] if st != l l when :ivar fcall('rb_ivar_get', rb_self, rb_intern(ast[1])) when :iasgn if want_value tmp = get_new_tmp_var("ivar_#{ast[1]}", want_value) scope.statements << C::CExpression[tmp, :'=', ast_to_c(ast[2], scope)] scope.statements << fcall('rb_ivar_set', rb_self, rb_intern(ast[1]), tmp) tmp else scope.statements << fcall('rb_ivar_set', rb_self, rb_intern(ast[1]), ast_to_c(ast[2], scope)) end when :cvar fcall('rb_cvar_get', rb_selfclass, rb_intern(ast[1])) when :cvasgn if want_value tmp = get_new_tmp_var("cvar_#{ast[1]}", want_value) scope.statements << C::CExpression[tmp, :'=', ast_to_c(ast[2], scope)] scope.statements << fcall('rb_cvar_set', rb_selfclass, rb_intern(ast[1]), tmp, rb_false) tmp else scope.statements << fcall('rb_cvar_set', rb_selfclass, rb_intern(ast[1]), ast_to_c(ast[2], scope), rb_false) end when :gvar fcall('rb_gv_get', ast[1]) when :gasgn if want_value tmp = get_new_tmp_var("gvar_#{ast[1]}", want_value) scope.statements << C::CExpression[tmp, :'=', ast_to_c(ast[2], scope)] scope.statements << fcall('rb_gv_set', ast[1], tmp) tmp else scope.statements << fcall('rb_gv_set', ast[1], ast_to_c(ast[2], scope)) end when :attrasgn # foo.bar= 42 (same as :call, except for return value) recv = ast_to_c(ast[1], scope) raise Fail, "unsupported #{ast.inspect}" if not ast[3] or ast[3][0] != :array if ast[3].length != 2 if ast[2] != '[]=' or ast[3].length != 3 raise Fail, "unsupported #{ast.inspect}" end # foo[4] = 2 idx = ast_to_c(ast[3][1], scope) end arg = ast_to_c(ast[3].last, scope) if want_value tmp = get_new_tmp_var('call', want_value) scope.statements << C::CExpression[tmp, :'=', arg] end if idx scope.statements << rb_funcall(recv, ast[2], idx, arg) else scope.statements << rb_funcall(recv, ast[2], arg) end tmp when :rb2cvar # hax, used in vararg parsing get_var(ast[1]) when :rb2cstmt ast[1] when :block_arg local(ast[3], fcall('rb_block_proc')) when :lit case ast[1] when Symbol # XXX ID2SYM C::CExpression[[rb_intern(ast[1].to_s), :<<, 8], :|, 0xe] when Range fcall('rb_range_new', ast[1].begin.object_id, ast[1].end.object_id, ast[1].exclude_end? ? 0 : 1) else # true/false/nil/fixnum ast[1].object_id end when :self rb_self when :str fcall('rb_str_new2', ast[1]) when :array tmp = get_new_tmp_var('ary', want_value) scope.statements << C::CExpression[tmp, :'=', fcall('rb_ary_new')] ast[1..-1].each { |e| scope.statements << fcall('rb_ary_push', tmp, ast_to_c(e, scope)) } tmp when :hash raise Fail, "bad #{ast.inspect}" if ast[1][0] != :array tmp = get_new_tmp_var('hash', want_value) scope.statements << C::CExpression[tmp, :'=', fcall('rb_hash_new')] ki = nil ast[1][1..-1].each { |k| if not ki ki = k else scope.statements << fcall('rb_hash_aset', tmp, ast_to_c(ki, scope), ast_to_c(k, scope)) ki = nil end } tmp when :iter if v = optimize_iter(ast, scope, want_value) return v end # for full support of :iter, we need access to the interpreter's ruby_block private global variable in eval.c # we can find it by analysing rb_block_given_p, but this won't work with a static precompiled rubyhack... # even with access to ruby_block, there we would need to redo PUSH_BLOCK, create a temporary dvar list, # handle [:break, lol], and do all the stack magic reused in rb_yield (probably incl setjmp etc) raise Fail, "unsupported iter #{ast[3].inspect} { | #{ast[1].inspect} | #{ast[2].inspect} }" when :call, :vcall, :fcall if v = optimize_call(ast, scope, want_value) return v end recv = ((ast[0] == :call) ? ast_to_c(ast[1], scope) : rb_self) if not ast[3] f = rb_funcall(recv, ast[2]) elsif ast[3][0] == :array args = ast[3][1..-1].map { |a| ast_to_c(a, scope) } f = rb_funcall(recv, ast[2], *args) elsif ast[3][0] == :splat args = ast_to_c(ast[3], scope) if not args.kind_of? C::Variable tmp = get_new_tmp_var('args', want_value) scope.statements << C::CExpression[tmp, :'=', args] args = tmp end f = fcall('rb_funcall3', recv, rb_intern(ast[2]), rb_ary_len(args), rb_ary_ptr(args)) # elsif ast[3][0] == :argscat else raise Fail, "unsupported #{ast.inspect}" end if want_value tmp ||= get_new_tmp_var('call', want_value) scope.statements << C::CExpression[tmp, :'=', f] tmp else scope.statements << f f end when :if, :when if ast[0] == :when and ast[1][0] == :array cnd = nil ast[1][1..-1].map { |cd| rb_test(ast_to_c(cd, scope), scope) }.each { |cd| cnd = (cnd ? C::CExpression[cnd, :'||', cd] : cd) } else cnd = rb_test(ast_to_c(ast[1], scope), scope) end tbdy = C::Block.new(scope) ebdy = C::Block.new(scope) if ast[3] or want_value if want_value tmp = get_new_tmp_var('if', want_value) thn = ast_to_c(ast[2], tbdy, tmp) tbdy.statements << C::CExpression[tmp, :'=', thn] if tmp != thn if ast[3] els = ast_to_c(ast[3], ebdy, tmp) else # foo = if bar ; baz ; end => nil if !bar els = rb_nil end ebdy.statements << C::CExpression[tmp, :'=', els] if tmp != els else ast_to_c(ast[2], tbdy, false) ast_to_c(ast[3], ebdy, false) end scope.statements << C::If.new(cnd, tbdy, ebdy) tmp when :while, :until pib = @iter_break @iter_break = nil # XXX foo = while ()... body = C::Block.new(scope) if ast[3] == 0 # do .. while(); ast_to_c(ast[2], body, false) end t = nil e = C::Break.new t, e = e, t if ast[0] == :until body.statements << C::If.new(rb_test(ast_to_c(ast[1], body), body), t, e) if ast[3] != 0 # do .. while(); ast_to_c(ast[2], body, false) end scope.statements << C::For.new(nil, nil, nil, body) @iter_break = pib nil.object_id when :and, :or, :not # beware lazy evaluation ! tmp = get_new_tmp_var('and', want_value) v1 = ast_to_c(ast[1], scope, tmp) # and/or need that tmp has the actual v1 value (returned when shortcircuit) scope.statements << C::CExpression[tmp, :'=', v1] if v1 != tmp v1 = tmp case ast[0] when :and t = C::Block.new(scope) v2 = ast_to_c(ast[2], t, tmp) t.statements << C::CExpression[tmp, :'=', v2] if v2 != tmp when :or e = C::Block.new(scope) v2 = ast_to_c(ast[2], e, tmp) e.statements << C::CExpression[tmp, :'=', v2] if v2 != tmp when :not t = C::CExpression[tmp, :'=', rb_false] e = C::CExpression[tmp, :'=', rb_true] end scope.statements << C::If.new(rb_test(v1, scope), t, e) tmp when :return scope.statements << C::Return.new(ast_to_c(ast[1], scope)) nil.object_id when :break if @iter_break v = (ast[1] ? ast_to_c(ast[1], scope, @iter_break) : nil.object_id) scope.statements << C::CExpression[@iter_break, :'=', [[v], value]] if @iter_break != v end scope.statements << C::Break.new nil.object_id when nil, :args nil.object_id when :nil rb_nil when :false rb_false when :true rb_true when :const rb_const(ast[1]) when :colon2 if cst = check_const(ast[1]) rb_const(ast[2], cst) else fcall('rb_const_get', ast_to_c(ast[1], scope), rb_intern(ast[2])) end when :colon3 rb_const(ast[1], ::Object) when :defined case ast[1][0] when :ivar fcall('rb_ivar_defined', rb_self, rb_intern(ast[1][1])) else raise Fail, "unsupported #{ast.inspect}" end when :masgn # parallel assignment: put everything in an Array, then pop everything back? rb_masgn(ast, scope, want_value) when :evstr fcall('rb_obj_as_string', ast_to_c(ast[1], scope)) when :dot2, :dot3 fcall('rb_range_new', ast_to_c(ast[1], scope), ast_to_c(ast[2], scope), ast[0] == :dot2 ? 0 : 1) when :splat fcall('rb_Array', ast_to_c(ast[1], scope)) when :to_ary fcall('rb_ary_to_ary', ast_to_c(ast[1], scope)) when :dstr # dynamic string: "foo#{bar}baz" tmp = get_new_tmp_var('dstr') scope.statements << C::CExpression[tmp, :'=', fcall('rb_str_new2', ast[1][1])] ast[2..-1].compact.each { |s| if s[0] == :str # directly append the char* scope.statements << fcall('rb_str_cat2', tmp, s[1]) else scope.statements << fcall('rb_str_append', tmp, ast_to_c(s, scope)) end } tmp when :case compile_case(ast, scope, want_value) when :ensure # TODO ret = ast_to_c(ast[1], scope, want_value) ast_to_c(ast[3], scope, false) ret else raise Fail, "unsupported #{ast.inspect}" end if want_value ret = C::CExpression[[ret], value] if ret.kind_of? Integer or ret.kind_of? String ret end end
the recursive AST to C compiler may append C statements to scope returns the C::CExpr holding the VALUE of the current ruby statement want_value is an optionnal hint as to the returned VALUE is needed or not if want_value is a C::Variable, the statements should try to populate this var instead of some random tmp var eg to simplify :if encoding unless we have 'foo = if 42;..'
ast_to_c
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def optimize_call(ast, scope, want_value) ce = C::CExpression op = ast[2] int = C::BaseType.new(:ptr) # signed VALUE args = ast[3][1..-1] if ast[3] and ast[3][0] == :array arg0 = args[0] if args and args[0] if arg0 and arg0[0] == :lit and arg0[1].kind_of?(Fixnum) and %w[== > < >= <= + -].include?(op) # TODO or @optim_hint[ast[1]] == 'fixnum' # optimize 'x==42', 'x+42', 'x-42' o2 = arg0[1] if o2 < 0 and ['+', '-'].include? op # need o2 >= 0 for overflow detection op = {'+' => '-', '-' => '+'}[op] o2 = -o2 return if not o2.kind_of? Fixnum # -0x40000000 end int_v = o2.object_id recv = ast_to_c(ast[1], scope) tmp = get_new_tmp_var('opt', want_value) if not recv.kind_of? C::Variable scope.statements << ce[tmp, :'=', recv] recv = tmp end case op when '==' # XXX assume == only return true for full equality: if not Fixnum, then always false # which breaks 1.0 == 1 and maybe others, but its ok scope.statements << C::If.new(ce[recv, :'==', [int_v]], ce[tmp, :'=', rb_true], ce[tmp, :'=', rb_false]) when '>', '<', '>=', '<=' # do the actual comparison on signed >>1 if both Fixnum t = C::If.new( ce[[[[recv], int], :>>, [1]], op.to_sym, [[[int_v], int], :>>, [1]]], ce[tmp, :'=', rb_true], ce[tmp, :'=', rb_false]) # fallback to actual rb_funcall e = ce[tmp, :'=', rb_funcall(recv, op, o2.object_id)] add_optimized_statement scope, ast[1], recv, 'fixnum' => t, 'other' => e when '+' e = ce[recv, :+, [int_v-1]] # overflow to Bignum ? cnd = ce[[recv, :&, [1]], :'&&', [[[recv], int], :<, [[e], int]]] t = ce[tmp, :'=', e] e = ce[tmp, :'=', rb_funcall(recv, op, o2.object_id)] if @optim_hint[ast[1]] == 'fixnum' # add_optimized_statement wont handle the overflow check correctly scope.statements << t else scope.statements << C::If.new(cnd, t, e) end when '-' e = ce[recv, :-, [int_v-1]] cnd = ce[[recv, :&, [1]], :'&&', [[[recv], int], :>, [[e], int]]] t = ce[tmp, :'=', e] e = ce[tmp, :'=', rb_funcall(recv, op, o2.object_id)] if @optim_hint[ast[1]] == 'fixnum' scope.statements << t else scope.statements << C::If.new(cnd, t, e) end end tmp # Symbol#== elsif arg0 and arg0[0] == :lit and arg0[1].kind_of? Symbol and op == '==' s_v = ast_to_c(arg0, scope) tmp = get_new_tmp_var('opt', want_value) recv = ast_to_c(ast[1], scope, tmp) if not recv.kind_of? C::Variable scope.statements << ce[tmp, :'=', recv] recv = tmp end scope.statements << C::If.new(ce[recv, :'==', [s_v]], ce[tmp, :'=', rb_true], ce[tmp, :'=', rb_false]) tmp elsif arg0 and op == '<<' tmp = get_new_tmp_var('opt', want_value) recv = ast_to_c(ast[1], scope, tmp) arg = ast_to_c(arg0, scope) if recv != tmp scope.statements << ce[tmp, :'=', recv] recv = tmp end ar = fcall('rb_ary_push', recv, arg) st = fcall('rb_str_concat', recv, arg) oth = rb_funcall(recv, op, arg) oth = ce[tmp, :'=', oth] if want_value add_optimized_statement scope, ast[1], recv, 'ary' => ar, 'string' => st, 'other' => oth tmp elsif arg0 and args.length == 1 and op == '[]' return if ast[1][0] == :const # Expression[42] tmp = get_new_tmp_var('opt', want_value) recv = ast_to_c(ast[1], scope, tmp) if not recv.kind_of? C::Variable scope.statements << ce[tmp, :'=', recv] recv = tmp end idx = get_new_tmp_var('idx') arg = ast_to_c(arg0, scope, idx) if not arg.kind_of? C::Variable scope.statements << ce[idx, :'=', arg] arg = idx end idx = ce[[idx], int] ar = C::Block.new(scope) ar.statements << ce[idx, :'=', [[[arg], int], :>>, [1]]] ar.statements << C::If.new(ce[idx, :<, [0]], ce[idx, :'=', [idx, :+, rb_ary_len(recv)]], nil) ar.statements << C::If.new(ce[[idx, :<, [0]], :'||', [idx, :>=, [[rb_ary_len(recv)], int]]], ce[tmp, :'=', rb_nil], ce[tmp, :'=', rb_ary_ptr(recv, idx)]) st = C::Block.new(scope) st.statements << ce[idx, :'=', [[[arg], int], :>>, [1]]] st.statements << C::If.new(ce[idx, :<, [0]], ce[idx, :'=', [idx, :+, rb_str_len(recv)]], nil) st.statements << C::If.new(ce[[idx, :<, [0]], :'||', [idx, :>=, [[rb_str_len(recv)], int]]], ce[tmp, :'=', rb_nil], ce[tmp, :'=', [[[[rb_str_ptr(recv, idx), :&, [0xff]], :<<, [1]], :|, [1]], value]]) hsh = ce[tmp, :'=', fcall('rb_hash_aref', recv, arg)] oth = ce[tmp, :'=', rb_funcall(recv, op, arg)] # ary/string only valid with fixnum argument ! add_optimized_statement scope, ast[1], recv, 'hash' => hsh, 'other' => oth, 'ary_bnd' => ce[tmp, :'=', rb_ary_ptr(recv, ce[[[arg], int], :>>, [1]])], ce[[arg, :&, 1], :'&&', rb_test_class_ary(recv)] => ar, ce[[arg, :&, 1], :'&&', rb_test_class_string(recv)] => st tmp elsif ast[1] and not arg0 and op == 'empty?' tmp = get_new_tmp_var('opt', want_value) recv = ast_to_c(ast[1], scope, tmp) if not recv.kind_of? C::Variable scope.statements << ce[tmp, :'=', recv] recv = tmp end ar = C::If.new(rb_ary_len(recv), ce[tmp, :'=', rb_false], ce[tmp, :'=', rb_true]) add_optimized_statement scope, ast[1], recv, 'ary' => ar, 'other' => ce[tmp, :'=', rb_funcall(recv, op)] tmp elsif ast[1] and not arg0 and op == 'pop' tmp = get_new_tmp_var('opt', want_value) recv = ast_to_c(ast[1], scope, tmp) if not recv.kind_of? C::Variable scope.statements << ce[tmp, :'=', recv] recv = tmp end t = fcall('rb_ary_pop', recv) e = rb_funcall(recv, op) if want_value t = ce[tmp, :'=', t] e = ce[tmp, :'=', e] end add_optimized_statement scope, ast[1], recv, 'ary' => t, 'other' => e tmp elsif ast[1] and op == 'kind_of?' and arg0 and (arg0[0] == :const or arg0[0] == :colon3) # TODO check const maps to toplevel when :const test = case arg0[1] when 'Symbol' tmp = get_new_tmp_var('kindof', want_value) ce[[ast_to_c(ast[1], scope, tmp), :'&', [0xf]], :'==', [0xe]] #when 'Numeric', 'Integer' when 'Fixnum' tmp = get_new_tmp_var('kindof', want_value) ce[ast_to_c(ast[1], scope, tmp), :'&', [0x1]] when 'Array' rb_test_class_ary(ast_to_c(ast[1], scope)) when 'String' rb_test_class_string(ast_to_c(ast[1], scope)) else return end puts "shortcut may be incorrect for #{ast.inspect}" if arg0[0] == :const tmp ||= get_new_tmp_var('kindof', want_value) scope.statements << C::If.new(test, ce[tmp, :'=', rb_true], ce[tmp, :'=', rb_false]) tmp elsif not ast[1] or ast[1] == [:self] optimize_call_static(ast, scope, want_value) end end
optional optimization of a call (eg a == 1, c+2, ...) return nil for normal rb_funcall, or a C::CExpr to use as retval.
optimize_call
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def get_cfuncptr(klass, method, singleton=false) cls = singleton ? (class << klass ; self ; end) : klass ptr = RubyHack.get_method_node_ptr(cls, method) return if ptr == 0 ftype = RubyHack::NODETYPE[(RubyHack.memory_read_int(ptr) >> 11) & 0xff] return if ftype != :cfunc fast = RubyHack.read_node(ptr) arity = fast[1][:arity] fptr = fast[1][:fptr] fproto = C::Function.new(value, []) case arity when -1; fproto.args << C::Variable.new(nil, C::BaseType.new(:int)) << C::Variable.new(nil, C::Pointer.new(value)) << C::Variable.new(nil, value) when -2; fproto.args << C::Variable.new(nil, value) << C::Variable.new(nil, value) else (arity+1).times { fproto.args << C::Variable.new(nil, value) } end C::CExpression[[fptr], C::Pointer.new(fproto)] end
return ptr, arity ptr is a CExpr pointing to the C func implementing klass#method
get_cfuncptr
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def optimize_call_static(ast, scope, want_value) arity = method_arity(ast[2]) rescue return if ast[2].to_s == @meth.to_s # self is recursive fptr = @cur_cfunc else fptr = get_cfuncptr(@klass, ast[2], @meth_singleton) return if not fptr end c_arglist = [] if not ast[3] args = [] elsif ast[3][0] == :array args = ast[3][1..-1] elsif ast[3][0] == :splat args = ast_to_c(ast[3], scope) if arity != -2 and !args.kind_of?(C::Variable) tmp = get_new_tmp_var('arg') scope.statements << C::CExpression[tmp, :'=', args] args = tmp end case arity when -2 c_arglist << rb_self << args when -1 c_arglist << [rb_ary_len(args)] << rb_ary_ptr(args) << rb_self else cnd = C::CExpression[rb_ary_len(args), :'!=', [arity]] scope.statements << C::If.new(cnd, rb_raise("#{arity} args expected", 'rb_eArgumentError'), nil) c_arglist << rb_self arity.times { |i| c_arglist << rb_ary_ptr(args, i) } end arity = :canttouchthis else return # TODO end case arity when :canttouchthis when -2 arg = get_new_tmp_var('arg') scope.statements << C::CExpression[arg, :'=', fcall('rb_ary_new')] args.each { |a| scope.statements << fcall('rb_ary_push', arg, ast_to_c(a, scope)) } c_arglist << rb_self << arg when -1 case args.length when 0 argv = C::CExpression[[0], C::Pointer.new(value)] when 1 val = ast_to_c(args[0], scope) if not val.kind_of? C::Variable argv = get_new_tmp_var('argv') scope.statements << C::CExpression[argv, :'=', val] val = argv end argv = C::CExpression[:'&', val] else argv = get_new_tmp_var('argv') argv.type = C::Array.new(value, args.length) args.each_with_index { |a, i| val = ast_to_c(a, scope) scope.statements << C::CExpression[[argv, :'[]', [i]], :'=', val] } end c_arglist << [args.length] << argv << rb_self else c_arglist << rb_self args.each { |a| va = get_new_tmp_var('arg') val = ast_to_c(a, scope, va) scope.statements << C::CExpression[va, :'=', val] if val != va c_arglist << va } end f = C::CExpression[fptr, :funcall, c_arglist] if want_value ret = get_new_tmp_var('ccall', want_value) scope.statements << C::CExpression[ret, :'=', f] ret else scope.statements << f end end
call C funcs directly assume private function calls are not virtual and hardlink them here
optimize_call_static
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def rb_const(constname, owner = resolve_const_owner(constname)) raise Fail, "no dynamic constant resolution #{constname}" if not owner @const_value ||= { [::Object, 'Object'] => rb_global('rb_cObject') } k = ::Object v = nil cname = owner.name cname += '::' + constname if constname cname.split('::').each { |n| kk = k.const_get(n) if not v = @const_value[[k, n]] # class A ; end ; B = A => B.name => 'A' vn = "const_#{escape_varname((k.name + '::' + n).sub(/^Object::/, '').gsub('::', '_'))}" vi = fcall('rb_const_get', rb_const(nil, k), fcall('rb_intern', n)) v = declare_newtopvar(vn, vi) # n wont be reused, so do not alloc a global intern_#{n} for this @const_value[[k, n]] = v end k = kk } v end
rb_const 'FOO', Bar::Baz ==> const_Bar = rb_const_get(rb_cObject, rb_intern("Bar")); const_Bar_Baz = rb_const_get(const_Bar, rb_intern("Baz")); const_Bar_Baz_FOO = rb_const_get(const_Bar_Baz, rb_intern("FOO")); use rb_const(nil, class) to get a pointer to a class/module
rb_const
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def rb_global(cname) C::CExpression[:*, @cp.toplevel.symbol[cname]] end
TODO remove this when the C compiler is fixed
rb_global
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def rb_funcall(recv, meth, *args) if not defined? @rb_fcid @cp.parse <<EOS int atexit(void(*)(void)); int printf(char*, ...); static unsigned rb_fcid_max = 1; static unsigned rb_fcntr[1]; static void rb_fcstat(void) { unsigned i; for (i=0 ; i<rb_fcid_max ; ++i) if (rb_fcntr[i]) printf("%u %u\\n", i, rb_fcntr[i]); } EOS @rb_fcid = -1 @rb_fcntr = @cp.toplevel.symbol['rb_fcntr'] @rb_fcid_max = @cp.toplevel.symbol['rb_fcid_max'] init.statements << fcall('atexit', @cp.toplevel.symbol['rb_fcstat']) end @rb_fcid += 1 @rb_fcid_max.initializer = C::CExpression[[@rb_fcid+1], @rb_fcid_max.type] @rb_fcntr.type.length = @rb_fcid+1 ctr = C::CExpression[:'++', [@rb_fcntr, :'[]', [@rb_fcid]]] C::CExpression[ctr, :',', super(recv, meth, *args)] end
dynamic trace of all rb_funcall made from our module
rb_funcall
ruby
stephenfewer/grinder
node/lib/metasm/samples/dynamic_ruby.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dynamic_ruby.rb
BSD-3-Clause
def create_sig(exe) func = case exe when COFFArchive; :create_sig_arch when PE, COFF; :create_sig_coff when ELF; :create_sig_elf else raise 'unsupported file format' end send(func, exe) { |sym, edata| sig = edata.data.unpack('H*').first edata.reloc.each { |o, r| # TODO if the reloc points to a known func (eg WinMain), keep the info sz = r.length sig[2*o, 2*sz] = '.' * sz * 2 } next if sig.gsub('.', '').length < 2*$min_sigbytes puts sym sig.scan(/.{1,78}/) { |s| puts ' ' + s } } end
read a binary file, print a signature for all symbols found
create_sig
ruby
stephenfewer/grinder
node/lib/metasm/samples/generate_libsigs.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/generate_libsigs.rb
BSD-3-Clause
def encode_edata Metasm::Shellcode.assemble(@@cpu, self).encode.encoded end
encodes the current string as a Shellcode, returns the resulting EncodedData
encode_edata
ruby
stephenfewer/grinder
node/lib/metasm/samples/metasm-shell.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/metasm-shell.rb
BSD-3-Clause
def encode ed = encode_edata if not ed.reloc.empty? puts 'W: encoded string has unresolved relocations: ' + ed.reloc.map { |o, r| r.target.inspect }.join(', ') end ed.fill ed.data end
encodes the current string as a Shellcode, returns the resulting binary String outputs warnings on unresolved relocations
encode
ruby
stephenfewer/grinder
node/lib/metasm/samples/metasm-shell.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/metasm-shell.rb
BSD-3-Clause
def decode_blocks(base_addr=0, eip=base_addr) sc = Metasm::Shellcode.decode(self, @@cpu) sc.base_addr = base_addr sc.disassemble(eip) end
decodes the current string as a Shellcode, with specified base address returns the resulting Disassembler
decode_blocks
ruby
stephenfewer/grinder
node/lib/metasm/samples/metasm-shell.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/metasm-shell.rb
BSD-3-Clause
def decode(base_addr=0, eip=base_addr) decode_blocks(base_addr, eip).to_s end
decodes the current string as a Shellcode, with specified base address returns the asm source equivallent
decode
ruby
stephenfewer/grinder
node/lib/metasm/samples/metasm-shell.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/metasm-shell.rb
BSD-3-Clause
def initialize(file, hooktype=:iat) if file.kind_of? Metasm::PE @pe = file elsif file[0, 2] == 'MZ' and file.length > 0x3c @pe = Metasm::PE.decode(file) else # filename @pe = Metasm::PE.decode_file(file) end @load_address = DL.memory_alloc(@pe.optheader.image_size) raise 'malloc' if @load_address == 0xffff_ffff puts "map sections" if $DEBUG DL.memory_write(@load_address, @pe.encoded.data[0, @pe.optheader.headers_size].to_str) @pe.sections.each { |s| DL.memory_write(@load_address+s.virtaddr, s.encoded.data.to_str) } puts "fixup sections" if $DEBUG off = @load_address - @pe.optheader.image_base @pe.relocations.to_a.each { |rt| base = rt.base_addr rt.relocs.each { |r| if r.type == 'HIGHLOW' ptr = @load_address + base + r.offset old = DL.memory_read(ptr, 4).unpack('V').first DL.memory_write_int(ptr, old + off) end } } @iat_cb = {} @eat_cb = {} case hooktype when :iat puts "hook IAT" if $DEBUG @pe.imports.to_a.each { |id| ptr = @load_address + id.iat_p id.imports.each { |i| n = "#{id.libname}!#{i.name}" cb = DL.callback_alloc_c('void x(void)') { raise "unemulated import #{n}" } DL.memory_write_int(ptr, cb) @iat_cb[n] = cb ptr += 4 } } when :eat, :exports puts "hook EAT" if $DEBUG ptr = @load_address + @pe.export.func_p @pe.export.exports.each { |e| n = e.name || e.ordinal cb = DL.callback_alloc_c('void x(void)') { raise "unemulated export #{n}" } DL.memory_write_int(ptr, cb - @load_address) # RVA @eat_cb[n] = cb ptr += 4 } end end
load a PE file, setup basic IAT hooks (raises "unhandled lib!import")
initialize
ruby
stephenfewer/grinder
node/lib/metasm/samples/peldr.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/peldr.rb
BSD-3-Clause
def reprotect_sections @pe.sections.each { |s| p = '' p << 'r' if s.characteristics.include? 'MEM_READ' p << 'w' if s.characteristics.include? 'MEM_WRITE' p << 'x' if s.characteristics.include? 'MEM_EXECUTE' DL.memory_perm(@load_address + s.virtaddr, s.virtsize, p) } end
reset original expected memory protections for the sections the IAT may reside in a readonly section, so call this only after all hook_imports
reprotect_sections
ruby
stephenfewer/grinder
node/lib/metasm/samples/peldr.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/peldr.rb
BSD-3-Clause
def hook_import(libname, impname, proto, &b) @pe.imports.to_a.each { |id| next if id.libname != libname ptr = @load_address + id.iat_p id.imports.each { |i| if i.name == impname DL.callback_free(@iat_cb["#{libname}!#{impname}"]) if proto.kind_of? Integer cb = proto else cb = DL.callback_alloc_c(proto, &b) @iat_cb["#{libname}!#{impname}"] = cb end DL.memory_write_int(ptr, cb) end ptr += 4 } } end
add a specific hook for an IAT function accepts a function pointer in proto exemple: hook_import('KERNEL32.dll', 'GetProcAddress', '__stdcall int f(int, char*)') { |h, name| puts "getprocaddr #{name}" ; 0 }
hook_import
ruby
stephenfewer/grinder
node/lib/metasm/samples/peldr.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/peldr.rb
BSD-3-Clause
def hook_export(name, proto, &b) ptr = @load_address + @pe.export.func_p @pe.export.exports.each { |e| n = e.name || e.ordinal if n == name DL.callback_free(@eat_cb[name]) if proto.kind_of? Integer cb = proto else cb = DL.callback_alloc_c(proto, &b) @eat_cb[name] = cb end DL.memory_write_int(ptr, cb - @load_address) # RVA end ptr += 4 } end
add a specific hook in the export table exemple: hook_export('ExportedFunc', '__stdcall int f(int, char*)') { |i, p| blabla ; 1 }
hook_export
ruby
stephenfewer/grinder
node/lib/metasm/samples/peldr.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/peldr.rb
BSD-3-Clause
def new_api_c(proto) proto += ';' # allow 'int foo()' cp = DL.host_cpu.new_cparser cp.parse(proto) cp.toplevel.symbol.each_value { |v| next if not v.kind_of? Metasm::C::Variable # enums if e = pe.export.exports.find { |e_| e_.name == v.name and e_.target } DL.new_caller_for(cp, v, v.name.downcase, @load_address + pe.label_rva(e.target)) end } cp.numeric_constants.each { |k, v, f| n = k.upcase n = "C#{n}" if n !~ /^[A-Z]/ DL.const_set(n, v) if not DL.const_defined?(n) and v.kind_of? Integer } end
similar to DL.new_api_c for the mapped PE
new_api_c
ruby
stephenfewer/grinder
node/lib/metasm/samples/peldr.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/peldr.rb
BSD-3-Clause
def intercept_iat(ldr) ldr.pe.imports.to_a.each { |id| id.imports.each { |i| next if not @exports.include? i.name or not @eat_cb[i.name] ldr.hook_import(id.libname, i.name, @eat_cb[i.name]) } } end
take another PeLdr and patch its IAT with functions from our @exports (eg our explicit export hooks)
intercept_iat
ruby
stephenfewer/grinder
node/lib/metasm/samples/peldr.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/peldr.rb
BSD-3-Clause
def do_singlestep(pid, tid) ctx = get_context(pid, tid) eip = ctx[:eip] if l = @label[eip] puts l + ':' end if $VERBOSE bin = @mem[pid][eip, 16] di = @prog.cpu.decode_instruction(Metasm::EncodedData.new(bin), eip) puts "#{'%08X' % eip} #{di.instruction}" end ctx[:eflags] |= 0x100 end
dumps the opcode at eip, sets the trace flag
do_singlestep
ruby
stephenfewer/grinder
node/lib/metasm/samples/wintrace.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/wintrace.rb
BSD-3-Clause
def hide_debugger(pid, tid, info) peb = @mem[pid][info.threadlocalbase + 0x30, 4].unpack('L').first @mem[pid][peb + 2, 2] = [0].pack('S') end
resets the DebuggerPresent field of the PEB
hide_debugger
ruby
stephenfewer/grinder
node/lib/metasm/samples/wintrace.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/wintrace.rb
BSD-3-Clause
def imm_to_const_decompose(imm, cstbase) cstbase = /#{cstbase}/i if not cstbase.kind_of? Regexp dict = {} c_parser.lexer.definition.keys.grep(cstbase).each { |cst| if i = c_parser.macro_numeric(cst) dict[cst] = i end } c_parser.toplevel.symbol.each { |k, v| dict[k] = v if v.kind_of? Integer and k =~ cstbase } dict.delete_if { |k, v| imm & v != v } if cst = dict.index(imm) cst else # a => 1, b => 2, c => 4, all => 7: discard abc, keep 'all' dict.delete_if { |k, v| dict.find { |kk, vv| vv > v and vv & v == v } } dict.keys.join(' | ') if not dict.empty? end end
find the bitwise decomposition of imm into constants whose name include cstbase
imm_to_const_decompose
ruby
stephenfewer/grinder
node/lib/metasm/samples/dasm-plugins/c_constants.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dasm-plugins/c_constants.rb
BSD-3-Clause
def matched_findsym(str, off) str = str[off, @siglenmax].unpack('H*').first @sigs.find { |sym, sig| str =~ /^#{sig}/i }[0] end
we found a match on str at off, identify the specific symbol that matched on conflict, only return the first match
matched_findsym
ruby
stephenfewer/grinder
node/lib/metasm/samples/dasm-plugins/match_libsigs.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dasm-plugins/match_libsigs.rb
BSD-3-Clause
def match_chunk(str) count = 0 off = 0 while o = (str[off..-1] =~ @giantregex) count += 1 off += o sym = matched_findsym(str, off) yield off, sym off += 1 end count end
matches the signatures against a raw string yields offset, symname for each match returns nr of matches found
match_chunk
ruby
stephenfewer/grinder
node/lib/metasm/samples/dasm-plugins/match_libsigs.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dasm-plugins/match_libsigs.rb
BSD-3-Clause
def match(str) chunksz = 1 << 20 chunkoff = 0 count = 0 while chunkoff < str.length chunk = str[chunkoff, chunksz+@siglenmax] count += match_chunk(chunk) { |o, sym| yield chunkoff+o, sym if o < chunksz } chunkoff += chunksz end count end
matches the signatures against a big raw string yields offset, symname for each match returns nr of matches found
match
ruby
stephenfewer/grinder
node/lib/metasm/samples/dasm-plugins/match_libsigs.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dasm-plugins/match_libsigs.rb
BSD-3-Clause
def reopen_rw(addr=nil, edata=nil) if not edata sections.each { |k, v| reopen_rw(k, v) } return true end return if not File.writable?(@program.filename) backup_program_file if not edata.data.kind_of? VirtualFile # section too small, loaded as real String # force reopen as VFile (allow hexediting in gui) return if not off = addr_to_fileoff(addr) len = edata.data.length edata.data = VirtualFile.read(@program.filename, 'rb+').dup(off, len) else edata.data.fd.reopen @program.filename, 'rb+' end end
create a backup and reopen the backend VirtualFile RW
reopen_rw
ruby
stephenfewer/grinder
node/lib/metasm/samples/dasm-plugins/patch_file.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dasm-plugins/patch_file.rb
BSD-3-Clause
def trace @trace_subfuncs = true @trace_terminate = false id = [pc, 0, 0] trace_func_newtrace(id) trace_func_block(id) continue end
start tracing now, and stop only when @trace_terminate is set
trace
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-plugins/trace_func.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-plugins/trace_func.rb
BSD-3-Clause
def trace_func_block(id) blockaddr = pc if b = trace_get_block(blockaddr) trace_func_add_block(id, blockaddr) if b.list.length == 1 trace_func_blockend(id, blockaddr) else bpx(b.list.last.address, true) { finished = trace_func_blockend(id, blockaddr) continue if not finished } end else # invalid opcode ? trace_func_blockend(id, blockaddr) end end
we hit the beginning of a block we want to trace
trace_func_block
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-plugins/trace_func.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-plugins/trace_func.rb
BSD-3-Clause
def trace_func_blockend(id, blockaddr) if di = disassembler.di_at(pc) if end_stepout(di) and trace_func_istraceend(id, di) # trace ends there trace_func_finish(id) return true elsif di.opcode.props[:saveip] and not trace_func_entersubfunc(id, di) # call to a subfunction bpx(di.next_addr, true) { trace_func_block(id) continue } continue else singlestep { newaddr = pc trace_func_block(id) trace_func_linkdasm(di.address, newaddr) continue } end else # XXX should link in the dasm somehow singlestep { trace_func_block(id) continue } end false end
we are at the end of a traced block, find whats next
trace_func_blockend
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-plugins/trace_func.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-plugins/trace_func.rb
BSD-3-Clause
def trace_get_block(addr) # TODO trace all blocks from addr for which we know the target, stop on call / jmp [foo] disassembler.disassemble_fast_block(addr) if di = disassembler.di_at(addr) di.block end end
retrieve an instructionblock, disassemble if needed
trace_get_block
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-plugins/trace_func.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-plugins/trace_func.rb
BSD-3-Clause
def trace_func_linkdasm(from_addr, new_addr) di = disassembler.di_at(from_addr) ndi = disassembler.di_at(new_addr) return if not di # is it a subfunction return ? if end_stepout(di) and cdi = (1..8).map { |i| disassembler.di_at(new_addr - i) }.compact.find { |cdi_| cdi_.opcode.props[:saveip] and cdi_.next_addr == new_addr } cdi.block.add_to_subfuncret new_addr ndi.block.add_from_subfuncret cdi.address if ndi cdi.block.each_to_normal { |f| disassembler.function[f] ||= DecodedFunction.new if disassembler.di_at(f) } else di.block.add_to_normal new_addr ndi.block.add_from_normal from_addr if ndi end end
update the blocks links in the disassembler
trace_func_linkdasm
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-plugins/trace_func.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-plugins/trace_func.rb
BSD-3-Clause
def trace_func_newtrace(id) @trace_func_counter ||= {} @trace_func_counter[id] = 0 puts "start tracing #{Expression[id[0]]}" # setup a bg_color_callback on the disassembler if not defined? @trace_func_dasmcolor @trace_func_dasmcolor = true return if not disassembler.gui oldcb = disassembler.gui.bg_color_callback disassembler.gui.bg_color_callback = lambda { |addr| if oldcb and c = oldcb[addr] c elsif di = disassembler.di_at(addr) and di.block.list.first.comment.to_s =~ /functrace/ 'ff0' end } end end
############################################################################################### you can redefine the following functions in another plugin to handle trace events differently a new trace is about to begin
trace_func_newtrace
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-plugins/trace_func.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-plugins/trace_func.rb
BSD-3-Clause
def trace_func_add_block(id, blockaddr) @trace_func_counter[id] += 1 if di = disassembler.di_at(blockaddr) di.add_comment "functrace #{@trace_func_counter[id]}" end end
a new block is added to a trace
trace_func_add_block
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-plugins/trace_func.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-plugins/trace_func.rb
BSD-3-Clause
def trace_func_istraceend(id, di) if trace_subfuncs if @trace_terminate true elsif id[2] == 0 # trace VS func_trace elsif target = disassembler.get_xrefs_x(di)[0] # check the current return address against the one saved at trace start resolve(disassembler.normalize(target)) == id[2] end else true end end
the tracer is on a end-of-func instruction, should the trace end ?
trace_func_istraceend
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-plugins/trace_func.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-plugins/trace_func.rb
BSD-3-Clause
def trace_func_entersubfunc(id, di) if trace_subfuncs @trace_func_subfunccache ||= {} if not target = @trace_func_subfunccache[di.address] # even if the target is dynamic, its module should be static if target = disassembler.get_xrefs_x(di)[0] @trace_func_subfunccache[di.address] = target = resolve(disassembler.normalize(target)) end end # check if the target subfunction is in the same module as the main # XXX should check against the list of loaded modules etc # XXX call thunk_foo -> jmp [other_module] true if target.kind_of? Integer and target & 0xffc0_0000 == id[0] & 0xffc0_0000 else false end end
the tracer is on a subfunction call instruction, should it trace into or stepover ?
trace_func_entersubfunc
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-plugins/trace_func.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-plugins/trace_func.rb
BSD-3-Clause
def build_ctx(ctx) # create boxes todo = ctx.root_addrs.dup & @addr_struct.keys todo << @addr_struct.keys.first if todo.empty? done = [] while a = todo.shift next if done.include? a done << a ctx.new_box a, :line_text_col => [], :line_address => [], :line_struct => [], :line_member => [] todo.concat @heap.xrchunksto[a].to_a & @addr_struct.keys end # link boxes if (@heap.xrchunksto[ctx.box.first.id].to_a & @addr_struct.keys).length == ctx.box.length - 1 ot = ctx.box[0].id ctx.box[1..-1].each { |b_| ctx.link_boxes(ot, b_.id) } else ctx.box.each { |b| @heap.xrchunksto[b.id].to_a.each { |t| ctx.link_boxes(b.id, t) if @addr_struct[t] } } end if snapped @datadiff = {} end # calc box dimensions/text ctx.box.each { |b| colstr = [] curaddr = b.id curst = @addr_struct[b.id] curmb = nil margin = '' start_addr = curaddr if snapped ghosts = snapped[curaddr] end line = 0 render = lambda { |str, col| colstr << [str, col] } nl = lambda { b[:line_address][line] = curaddr b[:line_text_col][line] = colstr b[:line_struct][line] = curst b[:line_member][line] = curmb colstr = [] line += 1 } render_val = lambda { |v| if v.kind_of?(::Integer) if v > 0x100 render['0x%X' % v, :text] elsif v < -0x100 render['-0x%X' % -v, :text] else render[v.to_s, :text] end elsif not v render['NULL', :text] else render[v.to_s, :text] end } render_st = nil render_st_ar = lambda { |ast, m| elemt = m.type.untypedef.type.untypedef if elemt.kind_of?(C::BaseType) and elemt.name == :char render[margin, :text] render["#{m.type.type.to_s[1...-1]} #{m.name}[#{m.type.length}] = #{ast[m].to_array.pack('C*').sub(/\0.*$/m, '').inspect}", :text] nl[] curaddr += ast.cp.sizeof(m) else t = m.type.type.to_s[1...-1] tsz = ast.cp.sizeof(m.type.type) fust = curst fumb = curmb curst = ast[m] ast[m].to_array.each_with_index { |v, i| curmb = i render[margin, :text] if elemt.kind_of?(C::Union) if m.type.untypedef.type.kind_of?(C::Union) render[elemt.kind_of?(C::Struct) ? 'struct ' : 'union ', :text] render["#{elemt.name} ", :text] if elemt.name else # typedef render["#{elemt.to_s[1...-1]} ", :text] end render_st[v] render[" #{m.name}[#{i}]", :text] else render["#{t} #{m.name}[#{i}] = ", :text] render_val[v] @datadiff[curaddr] = true if ghosts and ghosts.all? { |g| g[curaddr-start_addr, tsz] == ghosts[0][curaddr-start_addr, tsz] } and ghosts[0][curaddr-start_addr, tsz] != ast.str[curaddr, tsz].to_str end render[';', :text] nl[] curaddr += tsz } curst = fust curmb = fumb end } render_st = lambda { |ast| st_addr = curaddr oldst = curst oldmb = curmb oldmargin = margin render['{', :text] nl[] margin += ' ' curst = ast ast.struct.members.each { |m| curmb = m curaddr = st_addr + ast.struct.offsetof(@heap.cp, m) if bo = ast.struct.bitoffsetof(@heap.cp, m) # float curaddr to make ghost hilight work on bitfields curaddr += (1+bo[0])/1000.0 end if m.type.untypedef.kind_of?(C::Array) render_st_ar[ast, m] elsif m.type.untypedef.kind_of?(C::Union) render[margin, :text] if m.type.kind_of?(C::Union) render[m.type.kind_of?(C::Struct) ? 'struct ' : 'union ', :text] render["#{m.type.name} ", :text] if m.type.name else # typedef render["#{m.type.to_s[1...-1]} ", :text] end oca = curaddr render_st[ast[m]] nca = curaddr curaddr = oca render[" #{m.name if m.name};", :text] nl[] curaddr = nca else render[margin, :text] render["#{m.type.to_s[1...-1]} ", :text] render["#{m.name} = ", :text] render_val[ast[m]] tsz = ast.cp.sizeof(m) # TODO bit-level multighosting if ghosts and ghosts.all? { |g| g[curaddr.to_i-start_addr, tsz] == ghosts[0][curaddr.to_i-start_addr, tsz] } and ghosts[0][curaddr.to_i-start_addr, tsz] != ast.str[curaddr.to_i, tsz].to_str if bo ft = C::BaseType.new((bo[0] + bo[1] > 32) ? :__int64 : :__int32) v1 = @heap.cp.decode_c_value(ghosts[0][curaddr.to_i-start_addr, tsz], ft, 0) v2 = @heap.cp.decode_c_value(ast.str[curaddr.to_i, tsz], ft, 0) @datadiff[curaddr] = true if (v1 >> bo[0]) & ((1 << bo[1])-1) != (v2 >> bo[0]) & ((1 << bo[1])-1) else @datadiff[curaddr] = true end end render[';', :text] if m.type.kind_of?(C::Pointer) and m.type.type.kind_of?(C::BaseType) and m.type.type.name == :char if s = @dasm.decode_strz(ast[m], 32) render[" // #{s.inspect}", :comment] end end nl[] curaddr += tsz curaddr = curaddr.to_i if bo end } margin = oldmargin curst = oldst curmb = oldmb render[margin, :text] render['}', :text] } ast = @addr_struct[curaddr] render["struct #{ast.struct.name} *#{'0x%X' % curaddr} = ", :text] render_st[ast] render[';', :text] nl[] 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 b.h = line * @font_height } end
create the graph objects in ctx
build_ctx
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-plugins/heapscan/graphheap.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-plugins/heapscan/graphheap.rb
BSD-3-Clause
def create_struct(addr) raise "no chunk here" if not @heap.chunks[addr] ptsz = @dasm.cpu.size/8 # check if this is a c++ object with RTTI info vptr = @dasm.decode_dword(addr) rtti = @dasm.decode_dword(vptr-ptsz) case OS.shortname when 'winos' typeinfo = @dasm.decode_dword(rtti+3*ptsz) if rtti if typeinfo and s = @dasm.decode_strz(typeinfo+3*ptsz) rtti_name = s[/^(.*)@@$/, 1] # remove trailing @@ end when 'linos' typeinfo = @dasm.decode_dword(rtti+ptsz) if rtti if typeinfo and s = @dasm.decode_strz(typeinfo) rtti_name = s[/^[0-9]+(.*)$/, 1] # remove leading number end end if rtti_name and st = @heap.cp.toplevel.struct[rtti_name] return @heap.chunk_struct[addr] = st end st = C::Struct.new st.name = rtti_name || "chunk_#{'%x' % addr}" st.members = [] li = 0 (@heap.chunks[addr] / ptsz).times { |i| n = 'unk_%x' % (ptsz*i) v = @dasm.decode_dword(addr+ptsz*i) if i == 0 and rtti_name t = C::Pointer.new(C::Pointer.new(C::BaseType.new(:void))) n = 'vtable' elsif @heap.chunks[v] t = C::Pointer.new(C::BaseType.new(:void)) else t = C::BaseType.new("__int#{ptsz*8}".to_sym, :unsigned) end st.members << C::Variable.new(n, t) li = i+1 } (@heap.chunks[addr] % ptsz).times { |i| n = 'unk_%x' % (ptsz*li+i) t = C::BaseType.new(:char, :unsigned) st.members << C::Variable.new(n, t) } @heap.cp.toplevel.struct[st.name] = st @heap.chunk_struct[addr] = st end
create the struct chunk_<addr>, register it in @heap.chunk_struct
create_struct
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-plugins/heapscan/graphheap.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-plugins/heapscan/graphheap.rb
BSD-3-Clause
def chunkdw(ptr, len=@chunks[ptr]) if base = find_range(ptr) dwcache(base, @range[base])[(ptr-base)/@ptsz, len/@ptsz] end end
return the array of dwords in the chunk
chunkdw
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-plugins/heapscan/heapscan.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-plugins/heapscan/heapscan.rb
BSD-3-Clause
def chunklist @chunklist ||= @chunks.keys.sort end
returns the list of chunks, sorted
chunklist
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-plugins/heapscan/heapscan.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-plugins/heapscan/heapscan.rb
BSD-3-Clause
def find_elem(ptr, len, list=nil) return ptr if len[ptr] list ||= len.keys.sort if list.length < 16 return list.find { |p| p <= ptr and p + len[p] > ptr } end window = list while window and not window.empty? i = window.length/2 wi = window[i] if ptr < wi window = window[0, i] elsif ptr < wi + len[wi] return wi else window = window[i+1, i] end end end
dichotomic search of the chunk containing ptr len = hash ptr => length list = list of hash keys sorted
find_elem
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-plugins/heapscan/heapscan.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-plugins/heapscan/heapscan.rb
BSD-3-Clause
def find_roots(adj=@xrchunksto) @roots = {} adj.keys.sort.each { |r| if not @roots[r] l = reachfrom(r, adj, @roots) l.each { |t| @roots[t] = true if adj[t] } # may include r !, also dont mark leaves @roots[r] = l end } @roots.delete_if { |k, v| v == true } end
find the root nodes that allow acces to most other nodes { root => [reachable nodes] } does not include single nodes (@chunks.keys - @xrchunksfrom.keys)
find_roots
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-plugins/heapscan/heapscan.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-plugins/heapscan/heapscan.rb
BSD-3-Clause
def graph_from(p, adj = @xrchunksto) hash = {} todo = [p] while p = todo.pop next if hash[p] if adj[p] hash[p] = adj[p] todo.concat hash[p] end end hash end
create a subset of xrchunksto from one point
graph_from
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-plugins/heapscan/heapscan.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-plugins/heapscan/heapscan.rb
BSD-3-Clause
def dump_graph(fname='graph.gv', graph=@xrchunksto) File.open(fname, 'w') { |fd| fd.puts "digraph foo {" graph.each { |b, l| fd.puts l.map { |e| '"%x" -> "%x";' % [b, e] } } fd.puts "}" } end
dump the whole graph in a dot file
dump_graph
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-plugins/heapscan/heapscan.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-plugins/heapscan/heapscan.rb
BSD-3-Clause
def scan_chunks_xr @xrchunksto = {} @xrchunksfrom = {} each_heap { |a, l, ar| scan_heap_xr(a, l) } @mmapchunks.each { |a| scan_mmap_xr(a, @chunks[a]) } end
scan all chunks for cross-references (one chunk contaning a pointer to some other chunk)
scan_chunks_xr
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-plugins/heapscan/heapscan.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-plugins/heapscan/heapscan.rb
BSD-3-Clause
def scan_heap(base, len, ar) dw = dwcache(base, len) ptr = 0 psz = dw[ptr] sz = dw[ptr+1] base += 2*@ptsz # user pointer raise "bad heap base %x %x %x %x" % [psz, sz, base, len] if psz != 0 or sz & 1 == 0 loop do clen = sz & -8 # chunk size ptr += clen/@ptsz # start of next chk break if ptr >= dw.length or clen == 0 sz = dw[ptr+1] if sz & 1 > 0 # pv_inuse # user data length up to chucksize-4 (over next psz) #puts "used #{'%x' % base} #{clen-@ptsz}" if $VERBOSE @chunks[base] = clen-@ptsz else #puts "free #{'%x' % base} #{clen-@ptsz}" if $VERBOSE end base += clen end del_fastbin(ar) end
scan chunks from a heap base addr
scan_heap
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-plugins/heapscan/heapscan.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-plugins/heapscan/heapscan.rb
BSD-3-Clause
def scan_mmap(base, len) foo = chunkdata(base) clen = foo[1] & ~0xfff if foo[0] == 0 and foo[1] & 0xfff == 2 and clen > 0 and clen <= len @chunks[base + foo.length] = clen-4*@ptsz @mmapchunks << (base + foo.length) clen end end
scan chunks from a mmap base addr big chunks are allocated on anonymous-mmap areas for mmap chunks, pv_sz=0 pv_inuse=0, mmap=1, data starts at 8, mmapsz = userlen+12 [roundup 4096] one entry in /proc/pid/maps may point to multiple consecutive mmap chunks scans for a mmap chunk header, returns the chunk size if pattern match or nil
scan_mmap
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-plugins/heapscan/heapscan.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-plugins/heapscan/heapscan.rb
BSD-3-Clause
def scan_libc(addr) raise 'no libc' if not addr return if @main_arena_ptr = @dbg.symbols.index('main_arena') unless trim = @dbg.symbols.index('malloc_trim') || @dbg.symbols.index('weak_malloc_trim') @dbg.loadsyms 'libc[.-]' trim = @dbg.symbols.index('malloc_trim') || @dbg.symbols.index('weak_malloc_trim') end raise 'cant find malloc_trim' if not trim d = @dbg.disassembler d.disassemble_fast(trim) if not d.di_at(trim) if d.block_at(trim).list.last.opcode.name == 'call' # x86 getip, need to dasm to have func_binding (cross fingers) d.disassemble d.block_at(trim).to_normal.first end d.each_function_block(trim) { |b| # mutex_lock(&main_arena.mutex) gives us the addr next if not cmpxchg = d.block_at(b).list.find { |di| di.kind_of? DecodedInstruction and di.opcode.name == 'cmpxchg' } @main_arena_ptr = d.backtrace(cmpxchg.instruction.args.first.symbolic.pointer, cmpxchg.address) if @main_arena_ptr.length == 1 @main_arena_ptr = @main_arena_ptr[0].reduce break end } raise "cant find mainarena" if not @main_arena_ptr.kind_of? Integer @dbg.symbols[@main_arena_ptr] = 'main_arena' end
we need to find the main_arena from the libc we do this by analysing 'malloc_trim'
scan_libc
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-plugins/heapscan/heapscan.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-plugins/heapscan/heapscan.rb
BSD-3-Clause
def scan_chunks_xr @xrchunksto = {} @xrchunksfrom = {} each_heap { |ar| scan_heap_xr(ar) } end
scan all chunks for cross-references (one chunk containing a pointer to some other chunk)
scan_chunks_xr
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-plugins/heapscan/heapscan.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-plugins/heapscan/heapscan.rb
BSD-3-Clause
def each_heap heaps.each { |a, l| ar = @cp.decode_c_struct('_HEAP', @dbg.memory, a) yield ar } end
yields the _HEAP structure for all heaps
each_heap
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-plugins/heapscan/heapscan.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-plugins/heapscan/heapscan.rb
BSD-3-Clause
def each_heap_segment(ar) ar.segments.to_array.compact.each { |a| sg = @cp.decode_c_struct('_HEAP_SEGMENT', @dbg.memory, a) skiplist = [] ptr = sg.uncommittedranges while ptr ucr = @cp.decode_c_struct('_HEAP_UNCOMMMTTED_RANGE', @dbg.memory, ptr) skiplist << [ucr.Address, ucr.Size] ptr = ucr.Next end ptr = sg.firstentry # XXX lastentryinsegment == firstentry ??? # lastvalidentry = address of the end of the segment (may point to unmapped space) ptrend = sg.lastvalidentry skiplist.delete_if { |sa, sl| sa < ptr or sa + sl > ptrend } skiplist << [ptrend, 1] skiplist.sort.each { |sa, sl| yield(ptr, sa-ptr) ptr = sa + sl } } end
yields all [ptr, len] for allocated segments of a _HEAP this maps to the _HEAP_SEGMENT further subdivised to skip the _HEAP_UNCOMMMTTED_RANGE areas for the last chunk of the _HEAP_SEGMENT, only yield up to chunk_header
each_heap_segment
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-plugins/heapscan/heapscan.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-plugins/heapscan/heapscan.rb
BSD-3-Clause
def each_listentry(le, st, off=0) ptr0 = le.stroff ptr = le.flink while ptr != ptr0 yield @cp.decode_c_struct(st, @dbg.memory, ptr-off) ptr = @cp.decode_c_struct('_LIST_ENTRY', @dbg.memory, ptr).flink end end
call with a LIST_ENTRY allocstruct, the target structure and LE offset in this structure
each_listentry
ruby
stephenfewer/grinder
node/lib/metasm/samples/dbg-plugins/heapscan/heapscan.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/samples/dbg-plugins/heapscan/heapscan.rb
BSD-3-Clause
def initialize(tag:, classes: nil, **system_arguments) @tag = tag @system_arguments = validate_arguments(tag: tag, **system_arguments) @result = Primer::Classify.call(**@system_arguments.merge(classes: classes)) @trim = !!@system_arguments.delete(:trim) @system_arguments[:"data-view-component"] = true # Filter out Primer keys so they don't get assigned as HTML attributes @content_tag_args = add_test_selector(@system_arguments).except(*Primer::Classify::Utilities::UTILITIES.keys) end
## HTML attributes Use system arguments to add HTML attributes to elements. For the most part, system arguments map 1:1 to HTML attributes. For example, `render(Component.new(title: "Foo"))` will result in eg. `<div title="foo">`. However, ViewComponents applies special handling to certain system arguments. See the table below for details. | Name | Type | Description | | :- | :- | :- | | `aria` | `Hash` | Aria attributes: `aria: { label: "foo" }` renders `aria-label='foo'`. | | `data` | `Hash` | Data attributes: `data: { foo: :bar }` renders `data-foo='bar'`. | ## Utility classes ViewComponents provides a convenient way to add Primer CSS utility classes to HTML elements. Use the shorthand documented in the tables below instead of adding CSS classes directly. ### Animation | Name | Type | Description | | :- | :- | :- | | `animation` | Symbol | <%= one_of(Primer::Classify::Utilities.mappings(:animation)) %> | ### Border | Name | Type | Description | | :- | :- | :- | | `border_bottom` | Integer | Set to `0` to remove the bottom border. | | `border_left` | Integer | Set to `0` to remove the left border. | | `border_radius` | Integer | <%= one_of([0, 1, 2, 3]) %> | | `border_right` | Integer | Set to `0` to remove the right border. | | `border_top` | Integer | Set to `0` to remove the top border. | | `border` | Symbol | <%= one_of([:left, :top, :bottom, :right, :y, :x, true]) %> | | `box_shadow` | Boolean, Symbol | Box shadow. <%= one_of([true, :medium, :large, :extra_large, :none]) %> | ### Color | Name | Type | Description | | :- | :- | :- | | `bg` | Symbol | Background color. <%= one_of(Primer::Classify::Utilities.mappings(:bg)) %> | | `border_color` | Symbol | Border color. <%= one_of(Primer::Classify::Utilities.mappings(:border_color)) %> | | `color` | Symbol | Text color. <%= one_of(Primer::Classify::Utilities.mappings(:color)) %> | ### Flex | Name | Type | Description | | :- | :- | :- | | `align_items` | Symbol | <%= one_of(Primer::Classify::FLEX_ALIGN_ITEMS_VALUES) %> | | `align_self` | Symbol | <%= one_of(Primer::Classify::FLEX_ALIGN_SELF_VALUES) %> | | `direction` | Symbol | <%= one_of(Primer::Classify::FLEX_DIRECTION_VALUES) %> | | `flex` | Integer, Symbol | <%= one_of(Primer::Classify::FLEX_VALUES) %> | | `flex_grow` | Integer | To enable, set to `0`. | | `flex_shrink` | Integer | To enable, set to `0`. | | `flex_wrap` | Symbol | <%= one_of(Primer::Classify::FLEX_WRAP_MAPPINGS.keys) %> | | `justify_content` | Symbol | <%= one_of(Primer::Classify::FLEX_JUSTIFY_CONTENT_VALUES) %> | ### Grid | Name | Type | Description | | :- | :- | :- | | `clearfix` | Boolean | Whether to assign the `clearfix` class. | | `col` | Integer | Number of columns. <%= one_of(Primer::Classify::Utilities.mappings(:col)) %> | | `container` | Symbol | Size of the container. <%= one_of(Primer::Classify::Utilities.mappings(:container)) %> | ### Layout | Name | Type | Description | | :- | :- | :- | | `display` | Symbol | <%= one_of(Primer::Classify::Utilities.mappings(:display)) %> | | `w` | Symbol | Sets the element's width. <%= one_of(Primer::Classify::Utilities.mappings(:w)) %> | | `h` | Symbol | Sets the element's height. One of `:fit` or `:full`. | | `hide` | Symbol | Hide the element at a specific breakpoint. <%= one_of(Primer::Classify::Utilities.mappings(:hide)) %> | | `visibility` | Symbol | Visibility. <%= one_of(Primer::Classify::Utilities.mappings(:visibility)) %> | | `vertical_align` | Symbol | <%= one_of(Primer::Classify::Utilities.mappings(:vertical_align)) %> | ### Position | Name | Type | Description | | :- | :- | :- | | `bottom` | Boolean | If `false`, sets `bottom: 0`. | | `float` | Symbol | <%= one_of(Primer::Classify::Utilities.mappings(:float)) %> | | `left` | Boolean | If `false`, sets `left: 0`. | | `position` | Symbol | <%= one_of(Primer::Classify::Utilities.mappings(:position)) %> | | `right` | Boolean | If `false`, sets `right: 0`. | | `top` | Boolean | If `false`, sets `top: 0`. | ### Spacing | Name | Type | Description | | :- | :- | :- | | `m` | Integer | Margin. <%= one_of(Primer::Classify::Utilities.mappings(:m)) %> | | `mb` | Integer | Margin bottom. <%= one_of(Primer::Classify::Utilities.mappings(:mb)) %> | | `ml` | Integer | Margin left. <%= one_of(Primer::Classify::Utilities.mappings(:ml)) %> | | `mr` | Integer | Margin right. <%= one_of(Primer::Classify::Utilities.mappings(:mr)) %> | | `mt` | Integer | Margin top. <%= one_of(Primer::Classify::Utilities.mappings(:mt)) %> | | `mx` | Integer | Horizontal margins. <%= one_of(Primer::Classify::Utilities.mappings(:mx)) %> | | `my` | Integer | Vertical margins. <%= one_of(Primer::Classify::Utilities.mappings(:my)) %> | | `p` | Integer | Padding. <%= one_of(Primer::Classify::Utilities.mappings(:p)) %> | | `pb` | Integer | Padding bottom. <%= one_of(Primer::Classify::Utilities.mappings(:pb)) %> | | `pl` | Integer | Padding left. <%= one_of(Primer::Classify::Utilities.mappings(:pl)) %> | | `pr` | Integer | Padding right. <%= one_of(Primer::Classify::Utilities.mappings(:pr)) %> | | `pt` | Integer | Padding top. <%= one_of(Primer::Classify::Utilities.mappings(:pt)) %> | | `px` | Integer | Horizontal padding. <%= one_of(Primer::Classify::Utilities.mappings(:px)) %> | | `py` | Integer | Vertical padding. <%= one_of(Primer::Classify::Utilities.mappings(:py)) %> | ### Typography | Name | Type | Description | | :- | :- | :- | | `font_family` | Symbol | Font family. <%= one_of([:mono]) %> | | `font_size` | String, Integer, Symbol | <%= one_of(["00", 0, 1, 2, 3, 4, 5, 6, :small, :normal]) %> | | `font_style` | Symbol | Font style. <%= one_of([:italic]) %> | | `font_weight` | Symbol | Font weight. <%= one_of([:light, :normal, :bold, :emphasized]) %> | | `text_align` | Symbol | Text alignment. <%= one_of([:left, :right, :center]) %> | | `text_transform` | Symbol | Text transformation. <%= one_of([:uppercase, :capitalize]) %> | | `underline` | Boolean | Whether text should be underlined. | | `word_break` | Symbol | Whether to break words on line breaks. <%= one_of(Primer::Classify::Utilities.mappings(:word_break)) %> | ### Other | Name | Type | Description | | :- | :- | :- | | classes | String | CSS class name value to be concatenated with generated Primer CSS classes. | | test_selector | String | Adds `data-test-selector='given value'` in non-Production environments for testing purposes. | | trim | Boolean | Calls `strip` on the content to remove trailing and leading white spaces. |
initialize
ruby
primer/view_components
app/components/primer/base_component.rb
https://github.com/primer/view_components/blob/master/app/components/primer/base_component.rb
MIT
def initialize( title: "", title_tag: :h3, icon: "", icon_size: :medium, image_src: "", image_alt: " ", description: "", button_text: "", button_url: "", button_classes: "btn-primary my-3", link_text: "", link_url: "", # variations narrow: false, large: false, spacious: false, **system_arguments ) @system_arguments = system_arguments @system_arguments[:tag] = :div @system_arguments[:classes] = class_names( @system_arguments[:classes], "blankslate", "blankslate-narrow": narrow, "blankslate-large": large, "blankslate-spacious": spacious ) @title_tag = title_tag @icon = icon @icon_size = icon_size @image_src = image_src @image_alt = image_alt @title = title @description = description @button_text = button_text @button_url = button_url @button_classes = button_classes @link_text = link_text @link_url = link_url end
@param title [String] Text that appears in a larger bold font. @param title_tag [Symbol] HTML tag to use for title. @param icon [Symbol] Octicon icon to use at top of component. @param icon_size [Symbol] <%= one_of(Primer::Beta::Octicon::SIZE_MAPPINGS, sort: false) %> @param image_src [String] Image to display. @param image_alt [String] Alt text for image. @param description [String] Text that appears below the title. Typically a whole sentence. @param button_text [String] The text of the button. @param button_url [String] The URL where the user will be taken after clicking the button. @param button_classes [String] Classes to apply to action button @param link_text [String] The text of the link. @param link_url [String] The URL where the user will be taken after clicking the link. @param narrow [Boolean] Adds a maximum width. @param large [Boolean] Increases the font size. @param spacious [Boolean] Adds extra padding. @param system_arguments [Hash] <%= link_to_system_arguments_docs %>
initialize
ruby
primer/view_components
app/components/primer/blankslate_component.rb
https://github.com/primer/view_components/blob/master/app/components/primer/blankslate_component.rb
MIT
def initialize( scheme: DEFAULT_SCHEME, variant: nil, size: DEFAULT_SIZE, group_item: false, block: false, dropdown: false, **system_arguments ) @scheme = scheme @dropdown = dropdown @system_arguments = system_arguments @id = @system_arguments[:id] @system_arguments[:classes] = class_names( system_arguments[:classes], SCHEME_MAPPINGS[fetch_or_fallback(SCHEME_OPTIONS, scheme, DEFAULT_SCHEME)], SIZE_MAPPINGS[fetch_or_fallback(SIZE_OPTIONS, variant || size, DEFAULT_SIZE)], "btn" => !link?, "btn-block" => block, "BtnGroup-item" => group_item ) end
@param scheme [Symbol] <%= one_of(Primer::ButtonComponent::SCHEME_OPTIONS) %> @param variant [Symbol] DEPRECATED. <%= one_of(Primer::ButtonComponent::SIZE_OPTIONS) %> @param size [Symbol] <%= one_of(Primer::ButtonComponent::SIZE_OPTIONS) %> @param tag [Symbol] (Primer::Beta::BaseButton::DEFAULT_TAG) <%= one_of(Primer::Beta::BaseButton::TAG_OPTIONS) %> @param type [Symbol] (Primer::Beta::BaseButton::DEFAULT_TYPE) <%= one_of(Primer::Beta::BaseButton::TYPE_OPTIONS) %> @param group_item [Boolean] Whether button is part of a ButtonGroup. @param block [Boolean] Whether button is full-width with `display: block`. @param dropdown [Boolean] Whether or not to render a dropdown caret. @param system_arguments [Hash] <%= link_to_system_arguments_docs %>
initialize
ruby
primer/view_components
app/components/primer/button_component.rb
https://github.com/primer/view_components/blob/master/app/components/primer/button_component.rb
MIT
def initialize(condition:, component: Primer::BaseComponent, **base_component_arguments) @condition = condition @component = component @base_component_arguments = base_component_arguments @trim = !!@base_component_arguments.delete(:trim) end
@param condition [Boolean] Whether or not to wrap the content in a component. @param component [Class] The component class to use as a wrapper, defaults to `Primer::BaseComponent` @param base_component_arguments [Hash] The arguments to pass to the component.
initialize
ruby
primer/view_components
app/components/primer/conditional_wrapper.rb
https://github.com/primer/view_components/blob/master/app/components/primer/conditional_wrapper.rb
MIT
def initialize(icon:, scheme: DEFAULT_SCHEME, box: false, tooltip_direction: Primer::Alpha::Tooltip::DIRECTION_DEFAULT, **system_arguments) @icon = icon @system_arguments = system_arguments @system_arguments[:id] ||= self.class.generate_id @system_arguments[:classes] = class_names( "btn-octicon", SCHEME_MAPPINGS[fetch_or_fallback(SCHEME_OPTIONS, scheme, DEFAULT_SCHEME)], system_arguments[:classes], "Box-btn-octicon" => box ) validate_aria_label @aria_label = aria("label", @system_arguments) @aria_description = aria("description", @system_arguments) @tooltip_arguments = { for_id: @system_arguments[:id], direction: tooltip_direction } # If we have both an `aria-label` and a `aria-description`, we create a `Tooltip` with the description type and keep the `aria-label` in the button. # Otherwise, the `aria-label` is used as the tooltip text, which is the `aria-labelled-by` of the button, so we don't set it in the button. if @aria_label.present? && @aria_description.present? @system_arguments.delete(:"aria-description") @system_arguments[:aria].delete(:description) if @system_arguments.include?(:aria) @tooltip_arguments[:text] = @aria_description @tooltip_arguments[:type] = :description else @system_arguments.delete(:"aria-label") @system_arguments[:aria].delete(:label) if @system_arguments.include?(:aria) @tooltip_arguments[:text] = @aria_label @tooltip_arguments[:type] = :label end end
@param scheme [Symbol] <%= one_of(Primer::IconButton::SCHEME_OPTIONS) %> @param icon [String] Name of <%= link_to_octicons %> to use. @param tag [Symbol] <%= one_of(Primer::Beta::BaseButton::TAG_OPTIONS) %> @param type [Symbol] <%= one_of(Primer::Beta::BaseButton::TYPE_OPTIONS) %> @param aria-label [String] String that can be read by assistive technology. A label should be short and concise. See the accessibility section for more information. @param aria-description [String] String that can be read by assistive technology. A description can be longer as it is intended to provide more context and information. See the accessibility section for more information. @param tooltip_direction [Symbol] (Primer::Alpha::Tooltip::DIRECTION_DEFAULT) <%= one_of(Primer::Alpha::Tooltip::DIRECTION_OPTIONS) %> @param box [Boolean] Whether the button is in a <%= link_to_component(Primer::Beta::BorderBox) %>. If `true`, the button will have the `Box-btn-octicon` class. @param system_arguments [Hash] <%= link_to_system_arguments_docs %>
initialize
ruby
primer/view_components
app/components/primer/icon_button.rb
https://github.com/primer/view_components/blob/master/app/components/primer/icon_button.rb
MIT
def initialize(responsive: false, side: DEFAULT_SIDE, sidebar_col: DEFAULT_SIDEBAR_COL, **system_arguments) @system_arguments = system_arguments @side = fetch_or_fallback(ALLOWED_SIDES, side, DEFAULT_SIDE) @responsive = responsive @system_arguments[:classes] = class_names( "gutter-condensed gutter-lg", @system_arguments[:classes] ) @system_arguments[:direction] = responsive ? [:column, nil, :row] : nil @system_arguments[:display] = :flex @system_arguments[:tag] = :div @sidebar_col = fetch_or_fallback(ALLOWED_SIDEBAR_COLS, sidebar_col, DEFAULT_SIDEBAR_COL) @main_col = MAX_COL - @sidebar_col end
@param responsive [Boolean] Whether to collapse layout to a single column at smaller widths. @param side [Symbol] Which side to display the sidebar on. <%= one_of(Primer::LayoutComponent::ALLOWED_SIDES) %> @param sidebar_col [Integer] Sidebar column width. @param system_arguments [Hash] <%= link_to_system_arguments_docs %>
initialize
ruby
primer/view_components
app/components/primer/layout_component.rb
https://github.com/primer/view_components/blob/master/app/components/primer/layout_component.rb
MIT
def initialize( label:, direction: DIRECTION_DEFAULT, align: ALIGN_DEFAULT, multiline: MULTILINE_DEFAULT, no_delay: DELAY_DEFAULT, **system_arguments ) @system_arguments = system_arguments @system_arguments[:tag] ||= :span # rubocop:disable Primer/NoTagMemoize @system_arguments[:aria] = { label: label } @system_arguments[:skip_aria_label_check] = true @system_arguments[:classes] = class_names( @system_arguments[:classes], "tooltipped", "tooltipped-#{fetch_or_fallback(DIRECTION_OPTIONS, direction, DIRECTION_DEFAULT)}", ALIGN_MAPPING[fetch_or_fallback(ALIGN_MAPPING.keys, align, ALIGN_DEFAULT)], "tooltipped-no-delay" => fetch_or_fallback_boolean(no_delay, DELAY_DEFAULT), "tooltipped-multiline" => fetch_or_fallback_boolean(multiline, MULTILINE_DEFAULT) ) end
@param label [String] the text to appear in the tooltip @param direction [String] Direction of the tooltip. <%= one_of(Primer::Tooltip::DIRECTION_OPTIONS) %> @param align [String] Align tooltips to the left or right of an element, combined with a `direction` to specify north or south. <%= one_of(Primer::Tooltip::ALIGN_MAPPING.keys) %> @param multiline [Boolean] Use this when you have long content @param no_delay [Boolean] By default the tooltips have a slight delay before appearing. Set true to override this @param system_arguments [Hash] <%= link_to_system_arguments_docs %>
initialize
ruby
primer/view_components
app/components/primer/tooltip.rb
https://github.com/primer/view_components/blob/master/app/components/primer/tooltip.rb
MIT
def initialize(tag: DEFAULT_TAG, inline: false, expandable: false, max_width: nil, **system_arguments) @system_arguments = system_arguments @system_arguments[:tag] = fetch_or_fallback(TAG_OPTIONS, tag, DEFAULT_TAG) @system_arguments[:classes] = class_names( @system_arguments[:classes], "css-truncate", "css-truncate-overflow" => !inline, "css-truncate-target" => inline, "expandable" => inline && expandable ) @system_arguments[:style] = join_style_arguments(@system_arguments[:style], "max-width: #{max_width}px;") unless max_width.nil? end
@param tag [Symbol] <%= one_of(Primer::Truncate::TAG_OPTIONS) %> @param inline [Boolean] Whether the element is inline (or inline-block). @param expandable [Boolean] Whether the entire string should be revealed on hover. Can only be used in conjunction with `inline`. @param max_width [Integer] Sets the max-width of the text. @param system_arguments [Hash] <%= link_to_system_arguments_docs %>
initialize
ruby
primer/view_components
app/components/primer/truncate.rb
https://github.com/primer/view_components/blob/master/app/components/primer/truncate.rb
MIT
def initialize(size: Primer::Alpha::ActionBar::DEFAULT_SIZE, overflow_menu: true, **system_arguments) @system_arguments = system_arguments @overflow_menu = overflow_menu @size = fetch_or_fallback(Primer::Alpha::ActionBar::SIZE_OPTIONS, size, Primer::Alpha::ActionBar::DEFAULT_SIZE) @system_arguments[:classes] = class_names( system_arguments[:classes], "ActionBar", SIZE_MAPPINGS[@size] ) @system_arguments[:role] = "toolbar" return unless overflow_menu @action_menu = Primer::Alpha::ActionMenu.new( menu_id: self.class.generate_id, "data-target": "action-bar.moreMenu", hidden: true, classes: "ActionBar-more-menu", anchor_align: :end ) end
@param size [Symbol] <%= one_of(Primer::Alpha::ActionBar::SIZE_OPTIONS) %> @param overflow_menu [Boolean] Whether to render the overflow menu. @param system_arguments [Hash] <%= link_to_system_arguments_docs %>
initialize
ruby
primer/view_components
app/components/primer/alpha/action_bar.rb
https://github.com/primer/view_components/blob/master/app/components/primer/alpha/action_bar.rb
MIT
def initialize( id: self.class.generate_id, role: nil, item_classes: nil, scheme: DEFAULT_SCHEME, show_dividers: false, aria_selection_variant: DEFAULT_ARIA_SELECTION_VARIANT, select_variant: DEFAULT_SELECT_VARIANT, form_arguments: {}, **system_arguments ) @system_arguments = system_arguments @id = id @system_arguments[:id] = @id @system_arguments[:tag] = :ul @item_classes = item_classes @scheme = fetch_or_fallback(SCHEME_OPTIONS, scheme, DEFAULT_SCHEME) @show_dividers = show_dividers @select_variant = select_variant @aria_selection_variant = aria_selection_variant @system_arguments[:classes] = class_names( SCHEME_MAPPINGS[@scheme], system_arguments[:classes], "ActionListWrap", "ActionListWrap--divided" => @show_dividers ) @role = role || (allows_selection? ? MENU_ROLE : DEFAULT_ROLE) @system_arguments[:role] = @role @list_wrapper_arguments = {} @form_builder = form_arguments[:builder] @input_name = form_arguments[:name] return unless required_form_arguments_given? && !allows_selection? raise ArgumentError, "lists/menus that act as form inputs must also allow item selection (please pass the `select_variant:` option)" end
@param id [String] HTML ID value. @param role [Boolean] ARIA role describing the function of the list. listbox and menu are a common values. @param item_classes [String] Additional CSS classes to attach to items. @param scheme [Symbol] <%= one_of(Primer::Alpha::ActionList::SCHEME_OPTIONS) %> `inset` children are offset (vertically and horizontally) from list edges. `full` (default) children are flush (vertically and horizontally) with list edges. @param show_dividers [Boolean] Display a divider above each item in the list when it does not follow a header or divider. @param select_variant [Symbol] How items may be selected in the list. <%= one_of(Primer::Alpha::ActionList::SELECT_VARIANT_OPTIONS) %> @param aria_selection_variant [Symbol] Specifies which aria selection to use. <%= one_of(Primer::Alpha::ActionList::ARIA_SELECTION_VARIANT_OPTIONS) %> @param form_arguments [Hash] Allows an `ActionList` to act as a select list in multi- and single-select modes. Pass the `builder:` and `name:` options to this hash. `builder:` should be an instance of `ActionView::Helpers::FormBuilder`, which are created by the standard Rails `#form_with` and `#form_for` helpers. The `name:` option is the desired name of the field that will be included in the params sent to the server on form submission. *NOTE*: Consider using an <%= link_to_component(Primer::Alpha::ActionMenu) %> instead of using this feature directly. @param system_arguments [Hash] <%= link_to_system_arguments_docs %>
initialize
ruby
primer/view_components
app/components/primer/alpha/action_list.rb
https://github.com/primer/view_components/blob/master/app/components/primer/alpha/action_list.rb
MIT
def build_item(component_klass: ActionList::Item, **system_arguments) if single_select? && system_arguments[:active] && items.count(&:active?).positive? raise ArgumentError, "only a single item may be active when select_variant is set to :single" end # rubocop:enable Style/IfUnlessModifier system_arguments[:classes] = class_names( @item_classes, system_arguments[:classes] ) component_klass.new(list: self, **system_arguments) end
Builds a new item but does not add it to the list. Use this method instead of the `#with_item` slot if you need to render an item outside the context of a list, eg. if rendering additional items to append to an existing list, perhaps via a separate HTTP request. @param component_klass [Class] The class to use instead of the default <%= link_to_component(Primer::Alpha::ActionList::Item) %> @param system_arguments [Hash] These arguments are forwarded to <%= link_to_component(Primer::Alpha::ActionList::Item) %>, or whatever class is passed as the `component_klass` argument.
build_item
ruby
primer/view_components
app/components/primer/alpha/action_list.rb
https://github.com/primer/view_components/blob/master/app/components/primer/alpha/action_list.rb
MIT
def build_avatar_item(src:, username:, full_name: nil, full_name_scheme: Primer::Alpha::ActionList::Item::DEFAULT_DESCRIPTION_SCHEME, component_klass: ActionList::Item, avatar_arguments: {}, **system_arguments) build_item(label: username, description_scheme: full_name_scheme, component_klass: component_klass, **system_arguments).tap do |item| item.with_leading_visual_raw_content do # no alt text necessary for presentational item item.render(Primer::Beta::Avatar.new(src: src, **avatar_arguments, role: :presentation, size: 16)) end item.with_description_content(full_name) if full_name end end
Builds a new avatar item but does not add it to the list. Avatar items are a convenient way to accessibly add an item with a leading avatar image. Use this method instead of the `#with_avatar_item` slot if you need to render an avatar item outside the context of a list, eg. if rendering additional items to append to an existing list, perhaps via a separate HTTP request. @param src [String] The source url of the avatar image. @param username [String] The username associated with the avatar. @param full_name [String] Optional. The user's full name. @param full_name_scheme [Symbol] Optional. How to display the user's full name. <%= one_of(Primer::Alpha::ActionList::Item::DESCRIPTION_SCHEME_OPTIONS) %> @param component_klass [Class] The class to use instead of the default <%= link_to_component(Primer::Alpha::ActionList::Item) %> @param avatar_arguments [Hash] Optional. The arguments accepted by <%= link_to_component(Primer::Beta::Avatar) %> @param system_arguments [Hash] These arguments are forwarded to <%= link_to_component(Primer::Alpha::ActionList::Item) %>, or whatever class is passed as the `component_klass` argument.
build_avatar_item
ruby
primer/view_components
app/components/primer/alpha/action_list.rb
https://github.com/primer/view_components/blob/master/app/components/primer/alpha/action_list.rb
MIT