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 parse_new_label(base='', src=nil) parse_init label = new_label(base) @cursource << Label.new(label) parse src label end
create a new label from base, parse it (incl optionnal additionnal src) returns the new label name
parse_new_label
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse.rb
BSD-3-Clause
def parse_parser_instruction(tok) case tok.raw.downcase when '.align' e = Expression.parse(@lexer).reduce raise self, 'need immediate alignment size' unless e.kind_of? ::Integer @lexer.skip_space if ntok = @lexer.readtok and ntok.type == :punct and ntok.raw == ',' @lexer.skip_space_eol # allow s...
handles special directives (alignment, changing section, ...) special directives start with a dot
parse_parser_instruction
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse.rb
BSD-3-Clause
def readop(lexer) if not tok = lexer.readtok or tok.type != :punct lexer.unreadtok tok return end if tok.value if OP_PRIO[tok.value] return tok else lexer.unreadtok tok return end end op = tok case op.raw # may be followed by itself or '=' when '>', '<' i...
reads an operator from the lexer, returns the corresponding symbol or nil
readop
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse.rb
BSD-3-Clause
def parse_num_value(lexer, tok) if not tok.value and tok.raw =~ /^[a-f][0-9a-f]*h$/i # warn on variable name like ffffh puts "W: Parser: you may want to add a leading 0 to #{tok.raw.inspect} at #{tok.backtrace[-2]}:#{tok.backtrace[-1]}" if $VERBOSE end return if tok.value return if tok.raw[0] != ?....
parses floats/hex into tok.value, returns nothing does not parse unary operators (-/+/~)
parse_num_value
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse.rb
BSD-3-Clause
def parse_value(lexer) nil while tok = lexer.readtok and tok.type == :space return if not tok case tok.type when :string # ignores the 'offset' word if followed by a string if not tok.value and tok.raw.downcase == 'offset' nil while ntok = lexer.readtok and ntok.type == :space if ntok.type...
returns the next value from lexer (parenthesised expression, immediate, variable, unary operators)
parse_value
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse.rb
BSD-3-Clause
def parse(lexer) opstack = [] stack = [] return if not e = parse_value(lexer) stack << e while op = readop(lexer) nil while ntok = lexer.readtok and (ntok.type == :space or ntok.type == :eol) lexer.unreadtok ntok until opstack.empty? or OP_PRIO[op.value][opstack.last] stack << new(ops...
for boolean operators, true is 1 (or anything != 0), false is 0
parse
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse.rb
BSD-3-Clause
def parse_string!(str, &b) pp = Preprocessor.new(str) e = parse(pp, &b) # update arg len = pp.pos pp.queue.each { |t| len -= t.raw.length } str[0, len] = '' e end
parse an expression in a string updates the string to point after the parsed expression
parse_string!
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse.rb
BSD-3-Clause
def parse_attributes(parser, allow_declspec = false) while tok = parser.skipspaces and tok.type == :string case keyword = tok.raw when '__attribute__', '__declspec' # synonymous: __attribute__((foo)) == __declspec(foo) raise tok || parser if not tok = parser.skipspaces or tok.type != :punct or tok....
parses a sequence of __attribute__((anything)) into self.attributes (array of string)
parse_attributes
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def has_attribute(attr) attributes.to_a.include? attr end
checks if the object has an attribute in its attribute list
has_attribute
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def add_attribute(attr) (@attributes ||= []) << attr if not has_attribute(attr) end
adds an attribute to the object attribute list if it is not already in it
add_attribute
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def has_attribute_var(attr) $1 if attributes.to_a.find { |a| a =~ /^#{attr}\((.*)\)$/ } end
checks if the object has an attributes a la __attribute__((attr(stuff))), returns 'stuff' (raw, no split on ',' or anything)
has_attribute_var
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def compare_deep(o, seen = []) return true if o.object_id == self.object_id return if o.class != self.class or o.name != self.name or o.attributes != self.attributes o.members.to_a.zip(self.members.to_a).each { |om, sm| return if om.name != sm.name return if om.type != sm.type if om.type.pointer? ...
compare to another structure, comparing members recursively (names and type) returns true if the self is same as o
compare_deep
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def update_member_cache(parser) @fldlist = {} @members.to_a.each { |m| @fldlist[m.name] = m if m.name } end
updates the @fldoffset / @fldbitoffset hash storing the offset of members
update_member_cache
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def parse_initializer_designator(parser, scope, value, idx, root=true) if nt = parser.skipspaces and nt.type == :punct and nt.raw == '.' and nnt = parser.skipspaces and nnt.type == :string and findmember(nnt.raw) raise nnt, 'unhandled indirect initializer' if not nidx = @members.index(@members.find { |...
parses a designator+initializer eg '.toto = 4' or '.tutu[42][12].bla = 16' or (root ? '4' : '=4')
parse_initializer_designator
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def expand_member_offset(c_parser, off, str) # XXX choose in members, check sizeof / prefer structs m = @members.first str << '.' << m.name if m.name if m.type.respond_to?(:expand_member_offset) m.type.expand_member_offset(c_parser, off, str) else m.type end end
resolve structptr + offset into 'str.membername' handles 'var.substruct1.array[12].foo' updates str returns the final member type itself works for Struct/Union/Array
expand_member_offset
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def bitoffsetof(parser, name) raise parser, 'undefined structure' if not members update_member_cache(parser) if not fldlist return @fldbitoffset[name] if fldbitoffset and @fldbitoffset[name] return @fldbitoffset[name.name] if fldbitoffset and name.respond_to?(:name) and @fldbitoffset[name.name] return if...
returns the [bitoffset, bitlength] of the field if it is a bitfield this should be added to the offsetof(field)
bitoffsetof
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def findmember_atoffset(parser, off) return if not members update_member_cache(parser) if not fldlist if m = @fldoffset.index(off) @fldlist[m] end end
returns the @member element that has offsetof(m) == off
findmember_atoffset
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def update_member_cache(parser) super(parser) @fldoffset = {} @fldbitoffset = {} if fldbitoffset al = align(parser) off = 0 bit_off = 0 isz = nil @members.each_with_index { |m, i| if bits and b = @bits[i] if not isz mal = [m.type.align(parser), al].min off = (off + mal - ...
updates the @fldoffset / @fldbitoffset hash storing the offset of members
update_member_cache
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def parse_initializer_designator(parser, scope, value, idx, root=true) # root = true for 1st invocation (x = { 4 }) => immediate value allowed # or false for recursive invocations (x = { .y = 4 }) => need '=' sign before immediate if nt = parser.skipspaces and nt.type == :punct and nt.raw == '[' if not ro...
parses a designator+initializer eg '[12] = 4' or '[42].bla = 16' or '[3 ... 8] = 28'
parse_initializer_designator
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def replace(o) @lexpr, @op, @rexpr, @type = o.lexpr, o.op, o.rexpr, o.type self end
overwrites @lexpr @op @rexpr @type from the arg
replace
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def deep_dup n = dup n.lexpr = n.lexpr.deep_dup if n.lexpr.kind_of? CExpression n.rexpr = n.rexpr.deep_dup if n.rexpr.kind_of? CExpression n.rexpr = n.rexpr.map { |e| e.kind_of?(CExpression) ? e.deep_dup : e } if n.rexpr.kind_of? ::Array n end
deep copy of the object recurses only within CExpressions, anything else is copied by reference
deep_dup
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def parse(text=nil, filename='<unk>', lineno=1) @lexer.feed text, filename, lineno if text nil while not @lexer.eos? and (parse_definition(@toplevel) or parse_toplevel_statement(@toplevel)) raise @lexer.readtok || self, 'invalid definition' if not @lexer.eos? sanity_checks self end
parses the current lexer content (or the text arg) for toplevel definitions
parse
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def initialize(*args) model = args.grep(Symbol).first || :ilp32 lexer = args.grep(Preprocessor).first || Preprocessor.new @program = args.grep(ExeFormat).first cpu = args.grep(CPU).first cpu ||= @program.cpu if @program @lexer = lexer @prev_pragma_callback = @lexer.pragma_callback @lexer.pragma_...
allowed arguments: ExeFormat, CPU, Preprocessor, Symbol (for the data model)
initialize
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def check_compatible_type(tok, oldtype, newtype, strict = false, checked = []) return if not $VERBOSE oldtype = oldtype.untypedef newtype = newtype.untypedef oldtype = BaseType.new(:int) if oldtype.kind_of? Enum newtype = BaseType.new(:int) if newtype.kind_of? Enum puts tok.exception('type qualifier ...
checks that the types are compatible (variable predeclaration, function argument..) strict = false for func call/assignment (eg char compatible with int -- but int is incompatible with char) output warnings only
check_compatible_type
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def readtok_longstr if t = @lexer.readtok and t.type == :string and t.raw == 'L' and nt = @lexer.readtok and nt.type == :quoted and nt.raw[0] == ?" nt.raw[0, 0] = 'L' nt elsif t and t.type == :punct and t.raw == '/' and # nt has not been read nt = @lexer.readtok and nt.type == :punct and nt.raw =...
reads a token, convert 'L"foo"' to a :quoted
readtok_longstr
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def readtok if not t = @unreadtoks.pop return if not t = readtok_longstr case t.type when :space, :eol # merge consecutive :space/:eol t = t.dup t.type = :space t.raw = ' ' nil while nt = @lexer.readtok and (nt.type == :eol or nt.type == :space) @lexer.unreadtok nt when...
reads a token from self.lexer concatenates strings, merges spaces/eol to ' ', handles wchar strings, allows $@_ in :string
readtok
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def skipspaces nil while t = readtok and t.type == :space t end
returns the next non-space/non-eol token
skipspaces
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def checkstatementend(tok=nil) raise tok || self, '";" expected' if not tok = skipspaces or tok.type != :punct or (tok.raw != ';' and tok.raw != '}') unreadtok tok if tok.raw == '}' end
checks that we are at the end of a statement, ie an ';' character (consumed), or a '}' (not consumed) otherwise, raise either the given token or self.
checkstatementend
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def sizeof(var, type=nil) var, type = nil, var if var.kind_of? Type and not type type ||= var.type # XXX double-check class apparition order ('when' checks inheritance) case type when Array case type.length when nil if var.kind_of? CExpression and not var.lexpr and not var.op and var.rexpr.k...
returns the size of a type in bytes
sizeof
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def parse_definition(scope) return false if not basetype = Variable.parse_type(self, scope, true) # check struct predeclaration tok = skipspaces if tok and tok.type == :punct and tok.raw == ';' and basetype.type and (basetype.type.kind_of? Union or basetype.type.kind_of? Enum) return true else ...
parses variable/function definition/declaration/initialization populates scope.symbols and scope.struct raises on redefinitions returns false if no definition found
parse_definition
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def parse_toplevel_statement(scope) if tok = skipspaces and tok.type == :punct and tok.raw == ';' true elsif tok and tok.type == :punct and tok.raw == '{' raise tok || self, '"}" expected' if not tok = skipspaces or tok.type != :punct or tok.raw != '}' true elsif tok and tok.type == :string and %w[...
parses toplevel statements, return nil if none found toplevel statements are ';' and 'asm <..>'
parse_toplevel_statement
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def macro_numeric(m) d = @lexer.definition[m] return if not d.kind_of? Preprocessor::Macro or d.args or d.varargs # filter metasm-defined vars (eg __PE__ / _M_IX86) return if not d.name or not bt = d.name.backtrace or (bt[0][0] != ?" and bt[0][0] != ?<) raise 'cannot macro_numeric with unparsed data' if ...
check if a macro definition has a numeric value returns this value or nil
macro_numeric
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def numeric_constants ret = [] # macros @lexer.definition.each_key { |k| if v = macro_numeric(k) ret << [k, v] end } # enums seen_enum = {} @toplevel.struct.each { |k, v| if v.kind_of?(Enum) v.members.each { |kk, vv| ret << [kk, vv, k] seen_enum[kk] = true } ...
returns all numeric constants defined with their value, either macros or enums for enums, also return the enum name
numeric_constants
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def parse_type_base(parser, scope) specifier = [] qualifier = [] name = :int tok = nil loop do if not tok = parser.skipspaces raise parser if specifier.empty? break end if tok.type != :string parser.unreadtok tok break end case tok.raw when 'const', 'volatile' ...
parses int/long int/long long/double etc
parse_type_base
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def parse_declarator(parser, scope, rec = false) parse_attributes(parser, true) tok = parser.skipspaces # read upto name if tok and tok.type == :punct and tok.raw == '*' ptr = Pointer.new ptr.parse_attributes(parser) while ntok = parser.skipspaces and ntok.type == :string case ntok.raw ...
updates @type and @name, parses pointer/arrays/function declarations parses anonymous declarators (@name will be false) the caller is responsible for detecting redefinitions scope used only in CExpression.parse for array sizes and function prototype argument types rec for internal use only
parse_declarator
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def readop(parser) if not op = parser.skipspaces or op.type != :punct parser.unreadtok op return end case op.raw when '>', '<', '|', '&' # << >> || && if ntok = parser.readtok and ntok.type == :punct and ntok.raw == op.raw op.raw << ntok.raw else parser.unreadtok ntok end w...
reads a binary operator from the parser, returns the corresponding symbol or nil
readop
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def parse_intfloat(parser, scope, tok) if tok.type == :string and not tok.value case tok.raw when 'sizeof' if ntok = parser.skipspaces and ntok.type == :punct and ntok.raw == '(' # check type if v = Variable.parse_type(parser, scope) v.parse_declarator(parser, scope) raise tok ...
parse sizeof offsetof float immediate etc into tok.value
parse_intfloat
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def parse_value(parser, scope) return if not tok = parser.skipspaces case tok.type when :string parse_intfloat(parser, scope, tok) val = tok.value || tok.raw if val.kind_of? ::String raise tok, 'undefined variable' if not val = scope.symbol_ancestors[val] end case val when Type ...
returns the next value from parser (parenthesised expression, immediate, variable, unary operators)
parse_value
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def parse_value_postfix(parser, scope, val) tok = parser.skipspaces nval = \ if tok and tok.type == :punct case tok.raw when '+', '++', '-', '--', '->' ntok = parser.readtok if (tok.raw == '+' or tok.raw == '-') and ntok and ntok.type == :punct and (ntok.raw == tok.raw or (tok.raw == '...
parse postfix forms (postincrement, array index, struct member dereference)
parse_value_postfix
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def method_missing(on, *a) n = on.to_s if n[-1] == ?= send :[]=, n[0...-1], *a else super(on, *a) if not @struct.kind_of?(C::Union) or not @struct.findmember(n, true) send :[], n, *a end end
virtual accessors to members struct.foo is aliased to struct['foo'], struct.foo = 42 aliased to struct['foo'] = 42
method_missing
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def find_c_struct(structname) structname = structname.to_s if structname.kind_of?(::Symbol) if structname.kind_of?(::String) and not struct = @toplevel.struct[structname] struct = @toplevel.symbol[structname] raise "unknown struct #{structname.inspect}" if not struct struct = struct.type.untypedef ...
find a Struct/Union object from a struct name/typedef name raises if it cant find it
find_c_struct
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def find_c_type(typename) typename = typename.to_s if typename.kind_of? ::Symbol if typename.kind_of?(::String) and not type = @toplevel.struct[typename] if type = @toplevel.symbol[typename] type = type.type.untypedef else begin lexer.feed(typename) b = C::Block.new(@toplevel) ...
find a C::Type (struct/union/typedef/basetype) from a string
find_c_type
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def alloc_c_struct(structname, values=nil) struct = find_c_struct(structname) st = AllocCStruct.new(self, struct) values.each { |k, v| st[k] = v } if values st end
allocate a new AllocCStruct from the struct/struct typedef name of the current toplevel optionally populate the fields using the 'values' hash
alloc_c_struct
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def decode_c_struct(structname, str, offset=0) struct = find_c_struct(structname) AllocCStruct.new(self, struct, str, offset) end
parse a given String as an AllocCStruct offset is an optionnal offset from the string start modification to the structure will modify the underlying string
decode_c_struct
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def alloc_c_ary(typename, init=1) type = find_c_type(typename) len = init.kind_of?(Integer) ? init : init.length struct = C::Array.new(type, len) st = AllocCStruct.new(self, struct) if init.kind_of?(::Array) init.each_with_index { |v, i| st[i] = v } end st end
allocate an array of types init is either the length of the array, or an array of initial values
alloc_c_ary
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def encode_c_value(type, val) type = type.type if type.kind_of? Variable case val when nil; val = 0 when ::Integer when ::String val = DynLdr.str_ptr(val) when ::Hash type = type.pointed while type.pointer? raise "need a struct ptr for #{type} #{val.inspect}" if not type.kind_of? Union ...
convert (pack) a ruby value into a C buffer packs integers, converts Strings to their C pointer (using DynLdr)
encode_c_value
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def factorize(*a) factorize_init parse(*a) raise @lexer.readtok || self, 'eof expected' if not @lexer.eos? factorize_final end
returns a big string containing all definitions from headers used in the source (including macros)
factorize
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def dump_definitions(list, exclude=[]) # recurse all dependencies todo_rndr = {} todo_deps = {} list.each { |t| todo_rndr[t], todo_deps[t] = t.dump_def(@toplevel) } # c.toplevel.anonymous_enums.to_a.each { |t| todo_rndr[t], todo_deps[t] = t.dump_def(c.toplevel) } while !(ar = (todo_deps.values....
returns a big string representing the definitions of all terms appearing in +list+, excluding +exclude+ includes dependencies
dump_definitions
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def dump_definition(*funcnames) oldst = @toplevel.statements @toplevel.statements = [] dump_definitions(funcnames.map { |f| @toplevel.symbol[f] }) ensure @toplevel.statements = oldst end
returns a string containing the C definition(s) of toplevel functions, with their dependencies
dump_definition
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def dump(scp, r=[''], dep=[]) mydefs = @symbol.values.grep(TypeDef) + @struct.values + anonymous_enums.to_a todo_rndr = {} todo_deps = {} mydefs.each { |t| # filter out Enum values todo_rndr[t], todo_deps[t] = t.dump_def(self) } r, dep = dump_reorder(mydefs, todo_rndr, todo_deps, r, dep) dep -=...
return array of c source lines and array of dependencies (objects)
dump
ruby
stephenfewer/grinder
node/lib/metasm/metasm/parse_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/parse_c.rb
BSD-3-Clause
def exception(msg='syntax error') msgh = msg.to_s if msg msgh << ' near ' expanded_from.to_a.each { |ef| msgh << ef.exception(nil).message << " expanded to \n\t" } end msgh << ((@raw.length > 35) ? (@raw[0..10] + '<...>' + @raw[-10..-1]).inspect : @raw.inspect) msgh << " at " << backtrace_str ...
used when doing 'raise tok, "foo"' raises a ParseError, adding backtrace information
exception
ruby
stephenfewer/grinder
node/lib/metasm/metasm/preprocessor.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/preprocessor.rb
BSD-3-Clause
def apply(lexer, name, args, list=nil) expfrom = name.expanded_from.to_a + [name] if args # hargs is a hash argname.raw => array of tokens hargs = @args.zip(args).inject({}) { |h, (af, ar)| h.update af.raw => ar } if not varargs raise name, 'invalid argument count' if args.length != @args.length...
applies a preprocessor macro parses arguments if needed macros are lazy fills tokens.expanded_from returns an array of tokens
apply
ruby
stephenfewer/grinder
node/lib/metasm/metasm/preprocessor.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/preprocessor.rb
BSD-3-Clause
def parse_definition(lexer) varg = nil if tok = lexer.readtok_nopp and tok.type == :punct and tok.raw == '(' @args = [] loop do nil while tok = lexer.readtok_nopp and tok.type == :space # check '...' if tok and tok.type == :punct and tok.raw == '.' t1 = lexer.readtok_nopp t2 = l...
parses the argument list and the body from lexer converts # + # to ## in body
parse_definition
ruby
stephenfewer/grinder
node/lib/metasm/metasm/preprocessor.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/preprocessor.rb
BSD-3-Clause
def dump_macros(list, comment = true) depend = {} # build dependency graph (we can output macros in any order, but it's more human-readable) walk = lambda { |mname| depend[mname] ||= [] @definition[mname].body.each { |t| name = t.raw if @definition[name] depend[mname] << name if not depend...
dumps the definition of the macros whose name is in the list + their dependencies returns one big C-style source string
dump_macros
ruby
stephenfewer/grinder
node/lib/metasm/metasm/preprocessor.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/preprocessor.rb
BSD-3-Clause
def feed(text, filename='unknown', lineno=1) raise self, 'cannot start new text, did not finish current source' if not eos? feed!(text, filename, lineno) end
starts a new lexer, with the specified initial filename/line number (for backtraces)
feed
ruby
stephenfewer/grinder
node/lib/metasm/metasm/preprocessor.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/preprocessor.rb
BSD-3-Clause
def feed!(text, filename='unknown', lineno=1) raise ArgumentError, 'need something to parse!' if not text @text = text if not @may_preprocess and (@text =~ /^\s*(#|\?\?=)/ or (not @definition.empty? and @text =~ /#{@definition.keys.map { |k| Regexp.escape(k) }.join('|')}/)) @may_preprocess = true end ...
starts a new lexer, with the specified initial filename/line number (for backtraces) discards old text/whatever
feed!
ruby
stephenfewer/grinder
node/lib/metasm/metasm/preprocessor.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/preprocessor.rb
BSD-3-Clause
def feed_file(filename) feed(File.read(filename), filename) end
calls #feed on the content of the file
feed_file
ruby
stephenfewer/grinder
node/lib/metasm/metasm/preprocessor.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/preprocessor.rb
BSD-3-Clause
def getchar @ungetcharpos = @pos @ungetcharlineno = @lineno c = @text[@pos] @pos += 1 # check trigraph #if c == ?? and @text[@pos] == ?? and Trigraph[@text[@pos+1]] # puts "can i has trigraf plox ??#{c.chr} (#@filename:#@lineno)" if $VERBOSE # c = Trigraph[@text[@pos+1]] # @pos += 2 #end # check...
reads one character from self.text updates self.lineno handles \-continued lines
getchar
ruby
stephenfewer/grinder
node/lib/metasm/metasm/preprocessor.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/preprocessor.rb
BSD-3-Clause
def eos? @pos >= @text.length and @queue.empty? and @backtrace.empty? end
returns true if no more data is available
eos?
ruby
stephenfewer/grinder
node/lib/metasm/metasm/preprocessor.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/preprocessor.rb
BSD-3-Clause
def unreadtok(tok) @queue << tok if tok nil end
push back a token, will be returned on the next readtok lifo
unreadtok
ruby
stephenfewer/grinder
node/lib/metasm/metasm/preprocessor.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/preprocessor.rb
BSD-3-Clause
def readtok_nopp return @queue.pop unless @queue.empty? nbt = [] @backtrace.each { |bt| nbt << bt[0] << bt[1] } tok = Token.new(nbt << @filename << @lineno) case c = getchar when nil return nil when ?', ?" # read quoted string value readtok_nopp_str(tok, c) when ?a..?z, ?A..?Z, ?0..?9, ?$, ?_...
read and return the next token parses quoted strings (set tok.value) and C/C++ comments (:space/:eol)
readtok_nopp
ruby
stephenfewer/grinder
node/lib/metasm/metasm/preprocessor.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/preprocessor.rb
BSD-3-Clause
def readtok_nopp_str(tok, delimiter) tok.type = :quoted tok.raw << delimiter tok.value = '' tok.value.force_encoding('binary') if tok.value.respond_to?(:force_encoding) c = nil loop do raise tok, 'unterminated string' if not c = getchar tok.raw << c case c when delimiter; break when ?\\ r...
we just read a ' or a ", read until the end of the string tok.value will contain the raw string (with escapes interpreted etc)
readtok_nopp_str
ruby
stephenfewer/grinder
node/lib/metasm/metasm/preprocessor.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/preprocessor.rb
BSD-3-Clause
def define(name, value=nil, from=caller.first) from =~ /^(.*?):(\d+)/ btfile, btlineno = $1, $2.to_i if not @may_preprocess and @text =~ /#{Regexp.escape name}/ @may_preprocess = true end t = Token.new([btfile, btlineno]) t.type = :string t.raw = name.dup @definition[name] = Macro.new(t) if value.k...
defines a simple preprocessor macro (expands to 0 or 1 token) does not check overwriting
define
ruby
stephenfewer/grinder
node/lib/metasm/metasm/preprocessor.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/preprocessor.rb
BSD-3-Clause
def define_weak(name, value=nil, from=caller.first) define(name, value, from) if not @definition[name] end
defines a pp constant if it is not already defined
define_weak
ruby
stephenfewer/grinder
node/lib/metasm/metasm/preprocessor.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/preprocessor.rb
BSD-3-Clause
def define_strong(name, value=nil, from=caller.first) (@defined_strong ||= []) << name define(name, value, from) end
defines a pp constant so that later #define/#undef will be ignored
define_strong
ruby
stephenfewer/grinder
node/lib/metasm/metasm/preprocessor.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/preprocessor.rb
BSD-3-Clause
def nodefine_strong(name) (@defined_strong ||= []) << name end
does not define name, and prevent it from being defined later
nodefine_strong
ruby
stephenfewer/grinder
node/lib/metasm/metasm/preprocessor.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/preprocessor.rb
BSD-3-Clause
def preprocessor_directive(cmd, ocmd = cmd) # read spaces, returns the next token # XXX for all commands that may change @ifelse_nesting, ensure last element is :testing to disallow any other preprocessor directive to be run in a bad environment (while looking ahead) skipspc = lambda { loop do tok = readto...
handles #directives returns true if the command is valid second parameter for internal use
preprocessor_directive
ruby
stephenfewer/grinder
node/lib/metasm/metasm/preprocessor.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/preprocessor.rb
BSD-3-Clause
def directive_include(cmd, skipspc) raise cmd, 'nested too deeply' if backtrace.length > 200 # gcc # allow preprocessing nil while tok = readtok and tok.type == :space raise tok || cmd, 'pp syntax error' if not tok or (tok.type != :quoted and (tok.type != :punct or tok.raw != '<')) if tok.type == :quoted ...
handles the '#include' directive, which will insert a new file content in the token stream
directive_include
ruby
stephenfewer/grinder
node/lib/metasm/metasm/preprocessor.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/preprocessor.rb
BSD-3-Clause
def file_exist_nocase(name) componants = name.tr('\\', '/').split('/') if componants[0] == '' ret = '/' componants.shift else ret = './' end componants.each { |cp| return if not ccp = Dir.entries(ret).find { |ccp_| ccp_.downcase == cp.downcase } ret = File.join(ret, ccp) } ret end
checks if a file exists search for case-insensitive variants of the path returns the match if found, or nil
file_exist_nocase
ruby
stephenfewer/grinder
node/lib/metasm/metasm/preprocessor.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/preprocessor.rb
BSD-3-Clause
def directive_pragma(cmd, skipspc) nil while tok = readtok and tok.type == :space raise tok || cmd if not tok or tok.type != :string case tok.raw when 'once' @pragma_once[@filename[1..-2]] = true when 'no_warn_redefinition' @warn_redefinition = false when 'include_dir', 'include_path' nil while di...
handles a '#pragma' directive in the preprocessor source here we handle: 'once': do not re-#include this file 'no_warn_redefinition': macro redefinition warning 'include_dir' / 'include_path': insert directories in the #include <xx> search path (this new dir will be searched first) 'push_macro' / 'pop_macro': allows te...
directive_pragma
ruby
stephenfewer/grinder
node/lib/metasm/metasm/preprocessor.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/preprocessor.rb
BSD-3-Clause
def readop(lexer) if not tok = lexer.readtok or tok.type != :punct lexer.unreadtok tok return end op = tok case op.raw # may be followed by itself or '=' when '>', '<' if ntok = lexer.readtok and ntok.type == :punct and (ntok.raw == op.raw or ntok.raw == '=') op = op.dup op.raw ...
reads an operator from the lexer, returns the corresponding symbol or nil
readop
ruby
stephenfewer/grinder
node/lib/metasm/metasm/preprocessor.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/preprocessor.rb
BSD-3-Clause
def parse_value(lexer) nil while tok = lexer.readtok and tok.type == :space return if not tok case tok.type when :string parse_intfloat(lexer, tok) val = tok.value || tok.raw when :quoted if tok.raw[0] != ?' or tok.value.length > 1 # allow single-char lexer.unreadtok tok return ...
returns the next value from lexer (parenthesised expression, immediate, variable, unary operators) single-line only, and does not handle multibyte char string
parse_value
ruby
stephenfewer/grinder
node/lib/metasm/metasm/preprocessor.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/preprocessor.rb
BSD-3-Clause
def each_expr r = proc { |e| case e when Expression r[e.lexpr] ; r[e.rexpr] yield e when ExpressionType yield e when Renderable e.render.each { |re| r[re] } end } r[self] end
yields each Expr seen in #render (recursive)
each_expr
ruby
stephenfewer/grinder
node/lib/metasm/metasm/render.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/render.rb
BSD-3-Clause
def render_instruction(i) r = [] r << i.opname r << ' ' i.args.each { |a| r << a << ', ' } r.pop r end
renders an instruction may use instruction-global properties to render an argument (eg specify pointer size if not implicit)
render_instruction
ruby
stephenfewer/grinder
node/lib/metasm/metasm/render.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/render.rb
BSD-3-Clause
def build_bin_lookaside lookaside = Array.new(256) { [] } opcode_list.each { |op| build_opcode_bin_mask op b = (op.bin >> 20) & 0xff msk = (op.bin_mask >> 20) & 0xff b &= msk for i in b..(b | (255^msk)) lookaside[i] << op if i & msk == b end } lookaside end
create the lookaside hash from the first byte of the opcode
build_bin_lookaside
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/arm/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/arm/decode.rb
BSD-3-Clause
def decode_findopcode(edata) return if edata.ptr > edata.data.length-8 di = DecodedInstruction.new self code = edata.data[edata.ptr, 2].unpack('v')[0] return di if di.opcode = @bin_lookaside[code] end
tries to find the opcode encoded at edata.ptr
decode_findopcode
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/bpf/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/bpf/decode.rb
BSD-3-Clause
def init_backtrace_binding @backtrace_binding ||= {} opcode_list.map { |ol| ol.basename }.uniq.sort.each { |op| binding = case op when 'mov'; lambda { |di, a0, a1| { a0 => Expression[a1] } } when 'add'; lambda { |di, a0, a1| { a0 => Expression[a0, :+, a1] } } when 'sub'; lambda { |di, a0, a1| { a0 => E...
populate the @backtrace_binding hash with default values
init_backtrace_binding
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/bpf/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/bpf/decode.rb
BSD-3-Clause
def replace_instr_arg_immediate(i, old, new) i.args.map! { |a| case a when Expression; a == old ? new : Expression[a.bind(old => new).reduce] else a end } end
updates an instruction's argument replacing an expression with another (eg label renamed)
replace_instr_arg_immediate
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/bpf/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/bpf/decode.rb
BSD-3-Clause
def init_backtrace_binding @backtrace_binding ||= {} mask = 0xffff opcode_list.map { |ol| ol.basename }.uniq.sort.each { |op| binding = case op when 'mov'; lambda { |di, a0, a1| { a0 => Expression[a1] } } when 'add', 'adc', 'sub', 'sbc', 'and', 'xor', 'or', 'addi', 'subi' lambda { |di, a0, a1| ...
populate the @backtrace_binding hash with default values
init_backtrace_binding
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/cy16/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/cy16/decode.rb
BSD-3-Clause
def fix_fwdemu_binding(di, fbd) case di.opcode.name when 'call'; fbd[Indirection[[:sp, :-, 2], 2]] = fbd.delete(Indirection[:sp, 2]) end fbd end
patch a forward binding from the backtrace binding
fix_fwdemu_binding
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/cy16/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/cy16/decode.rb
BSD-3-Clause
def backtrace_is_function_return(expr, di=nil) expr = Expression[expr].reduce_rec expr.kind_of?(Indirection) and expr.len == 2 and expr.target == Expression[:sp] end
checks if expr is a valid return expression matching the :saveip instruction
backtrace_is_function_return
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/cy16/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/cy16/decode.rb
BSD-3-Clause
def backtrace_update_function_binding(dasm, faddr, f, retaddrlist, *wantregs) b = f.backtrace_binding bt_val = lambda { |r| next if not retaddrlist b[r] = Expression::Unknown bt = [] retaddrlist.each { |retaddr| bt |= dasm.backtrace(Expression[r], retaddr, :include_start => true, :snapsho...
updates the function backtrace_binding if the function is big and no specific register is given, do nothing (the binding will be lazily updated later, on demand)
backtrace_update_function_binding
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/cy16/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/cy16/decode.rb
BSD-3-Clause
def replace_instr_arg_immediate(i, old, new) i.args.map! { |a| case a when Expression; a == old ? new : Expression[a.bind(old => new).reduce] when Memref a.offset = (a.offset == old ? new : Expression[a.offset.bind(old => new).reduce]) if a.offset a else a end } end
updates an instruction's argument replacing an expression with another (eg label renamed)
replace_instr_arg_immediate
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/cy16/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/cy16/decode.rb
BSD-3-Clause
def disassembler_default_func df = DecodedFunction.new ra = Indirection[:callstack, @size/8] df.backtracked_for << BacktraceTrace.new(ra, :default, ra, :x, nil) df.backtrace_binding[:callstack] = Expression[:callstack, :+, @size/8] df.btfor_callback = lambda { |dasm, btfor, funcaddr, calladdr| if funcaddr ...
returns a DecodedFunction suitable for :default uses disassembler_default_bt{for/bind}_callback
disassembler_default_func
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/dalvik/decode.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/dalvik/decode.rb
BSD-3-Clause
def instr(name, *args) # XXX parse_postfix ? @source << Instruction.new(@exeformat.cpu, name, args) end
shortcut to add an instruction to the source
instr
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/compile_c.rb
BSD-3-Clause
def findreg(sz = @cpusz) caching = @state.cache.keys.grep(Reg).map { |r| r.val } if not regval = ([*0..@regnummax] - @state.used - caching).first || ([*0..@regnummax] - @state.used).first raise 'need more registers! (or a better compiler?)' end getreg(regval, sz) end
returns an available register, tries to find one not in @state.cache do not use with sz==8 (aliasing ah=>esp) does not put it in @state.inuse TODO multipass for reg cache optimization TODO dynamic regval for later fixup (need a value to be in ecx for shl, etc)
findreg
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/compile_c.rb
BSD-3-Clause
def getreg(regval, sz=@cpusz) flushcachereg(regval) @state.dirty |= [regval] Reg.new(regval, sz) end
returns a Reg from a regval, mark it as dirty, flush old cache dependencies
getreg
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/compile_c.rb
BSD-3-Clause
def flushcachereg(regval) @state.cache.delete_if { |e, val| case e when Reg; e.val == regval when Address; e = e.modrm ; redo when ModRM; e.b && (e.b.val == regval) or e.i && (e.i.val == regval) when Composite; e.low.val == regval or e.high.val == regval end } end
remove the cache keys that depends on the register
flushcachereg
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/compile_c.rb
BSD-3-Clause
def unuse(*vals) vals.each { |val| val = val.modrm if val.kind_of? Address @state.inuse.delete val } # XXX cache exempt exempt = @state.bound.values.map { |r| r.kind_of? Composite ? [r.low.val, r.high.val] : r.val }.flatten exempt << 4 exempt << 5 if @state.saved_ebp @state.used.delete_if { |regval|...
removes elements from @state.inuse, free @state.used if unreferenced must be the exact object present in inuse
unuse
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/compile_c.rb
BSD-3-Clause
def inuse(v) case v when Reg; @state.used |= [v.val] when ModRM @state.used |= [v.i.val] if v.i @state.used |= [v.b.val] if v.b when Composite; @state.used |= [v.low.val, v.high.val] when Address; inuse v.modrm ; return v else return v end @state.inuse |= [v] v end
marks an arg as in use, returns the arg
inuse
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/compile_c.rb
BSD-3-Clause
def findvar(var) if ret = @state.bound[var] return ret end if ret = @state.cache.index(var) ret = ret.dup inuse ret return ret end sz = 8*sizeof(var) rescue nil # extern char foo[]; case off = @state.offset[var] when C::CExpression # stack, dynamic address # TODO # no need to updat...
returns a variable storage (ModRM for stack/global, Reg/Composite for register-bound)
findvar
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/compile_c.rb
BSD-3-Clause
def resolve_address(e) r = e.modrm unuse e if r.imm and not r.b and not r.i reg = r.imm elsif not r.imm and ((not r.b and r.s == 1) or not r.i) reg = r.b || r.i elsif reg = @state.cache.index(e) reg = reg.dup else reg = findreg r.sz = reg.sz instr 'lea', reg, r end inuse reg @state.c...
resolves the Address to Reg/Expr (may encode an 'lea')
resolve_address
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/compile_c.rb
BSD-3-Clause
def make_volatile(e, type, rsz=@cpusz) if e.kind_of? ModRM or @state.bound.index(e) if type.integral? or type.pointer? oldval = @state.cache[e] if type.integral? and type.name == :__int64 and @cpusz != 64 e2l = inuse findreg(32) unuse e e2h = inuse findreg(32) el, eh = get_composite_par...
copies the arg e to a volatile location (register/composite) if it is not already unuses the old storage may return a register bigger than the type size (eg __int8 are stored in full reg size) use rsz only to force 32bits-return on a 16bits cpu
make_volatile
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/compile_c.rb
BSD-3-Clause
def get_composite_parts(e) case e when ModRM el = e.dup el.sz = 32 eh = el.dup eh.imm = Expression[eh.imm, :+, 4] when Expression el = Expression[e, :&, 0xffff_ffff] eh = Expression[e, :>>, 32] when Composite el = e.low eh = e.high when Reg el = e eh = findreg else raise end ...
returns two args corresponding to the low and high 32bits of the 64bits composite arg
get_composite_parts
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/compile_c.rb
BSD-3-Clause
def getcc(op, type) case op when :'=='; 'z' when :'!='; 'nz' when :'<' ; 'b' when :'>' ; 'a' when :'<='; 'be' when :'>='; 'ae' else raise "bad comparison op #{op}" end.tr((type.specifier == :unsigned ? '' : 'ab'), 'gl') end
returns the instruction suffix for a comparison operator
getcc
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/compile_c.rb
BSD-3-Clause
def c_cexpr_inner(expr) case expr when ::Integer; Expression[expr] when C::Variable; findvar(expr) when C::CExpression if not expr.lexpr or not expr.rexpr inuse c_cexpr_inner_nol(expr) else inuse c_cexpr_inner_l(expr) end when C::Label; findvar(C::Variable.new(expr.name, C::Array.new(C::BaseT...
compiles a c expression, returns an Ia32 instruction argument
c_cexpr_inner
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/compile_c.rb
BSD-3-Clause
def c_cexpr_inner_l(expr) case expr.op when :funcall c_cexpr_inner_funcall(expr) when :'+=', :'-=', :'*=', :'/=', :'%=', :'^=', :'&=', :'|=', :'<<=', :'>>=' l = c_cexpr_inner(expr.lexpr) raise 'bad lvalue' if not l.kind_of? ModRM and not @state.bound.index(l) instr 'fld', l if expr.type.float? r = ...
compiles a CExpression, not arithmetic (assignment, comparison etc)
c_cexpr_inner_l
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/compile_c.rb
BSD-3-Clause
def c_cexpr_inner_arith_float(l, op, r, type) op = case op when :+; 'fadd' when :-; 'fsub' when :*; 'fmul' when :/; 'fdiv' else raise "unsupported FPU operation #{l} #{op} #{r}" end unuse r case r when FpReg; instr op+'p', FpReg.new(1) when ModRM; instr op, r end end
compiles a float arithmetic expression l is ST(0)
c_cexpr_inner_arith_float
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/compile_c.rb
BSD-3-Clause
def c_cexpr_inner_arith_int(l, op, r, type) op = case op when :+; 'add' when :-; 'sub' when :&; 'and' when :|; 'or' when :^; 'xor' when :>>; type.specifier == :unsigned ? 'shr' : 'sar' when :<<; 'shl' when :*; 'mul' when :/; 'div' when :%; 'mod' end case op when 'add', 'sub', 'and', 'or', '...
compile an integral arithmetic expression, reg-sized
c_cexpr_inner_arith_int
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/compile_c.rb
BSD-3-Clause
def c_cexpr_inner_arith_int64compose(l, op, r, type) op = case op when :+; 'add' when :-; 'sub' when :&; 'and' when :|; 'or' when :^; 'xor' when :>>; type.specifier == :unsigned ? 'shr' : 'sar' when :<<; 'shl' when :*; 'mul' when :/; 'div' when :%; 'mod' end ll, lh = get_composite_parts l #...
compile an integral arithmetic 64-bits expression on a non-64 cpu
c_cexpr_inner_arith_int64compose
ruby
stephenfewer/grinder
node/lib/metasm/metasm/cpu/ia32/compile_c.rb
https://github.com/stephenfewer/grinder/blob/master/node/lib/metasm/metasm/cpu/ia32/compile_c.rb
BSD-3-Clause