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 single byte value or full data statement
if not ntok = @lexer.readtok or not ntok.type == :string or not Data::DataSpec.include?(ntok.raw)
@lexer.unreadtok ntok
type = 'db'
else
type = ntok.raw
end
fillwith = parse_data_data type
else
@lexer.unreadtok ntok
end
raise tok, 'syntax error' if ntok = @lexer.nexttok and ntok.type != :eol
@cursource << Align.new(e, fillwith, tok.backtrace)
when '.pad'
@lexer.skip_space
if ntok = @lexer.readtok and ntok.type != :eol
# allow single byte value or full data statement
if not ntok.type == :string or not Data::DataSpec.include?(ntok.raw)
@lexer.unreadtok ntok
type = 'db'
else
type = ntok.raw
end
fillwith = parse_data_data(type)
else
@lexer.unreadtok ntok
end
raise tok, 'syntax error' if ntok = @lexer.nexttok and ntok.type != :eol
@cursource << Padding.new(fillwith, tok.backtrace)
when '.offset'
e = Expression.parse(@lexer)
raise tok, 'syntax error' if ntok = @lexer.nexttok and ntok.type != :eol
@cursource << Offset.new(e, tok.backtrace)
when '.padto'
e = Expression.parse(@lexer)
@lexer.skip_space
if ntok = @lexer.readtok and ntok.type == :punct and ntok.raw == ','
@lexer.skip_space
# allow single byte value or full data statement
if not ntok = @lexer.readtok or not ntok.type == :string or not Data::DataSpec.include?(ntok.raw)
@lexer.unreadtok ntok
type = 'db'
else
type = ntok.raw
end
fillwith = parse_data_data type
else
@lexer.unreadtok ntok
end
raise tok, 'syntax error' if ntok = @lexer.nexttok and ntok.type != :eol
@cursource << Padding.new(fillwith, tok.backtrace) << Offset.new(e, tok.backtrace)
else
@cpu.parse_parser_instruction(self, tok)
end
end | 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 '>', '<'
if ntok = lexer.readtok and ntok.type == :punct and (ntok.raw == op.raw or ntok.raw == '=')
op = op.dup
op.raw << ntok.raw
else
lexer.unreadtok ntok
end
# may be followed by itself
when '|', '&'
if ntok = lexer.readtok and ntok.type == :punct and ntok.raw == op.raw
op = op.dup
op.raw << ntok.raw
else
lexer.unreadtok ntok
end
# must be followed by '='
when '!', '='
if not ntok = lexer.readtok or ntok.type != :punct and ntok.raw != '='
lexer.unreadtok ntok
lexer.unreadtok tok
return
end
op = op.dup
op.raw << ntok.raw
# ok
when '^', '+', '-', '*', '/', '%'
# unknown
else
lexer.unreadtok tok
return
end
op.value = op.raw.to_sym
op
end | 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] != ?. and !(?0..?9).include? tok.raw[0]
case tr = tok.raw.downcase
when /^0b([01][01_]*)$/, /^([01][01_]*)b$/
tok.value = $1.to_i(2)
when /^(0[0-7][0-7_]*)$/
tok.value = $1.to_i(8)
when /^([0-9][a-f0-9_]*)h$/
tok.value = $1.to_i(16)
when /^0x([a-f0-9][a-f0-9_]*)(u?l?l?|l?l?u?|p([0-9][0-9_]*[fl]?)?)$/, '0x'
tok.value = $1.to_i(16) if $1
ntok = lexer.readtok
# check for C99 hex float
if not tr.include? 'p' and ntok and ntok.type == :punct and ntok.raw == '.'
if not nntok = lexer.readtok or nntok.type != :string
lexer.unreadtok nntok
lexer.unreadtok ntok
return
end
# read all pre-mantissa
tok.raw << ntok.raw
ntok = nntok
tok.raw << ntok.raw if ntok
raise tok, 'invalid hex float' if not ntok or ntok.type != :string or ntok.raw !~ /^[0-9a-f_]*p([0-9][0-9_]*[fl]?)?$/i
raise tok, 'invalid hex float' if tok.raw.delete('_').downcase[0,4] == '0x.p' # no digits
ntok = lexer.readtok
end
if not tok.raw.downcase.include? 'p'
# standard hex
lexer.unreadtok ntok
else
if tok.raw.downcase[-1] == ?p
# read signed mantissa
tok.raw << ntok.raw if ntok
raise tok, 'invalid hex float' if not ntok or ntok.type == :punct or (ntok.raw != '+' and ntok.raw != '-')
ntok = lexer.readtok
tok.raw << ntok.raw if ntok
raise tok, 'invalid hex float' if not ntok or ntok.type != :string or ntok.raw !~ /^[0-9][0-9_]*[fl]?$/i
end
raise tok, 'internal error' if not tok.raw.delete('_').downcase =~ /^0x([0-9a-f]*)(?:\.([0-9a-f]*))?p([+-]?[0-9]+)[fl]?$/
b1, b2, b3 = $1.to_i(16), $2, $3.to_i
b2 = b2.to_i(16) if b2
tok.value = b1.to_f
# tok.value += 1/b2.to_f # TODO
puts "W: unhandled hex float #{tok.raw}" if $VERBOSE and b2 and b2 != 0
tok.value *= 2**b3
puts "hex float: #{tok.raw} => #{tok.value}" if $DEBUG
end
when /^([0-9][0-9_]*)(u?l?l?|l?l?u?|e([0-9][0-9_]*[fl]?)?)$/, '.'
tok.value = $1.to_i if $1
ntok = lexer.readtok
if tok.raw == '.' and (not ntok or ntok.type != :string)
lexer.unreadtok ntok
return
end
if not tr.include? 'e' and tr != '.' and ntok and ntok.type == :punct and ntok.raw == '.'
if not nntok = lexer.readtok or nntok.type != :string
lexer.unreadtok nntok
lexer.unreadtok ntok
return
end
# read upto '.'
tok.raw << ntok.raw
ntok = nntok
end
if not tok.raw.downcase.include? 'e' and tok.raw[-1] == ?.
# read fractional part
tok.raw << ntok.raw if ntok
raise tok, 'bad float' if not ntok or ntok.type != :string or ntok.raw !~ /^[0-9_]*(e[0-9_]*)?[fl]?$/i
ntok = lexer.readtok
end
if tok.raw.downcase[-1] == ?e
# read signed exponent
tok.raw << ntok.raw if ntok
raise tok, 'bad float' if not ntok or ntok.type != :punct or (ntok.raw != '+' and ntok.raw != '-')
ntok = lexer.readtok
tok.raw << ntok.raw if ntok
raise tok, 'bad float' if not ntok or ntok.type != :string or ntok.raw !~ /^[0-9][0-9_]*[fl]?$/i
ntok = lexer.readtok
end
lexer.unreadtok ntok
if tok.raw.delete('_').downcase =~ /^(?:(?:[0-9]+\.[0-9]*|\.[0-9]+)(?:e[+-]?[0-9]+)?|[0-9]+e[+-]?[0-9]+)[fl]?$/i
tok.value = tok.raw.to_f
else
raise tok, 'internal error' if tok.raw =~ /[e.]/i
end
else raise tok, 'invalid numeric constant'
end
end | 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 == :string; tok = ntok
else lexer.unreadtok ntok
end
end
parse_intfloat(lexer, tok)
val = tok.value || tok.raw
when :quoted
if tok.raw[0] != ?'
lexer.unreadtok tok
return
end
s = tok.value || tok.raw[1..-2] # raise tok, 'need ppcessing !'
s = s.reverse if lexer.respond_to? :program and lexer.program and lexer.program.cpu and lexer.program.cpu.endianness == :little
val = s.unpack('C*').inject(0) { |sum, c| (sum << 8) | c }
when :punct
case tok.raw
when '('
nil while ntok = lexer.readtok and (ntok.type == :space or ntok.type == :eol)
lexer.unreadtok ntok
val = parse(lexer)
nil while ntok = lexer.readtok and (ntok.type == :space or ntok.type == :eol)
raise tok, "syntax error, no ) found after #{val.inspect}, got #{ntok.inspect}" if not ntok or ntok.type != :punct or ntok.raw != ')'
when '!', '+', '-', '~'
nil while ntok = lexer.readtok and (ntok.type == :space or ntok.type == :eol)
lexer.unreadtok ntok
raise tok, 'need expression after unary operator' if not val = parse_value(lexer)
val = Expression[tok.raw.to_sym, val]
when '.'
parse_intfloat(lexer, tok)
if not tok.value
lexer.unreadtok tok
return
end
val = tok.value
else
lexer.unreadtok tok
return
end
else
lexer.unreadtok tok
return
end
nil while tok = lexer.readtok and tok.type == :space
lexer.unreadtok tok
val
end | 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(opstack.pop, stack.pop, stack.pop)
end
opstack << op.value
raise op, 'need rhs' if not e = parse_value(lexer)
stack << e
end
until opstack.empty?
stack << new(opstack.pop, stack.pop, stack.pop)
end
Expression[stack.first]
end | 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.raw != '('
raise tok || parser if keyword == '__attribute__' and (not tok = parser.skipspaces or tok.type != :punct or tok.raw != '(')
nest = 0
attrib = ''
loop do
raise parser if not tok = parser.skipspaces
if tok.type == :punct and tok.raw == ')'
if nest == 0
raise tok || parser if keyword == '__attribute__' and (not tok = parser.skipspaces or tok.type != :punct or tok.raw != ')')
break
else
nest -= 1
end
elsif tok.type == :punct and tok.raw == '('
nest += 1
elsif nest == 0 and tok.type == :punct and tok.raw == ','
raise tok || parser if not allow_declspec and DECLSPECS.include? attrib
add_attribute attrib
attrib = ''
next
end
attrib << tok.raw
end
raise tok || parser, "attr #{attrib.inspect} not allowed here" if not allow_declspec and DECLSPECS.include? attrib
else
if allow_declspec and DECLSPECS.include? keyword.gsub('_', '')
attrib = keyword.gsub('_', '')
else break
end
end
add_attribute(attrib)
end
parser.unreadtok tok
end | 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?
ot = om.type
st = sm.type
500.times { # limit for selfpointers (shouldnt happen)
break if not ot.pointer?
ot = ot.pointed.untypedef
st = st.pointed.untypedef
}
if ot.kind_of?(C::Union) and ot.name and not seen.include?(ot)
return if not st.compare_deep(ot, seen+[ot])
end
end
}
true
end | 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 { |m| m.name == nnt.raw }) # TODO
if not root
value[idx] ||= [] # AryRecorder may change [] to AryRec.new, can't do v = v[i] ||= []
value = value[idx]
end
idx = nidx
@members[idx].type.untypedef.parse_initializer_designator(parser, scope, value, idx, false)
else
parser.unreadtok nnt
if root
parser.unreadtok nt
value[idx] = @members[idx].type.parse_initializer(parser, scope)
else
raise nt || parser, '"=" expected' if not nt or nt.type != :punct or nt.raw != '='
value[idx] = parse_initializer(parser, scope)
end
end
idx + 1
end | 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 @fldlist[name] or @members.include?(name)
raise parser, 'undefined union' if not @members
raise parser, 'unknown union member' if not findmember(name)
@members.find { |m|
m.type.untypedef.kind_of?(Union) and m.type.untypedef.findmember(name)
}.type.untypedef.bitoffsetof(parser, name)
end | 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 - 1) / mal * mal
end
isz = parser.sizeof(m)
if b == 0 or (bit_off > 0 and bit_off + b > 8*isz)
bit_off = 0
mal = [m.type.align(parser), al].min
off = (off + isz + mal - 1) / mal * mal
end
if m.name
@fldoffset[m.name] = off
@fldbitoffset ||= {}
@fldbitoffset[m.name] = [bit_off, b]
end
bit_off += b
else
if isz
off += isz
bit_off = 0
isz = nil
end
mal = [m.type.align(parser), al].min
off = (off + mal - 1) / mal * mal
@fldoffset[m.name] = off if m.name
off += parser.sizeof(m)
end
}
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)
# 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 root
value[idx] ||= [] # AryRecorder may change [] to AryRec.new, can't do v = v[i] ||= []
value = value[idx]
end
raise nt, 'const expected' if not idx = CExpression.parse(parser, scope) or not idx.constant? or not idx = idx.reduce(parser) or not idx.kind_of? ::Integer
nt = parser.skipspaces
if nt and nt.type == :punct and nt.raw == '.' # range
raise nt || parser, '".." expected' if not nt = parser.skipspaces or nt.type != :punct or nt.raw != '.'
raise nt || parser, '"." expected' if not nt = parser.skipspaces or nt.type != :punct or nt.raw != '.'
raise nt, 'const expected' if not eidx = CExpression.parse(parser, scope) or not eidx.constant? or not eidx = eidx.reduce(parser) or not eidx.kind_of? ::Integer
raise nt, 'bad range' if eidx < idx
nt = parser.skipspaces
realvalue = value
value = AryRecorder.new
end
raise nt || parser, '"]" expected' if not nt or nt.type != :punct or nt.raw != ']'
raise nt, 'array is smaller than that' if length and (eidx||idx) >= @length
@type.untypedef.parse_initializer_designator(parser, scope, value, idx, false)
if eidx
(idx..eidx).each { |i| realvalue[i] = value.playback_idx(idx) }
idx = eidx # next default value = eidx+1 (eg int x[] = { [1 ... 3] = 4, 5 } => x[4] = 5)
end
else
if root
parser.unreadtok nt
value[idx] = @type.parse_initializer(parser, scope)
else
raise nt || parser, '"=" expected' if not nt or nt.type != :punct or nt.raw != '='
value[idx] = parse_initializer(parser, scope)
end
end
idx + 1
end | 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_callback = lambda { |tok| parse_pragma_callback(tok) }
@toplevel = Block.new(nil)
@unreadtoks = []
@endianness = cpu ? cpu.endianness : :big
@typesize = { :void => 1, :__int8 => 1, :__int16 => 2, :__int32 => 4, :__int64 => 8,
:char => 1, :float => 4, :double => 8, :longdouble => 12 }
send model
cpu.tune_cparser(self) if cpu
@program.tune_cparser(self) if @program
end | 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 mismatch').message if oldtype.qualifier.to_a.uniq.length > newtype.qualifier.to_a.uniq.length
# avoid infinite recursion
return if checked.include? oldtype
checked = checked + [oldtype]
begin
case newtype
when Function
raise tok, 'type error' if not oldtype.kind_of? Function
check_compatible_type tok, oldtype.type, newtype.type, strict, checked
if oldtype.args and newtype.args
if oldtype.args.length != newtype.args.length or
oldtype.varargs != newtype.varargs
raise tok, 'type error'
end
oldtype.args.zip(newtype.args) { |oa, na|
# begin ; rescue ParseError: raise $!.message + "in parameter #{oa.name}" end
check_compatible_type tok, oa.type, na.type, strict, checked
}
end
when Pointer
if oldtype.kind_of? BaseType and oldtype.integral?
puts tok.exception('making pointer from integer without a cast').message
return
end
raise tok, 'type error' if not oldtype.kind_of? Pointer
hasvoid = true if (t = newtype.type.untypedef).kind_of? BaseType and t.name == :void
hasvoid = true if (t = oldtype.type.untypedef).kind_of? BaseType and t.name == :void # struct foo *f = NULL;
if strict and not hasvoid
check_compatible_type tok, oldtype.type, newtype.type, strict, checked
end
when Union
raise tok, 'type error' if not oldtype.class == newtype.class
if oldtype.members and newtype.members
if oldtype.members.length != newtype.members.length
raise tok, 'bad member count'
end
oldtype.members.zip(newtype.members) { |om, nm|
# raise tok if om.name and nm.name and om.name != nm.name # don't care
check_compatible_type tok, om.type, nm.type, strict, checked
}
end
when BaseType
raise tok, 'type error' if not oldtype.kind_of? BaseType
if strict
if oldtype.name != newtype.name or
oldtype.specifier != newtype.specifier
raise tok, 'type error'
end
else
raise tok, 'type error' if @typesize[newtype.name] == 0 and @typesize[oldtype.name] > 0
puts tok.exception('type size mismatch, may lose bits').message if @typesize[oldtype.name] > @typesize[newtype.name]
puts tok.exception('sign mismatch').message if oldtype.specifier != newtype.specifier and @typesize[newtype.name] == @typesize[oldtype.name]
end
end
rescue ParseError
raise $! if checked.length != 1 # bubble up
oname = (oldtype.to_s rescue oldtype.class.name)
nname = (newtype.to_s rescue newtype.class.name)
puts $!.message + " incompatible type #{oname} to #{nname}"
end
end | 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 == '/'
# windows.h has a #define some_type_name /##/, and VS interprets this as a comment..
puts @lexer.exception('#defined //').message if $VERBOSE
t = @lexer.readtok while t and t.type != :eol
t
else
@lexer.unreadtok nt
t
end
end | 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 :quoted
# merge consecutive :quoted
t = t.dup
while nt = readtok_longstr
case nt.type
when :quoted
if t.raw[0] == ?" and nt.raw[0, 2] == 'L"'
# ensure wide prefix is set
t.raw[0, 0] = 'L'
end
t.raw << ' ' << nt.raw
t.value << nt.value
when :space, :eol
else break
end
end
@lexer.unreadtok nt
else
if (t.type == :punct and (t.raw == '_' or t.raw == '@' or t.raw == '$')) or t.type == :string
t = t.dup
t.type = :string
nt = nil
t.raw << nt.raw while nt = @lexer.readtok and ((nt.type == :punct and (nt.raw == '_' or nt.raw == '@' or nt.raw == '$')) or nt.type == :string)
@lexer.unreadtok nt
end
end
end
t
end | 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.kind_of? Variable
var = var.rexpr
end
raise self, 'unknown array size' if not var.kind_of? Variable or not var.initializer
init = var.initializer
init = init.rexpr if init.kind_of? C::CExpression and not init.op and init.rexpr.kind_of? ::String
case init
when ::String; sizeof(nil, type.type) * (init.length + 1)
when ::Array
v = init.compact.first
v ? (sizeof(nil, type.type) * init.length) : 0
else sizeof(init)
end
when ::Integer; type.length * sizeof(type.type)
when CExpression
len = type.length.reduce(self)
raise self, 'unknown array size' if not len.kind_of? ::Integer
len * sizeof(type)
else raise self, 'unknown array size'
end
when Pointer
if var.kind_of? CExpression and not var.op and var.rexpr.kind_of? ::String
# sizeof("lolz") => 5
sizeof(nil, type.type) * (var.rexpr.length + 1)
else
@typesize[:ptr]
end
when Function
# raise
1 # gcc
when BaseType
@typesize[type.name]
when Enum
@typesize[:int]
when Struct
raise self, "unknown structure size #{type.name}" if not type.members
al = type.align(self)
al = 1 if (var.kind_of?(Attributes) and var.has_attribute('sizeof_packed')) or type.has_attribute('sizeof_packed')
lm = type.members.last
lm ? (type.offsetof(self, lm) + sizeof(lm) + al - 1) / al * al : 0
when Union
raise self, "unknown structure size #{type.name}" if not type.members
type.members.map { |m| sizeof(m) }.max || 0
when TypeDef
sizeof(var, type.type)
end
end | 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 unreadtok tok
end
nofunc = false
loop do
var = basetype.dup
var.parse_declarator(self, scope)
raise var.backtrace if not var.name # barrel roll
if prev = scope.symbol[var.name]
if prev.kind_of? TypeDef and var.storage == :typedef
check_compatible_type(var.backtrace, prev.type, var.type, true)
# windows.h redefines many typedefs with the same definition
puts "redefining typedef #{var.name}" if $VERBOSE
var = prev
elsif not prev.kind_of?(Variable) or
prev.initializer or
(prev.storage != :extern and prev.storage != var.storage) or
(scope != @toplevel and prev.storage != :static)
if prev.kind_of? ::Integer # enum value
prev = (scope.struct.values.grep(Enum) + scope.anonymous_enums.to_a).find { |e| e.members.index(prev) }
end
raise var.backtrace, "redefinition, previous is #{prev.backtrace.exception(nil).message rescue :unknown}"
else
check_compatible_type var.backtrace, prev.type, var.type, true
(var.attributes ||= []).concat prev.attributes if prev.attributes
end
elsif var.storage == :typedef
attrs = var.attributes
var = TypeDef.new var.name, var.type, var.backtrace
var.attributes = attrs if attrs
end
scope.statements << Declaration.new(var) unless var.kind_of? TypeDef
raise tok || self, 'punctuation expected' if not tok = skipspaces or (tok.type != :punct and not %w[asm __asm __asm__].include? tok.raw)
case tok.raw
when '{'
# function body
raise tok if nofunc or not var.kind_of? Variable or not var.type.kind_of? Function
scope.symbol[var.name] = var
body = var.initializer = Block.new(scope)
var.type.args ||= []
var.type.args.each { |v|
# put func parameters in func body scope
# arg redefinition is checked in parse_declarator
if not v.name
puts "unnamed argument in definition of #{var.name}" if $DEBUG
next # should raise to be compliant
end
body.symbol[v.name] = v # XXX will need special check in stack allocator
}
loop do
raise tok || self, var.backtrace.exception('"}" expected for end of function') if not tok = skipspaces
break if tok.type == :punct and tok.raw == '}'
unreadtok tok
if not parse_definition(body)
body.statements << parse_statement(body, [var.type.type])
end
end
if $VERBOSE and not body.statements.last.kind_of? Return and not body.statements.last.kind_of? Asm
puts tok.exception('missing function return value').message if not var.type.type.untypedef.kind_of? BaseType or var.type.type.untypedef.name != :void
end
break
when 'asm', '__asm', '__asm__'
# GCC function redirection
# void foo(void) __asm__("bar"); => when code uses 'foo', silently redirect to 'bar' instead
raise tok if nofunc or not var.kind_of? Variable or not var.type.kind_of? Function
# most of the time, 'bar' is not defined anywhere, so we support it only
# to allow parsing of headers using it, hoping noone will actually use them
unused = Asm.parse(self, scope)
puts "unsupported gcc-style __asm__ function redirect #{var.name.inspect} => #{unused.body.inspect}" if $VERBOSE
break
when '='
# variable initialization
raise tok, '"{" or ";" expected' if var.type.kind_of? Function
raise tok, 'cannot initialize extern variable' if var.storage == :extern
scope.symbol[var.name] = var # allow initializer to reference var, eg 'void *ptr = &ptr;'
var.initializer = var.type.parse_initializer(self, scope)
if var.initializer.kind_of?(CExpression) and (scope == @toplevel or var.storage == :static)
raise tok, "initializer for static #{var.name} is not constant" if not var.initializer.constant?
end
reference_value = lambda { |e, v|
found = false
case e
when Variable; found = true if e == v
when CExpression; e.walk { |ee| found ||= reference_value[ee, v] } if e.op != :& or e.lexpr
end
found
}
raise tok, "initializer for #{var.name} is not constant (selfreference)" if reference_value[var.initializer, var]
raise tok || self, '"," or ";" expected' if not tok = skipspaces or tok.type != :punct
else
scope.symbol[var.name] = var
end
case tok.raw
when ','; nofunc = true
when ';'; break
when '}'; unreadtok(tok); break
else raise tok, '";" or "," expected'
end
end
true
end | 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[asm __asm __asm__].include? tok.raw
scope.statements << Asm.parse(self, scope)
true
end
end | 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 not eos?
@lexer.feed m
if e = CExpression.parse(self, Block.new(@toplevel)) and eos?
v = e.reduce(self)
return v if v.kind_of? ::Numeric
end
readtok until eos?
nil
rescue ParseError
readtok until eos?
nil
end | 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
}
end
}
@toplevel.symbol.each { |k, v|
ret << [k, v] if v.kind_of?(::Numeric) and not seen_enum[k]
}
ret
end | 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'
qualifier << tok.raw.to_sym
when 'long', 'short', 'signed', 'unsigned'
specifier << tok.raw.to_sym
when 'int', 'char', 'void', 'float', 'double', '__int8', '__int16', '__int32', '__int64'
name = tok.raw.to_sym
break
when 'intptr_t', 'uintptr_t'
name = :ptr
specifier << :unsigned if tok.raw == 'uintptr_t'
break
else
parser.unreadtok tok
break
end
end
case name
when :double # long double
if specifier == [:long]
name = :longdouble
specifier.clear
elsif not specifier.empty?
raise tok || parser, 'invalid specifier list'
end
when :int # short, long, long long X signed, unsigned
# Array#count not available on old ruby (eg 1.8.4), so use ary.len - (ary-stuff).len
specifier = specifier - [:long] + [:longlong] if specifier.length - (specifier-[:long]).length == 2
if specifier.length - (specifier-[:signed, :unsigned]).length > 1 or specifier.length - (specifier-[:short, :long, :longlong]).length > 1
raise tok || parser, 'invalid specifier list'
else
name = (specifier & [:longlong, :long, :short])[0] || :int
specifier -= [:longlong, :long, :short]
end
specifier.delete :signed # default
when :char # signed, unsigned
# signed char != char and unsigned char != char
if (specifier & [:signed, :unsigned]).length > 1 or (specifier & [:short, :long]).length > 0
raise tok || parser, 'invalid specifier list'
end
when :__int8, :__int16, :__int32, :__int64, :ptr
if (specifier & [:signed, :unsigned]).length > 1 or (specifier & [:short, :long]).length > 0
raise tok || parser, 'invalid specifier list'
end
specifier.delete :signed # default
else # none
raise tok || parser, 'invalid type' if not specifier.empty?
end
@type = BaseType.new(name, *specifier)
@type.qualifier = qualifier if not qualifier.empty?
end | 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
when 'const', 'volatile'
(ptr.qualifier ||= []) << ntok.raw.to_sym
ptr.parse_attributes(parser)
else break
end
end
parser.unreadtok ntok
parse_declarator(parser, scope, true)
t = self
t = t.type while t.type and (t.type.kind_of?(Pointer) or t.type.kind_of?(Function))
ptr.type = t.type
t.type = ptr
if t.kind_of? Function and ptr.attributes
@attributes ||= []
@attributes |= ptr.attributes
ptr.attributes = nil
end
return
elsif tok and tok.type == :punct and tok.raw == '('
parse_declarator(parser, scope, true)
raise tok || parser, '")" expected' if not tok = parser.skipspaces or tok.type != :punct or tok.raw != ')'
elsif tok and tok.type == :string
case tok.raw
when 'const', 'volatile'
(@type.qualifier ||= []) << tok.raw.to_sym
return parse_declarator(parser, scope, rec)
when 'register', 'auto', 'static', 'typedef', 'extern'
raise tok, 'multiple storage class' if storage
@storage = tok.raw.to_sym
puts tok.exception('misplaced storage specifier').message if $VERBOSE
return parse_declarator(parser, scope, rec)
end
raise tok if name or name == false
raise tok, 'bad var name' if Keyword[tok.raw] or (?0..?9).include?(tok.raw[0])
@name = tok.raw
@backtrace = tok
parse_attributes(parser, true)
else
# unnamed
raise tok || parser if name or name == false
@name = false
@backtrace = tok
parser.unreadtok tok
parse_attributes(parser, true)
end
parse_declarator_postfix(parser, scope)
if not rec
raise @backtrace, 'void type is invalid' if name and (t = @type.untypedef).kind_of? BaseType and
t.name == :void and storage != :typedef
raise @backtrace, "incomplete type #{@type.name}" if (@type.kind_of? Union or @type.kind_of? Enum) and
not @type.members and storage != :typedef and storage != :extern # gcc uses an undefined extern struct just to cast it later (_IO_FILE_plus)
end
end | 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
when '!' # != (mandatory)
if not ntok = parser.readtok or ntok.type != :punct and ntok.raw != '='
parser.unreadtok op
return
end
op.raw << ntok.raw
when '+', '-', '*', '/', '%', '^', '=', ',', '?', ':', '>>', '<<', '||', '&&',
'+=','-=','*=','/=','%=','^=','==','&=','|=','!=' # ok
else # bad
parser.unreadtok op
return
end
# may be followed by '='
case op.raw
when '+', '-', '*', '/', '%', '^', '&', '|', '>>', '<<', '<', '>', '='
if ntok = parser.readtok and ntok.type == :punct and ntok.raw == '='
op.raw << ntok.raw
else
parser.unreadtok ntok
end
end
op.value = op.raw.to_sym
op
end | 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 if v.name != false
raise tok if not ntok = parser.skipspaces or ntok.type != :punct or ntok.raw != ')'
else
raise tok, 'expr expected' if not v = parse(parser, scope)
raise tok if not ntok = parser.skipspaces or ntok.type != :punct or ntok.raw != ')'
end
else
parser.unreadtok ntok
raise tok, 'expr expected' if not v = parse_value(parser, scope)
end
tok.value = parser.sizeof(v)
return
when '__builtin_offsetof'
raise tok if not ntok = parser.skipspaces or ntok.type != :punct or ntok.raw != '('
raise tok if not ntok = parser.skipspaces or ntok.type != :string or ntok.raw != 'struct'
raise tok if not ntok = parser.skipspaces or ntok.type != :string
raise tok, 'unknown structure' if not struct = scope.struct_ancestors[ntok.raw] or not struct.kind_of? Union or not struct.members
raise tok if not ntok = parser.skipspaces or ntok.type != :punct or ntok.raw != ','
raise tok if not ntok = parser.skipspaces or ntok.type != :string
tok.value = struct.offsetof(parser, ntok.raw)
raise tok if not ntok = parser.skipspaces or ntok.type != :punct or ntok.raw != ')'
return
end
end
Expression.parse_num_value(parser, tok)
end | 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
raise tok, 'invalid variable'
when Variable
val = parse_value_postfix(parser, scope, val)
when ::Float
# parse suffix
type = :double
if (?0..?9).include?(tok.raw[0])
case tok.raw.downcase[-1]
when ?l; type = :longdouble
when ?f; type = :float
end
end
val = CExpression[val, BaseType.new(type)]
when ::Integer
# parse suffix
# XXX 010h ?
type = :int
specifier = []
if (?0..?9).include?(tok.raw[0])
suffix = tok.raw.downcase[-3, 3] || tok.raw.downcase[-2, 2] || tok.raw.downcase[-1, 1] # short string
specifier << :unsigned if suffix.include?('u') # XXX or tok.raw.downcase[1] == ?x
type = :longlong if suffix.count('l') == 2
type = :long if suffix.count('l') == 1
end
val = CExpression[val, BaseType.new(type, *specifier)]
val = parse_value_postfix(parser, scope, val)
else raise parser, "internal error #{val.inspect}"
end
when :quoted
if tok.raw[0] == ?'
raise tok, 'invalid character constant' if not [1, 2, 4, 8].include? tok.value.length # TODO 0fill
val = CExpression[Expression.decode_imm(tok.value, tok.value.length, :big), BaseType.new(:int)]
val = parse_value_postfix(parser, scope, val)
else
val = CExpression[tok.value, Pointer.new(BaseType.new(tok.raw[0, 2] == 'L"' ? :short : :char))]
val = parse_value_postfix(parser, scope, val)
end
when :punct
case tok.raw
when '('
ntok = nil
# check type casting
if v = Variable.parse_type(parser, scope)
v.parse_declarator(parser, scope)
(v.type.attributes ||= []).concat v.attributes if v.attributes
raise tok, 'bad cast' if v.name != false
raise ntok || tok, 'no ")" found' if not ntok = parser.skipspaces or ntok.type != :punct or ntok.raw != ')'
raise ntok, 'expr expected' if not val = parse_value(parser, scope) # parses postfix too
#raise ntok, 'unable to cast a struct' if val.type.untypedef.kind_of? Union
val = CExpression[[val], v.type]
# check compound statement expression
elsif ntok = parser.skipspaces and ntok.type == :punct and ntok.raw == '{'
parser.unreadtok ntok
blk = parser.parse_statement(scope, [:expression]) # XXX nesting ?
raise ntok || tok, 'no ")" found' if not ntok = parser.skipspaces or ntok.type != :punct or ntok.raw != ')'
type = blk.statements.last.kind_of?(CExpression) ? blk.statements.last.type : BaseType.new(:void)
val = CExpression[blk, type]
else
parser.unreadtok ntok
if not val = parse(parser, scope)
parser.unreadtok tok
return
end
raise ntok || tok, 'no ")" found' if not ntok = parser.readtok or ntok.type != :punct or ntok.raw != ')'
val = parse_value_postfix(parser, scope, val)
end
when '.' # float
parse_intfloat(parser, scope, tok)
if not tok.value
parser.unreadtok tok
return
end
val = tok.value || tok.raw
type = :double
case tok.raw.downcase[-1]
when ?l; type = :longdouble
when ?f; type = :float
end
val = CExpression.new[val, BaseType.new(type)]
when '+', '-', '&', '!', '~', '*', '--', '++', '&&'
# unary prefix
# may have been read ahead
raise parser if not ntok = parser.readtok
# check for -- ++ &&
if ntok.type == :punct and ntok.raw == tok.raw and %w[+ - &].include?(tok.raw)
tok.raw << ntok.raw
else
parser.unreadtok ntok
end
case tok.raw
when '&'
val = parse_value(parser, scope)
if val.kind_of? CExpression and val.op == :& and not val.lexpr and
(val.rexpr.kind_of? Variable or val.rexpr.kind_of? CExpression) and val.rexpr.type.kind_of? Function
# &&function == &function
elsif (val.kind_of? CExpression or val.kind_of? Variable) and val.type.kind_of? Array
# &ary = ary
else
raise parser, "invalid lvalue #{val}" if not CExpression.lvalue?(val) and not parser.allow_bad_c
raise val.backtrace, 'cannot take addr of register' if val.kind_of? Variable and val.storage == :register and not parser.allow_bad_c
val = CExpression.new(nil, tok.raw.to_sym, val, Pointer.new(val.type))
end
when '++', '--'
val = parse_value(parser, scope)
raise parser, "invalid lvalue #{val}" if not CExpression.lvalue?(val) and not parser.allow_bad_c
val = CExpression.new(nil, tok.raw.to_sym, val, val.type)
when '&&'
raise tok, 'label name expected' if not val = parser.skipspaces or val.type != :string
val = CExpression.new(nil, nil, Label.new(val.raw, nil), Pointer.new(BaseType.new(:void)))
when '*'
raise tok, 'expr expected' if not val = parse_value(parser, scope)
raise tok, 'not a pointer' if not val.type.pointer? and not parser.allow_bad_c
newtype = val.type.pointer? ? val.type.pointed : BaseType.new(:int)
if not newtype.untypedef.kind_of? Function # *fptr == fptr
val = CExpression.new(nil, tok.raw.to_sym, val, newtype)
end
when '~', '!', '+', '-'
raise tok, 'expr expected' if not val = parse_value(parser, scope)
raise tok, 'type not arithmetic' if not val.type.arithmetic? and not parser.allow_bad_c
val = CExpression.new(nil, tok.raw.to_sym, val, val.type)
val.type = BaseType.new(:int) if tok.raw == '!'
else raise tok, 'internal error'
end
else
parser.unreadtok tok
return
end
else
parser.unreadtok tok
return
end
if val.kind_of? Variable and val.type.kind_of? Function
# void (*bla)() = printf; => ...= &printf;
val = CExpression[:&, val]
end
val
end | 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 == '-' and ntok.raw == '>'))
tok.raw << ntok.raw
else
parser.unreadtok ntok
end
case tok.raw
when '+', '-'
nil
when '++', '--'
raise parser, "#{val}: invalid lvalue" if not CExpression.lvalue?(val)
CExpression.new(val, tok.raw.to_sym, nil, val.type)
when '->'
# XXX allow_bad_c..
raise tok, "#{val}: not a pointer" if not val.type.pointer?
type = val.type.pointed.untypedef
raise tok, "#{val}: bad pointer" if not type.kind_of? Union
raise tok, "#{val}: incomplete type" if not type.members
raise tok, "#{val}: invalid member" if not tok = parser.skipspaces or tok.type != :string or not m = type.findmember(tok.raw)
CExpression.new(val, :'->', tok.raw, m.type)
end
when '.'
type = val.type.untypedef
if not ntok = parser.skipspaces or ntok.type != :string or not type.kind_of? Union
parser.unreadtok ntok
nil
else
raise ntok, "#{val}: incomplete type" if not type.members
raise ntok, "#{val}: invalid member" if not m = type.findmember(ntok.raw)
CExpression.new(val, :'.', ntok.raw, m.type)
end
when '['
raise tok, "#{val}: index expected" if not idx = parse(parser, scope)
val, idx = idx, val if not val.type.pointer? # fake support of "4[tab]"
raise tok, "#{val}: not a pointer" if not val.type.pointer?
raise tok, "#{val}: invalid index" if not idx.type.integral?
raise tok, "#{val}: get perpendicular ! (elsewhere)" if idx.kind_of?(CExpression) and idx.op == :','
raise tok || parser, "']' expected" if not tok = parser.skipspaces or tok.type != :punct or tok.raw != ']'
type = val.type.untypedef.type
# TODO boundscheck (and become king of the universe)
CExpression.new(val, :'[]', idx, type)
when '('
type = val.type.untypedef
type = type.type.untypedef if type.kind_of? Pointer
raise tok, "#{val}: not a function" if not type.kind_of? Function
args = []
loop do
a = parse(parser, scope, false)
break if not a
args << a
if not ntok = parser.skipspaces or ntok.type != :punct or ntok.raw != ','
parser.unreadtok ntok
break
end
end
raise ntok || parser, "#{val}: ')' expected" if not ntok = parser.skipspaces or ntok.type != :punct or ntok.raw != ')'
type.args ||= []
raise tok, "#{val}: bad argument count: #{args.length} for #{type.args.length}" if (type.varargs ? (args.length < type.args.length) : (args.length != type.args.length))
type.args.zip(args) { |ta, a|
p, i = ta.type.pointer?, ta.type.integral?
r = a.reduce(parser) if p or i
if (not p and not i) or (i and not r.kind_of? ::Integer) or (p and r != 0)
tok = tok.dup ; tok.raw = a.to_s
parser.check_compatible_type(tok, a.type, ta.type)
end
}
CExpression.new(val, :funcall, args, type.type)
end
end
if nval
parse_value_postfix(parser, scope, nval)
else
parser.unreadtok tok
val
end
end | 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
struct = struct.pointed while struct.pointer?
raise "unknown struct #{structname.inspect}" if not struct.kind_of? C::Union
end
struct = structname if structname.kind_of? C::Union
raise "unknown struct #{structname.inspect}" if not struct.kind_of? C::Union
struct
end | 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)
var = Variable.parse_type(self, b)
var.parse_declarator(self, b)
type = var.type
rescue
end
end
end
type = typename if typename.kind_of?(C::Type)
raise "unknown type #{typename.inspect}" if not type.kind_of? C::Type
type
end | 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
buf = alloc_c_struct(type, val)
val.instance_variable_set('@rb2c', buf) # GC trick
val = buf
when ::Proc
val = DynLdr.convert_rb2c(type, val) # allocate a DynLdr callback
when AllocCStruct
val = DynLdr.str_ptr(val.str) + val.stroff
#when ::Float # TODO
else raise "TODO #{val.inspect}"
end
val = Expression.encode_immediate(val, sizeof(type), @endianness) if val.kind_of?(::Integer)
val
end | 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.flatten - todo_deps.keys)).empty?
ar.each { |t|
todo_rndr[t], todo_deps[t] = t.dump_def(@toplevel)
}
end
exclude.each { |t| todo_deps.delete t ; todo_rndr.delete t }
todo_deps.each_key { |t| todo_deps[t] -= exclude }
all = @toplevel.struct.values + @toplevel.symbol.values
all -= all.grep(::Integer) # Enum values
@toplevel.dump_reorder(all, todo_rndr, todo_deps)[0].join("\n")
end | 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 -= @symbol.values + @struct.values
[r, dep]
end | 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
ParseError.new msgh
end | 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
else
raise name, 'invalid argument count' if args.length < @args.length
virg = name.dup # concat remaining args in __VA_ARGS__
virg.type = :punct
virg.raw = ','
va = args[@args.length..-1].map { |a| a + [virg.dup] }.flatten
va.pop
hargs['__VA_ARGS__'] = va
end
else
hargs = {}
end
res = []
b = @body.map { |t| t = t.dup ; t.expanded_from = expfrom ; t }
while t = b.shift
if a = hargs[t.raw]
# expand macros
a = a.dup
while at = a.shift
margs = nil
if at.type == :string and am = lexer.definition[at.raw] and not at.expanded_from.to_a.find { |ef| ef.raw == @name.raw } and
((am.args and margs = Macro.parse_arglist(lexer, a)) or not am.args)
toks = am.apply(lexer, at, margs, a)
a = toks + a # reroll
else
res << at.dup if not res.last or res.last.type != :space or at.type != :space
end
end
elsif t.type == :punct and t.raw == '##'
# the '##' operator: concat the next token to the last in body
nil while t = b.shift and t.type == :space
res.pop while res.last and res.last.type == :space
if not a = hargs[t.raw]
a = [t]
end
if varargs and t.raw == '__VA_ARGS__' and res.last and res.last.type == :punct and res.last.raw == ','
if args.length == @args.length # pop last , if no vararg passed # XXX poof(1, 2,) != poof(1, 2)
res.pop
else # allow merging with ',' without warning
res.concat a
end
else
a = a[1..-1] if a.first and a.first.type == :space
if not res.last or res.last.type != :string or not a.first or a.first.type != :string
puts name.exception("cannot merge token #{res.last.raw} with #{a.first ? a.first.raw : 'nil'}").message if not a.first or (a.first.raw != '.' and res.last.raw != '.') if $VERBOSE
res.concat a
else
res[-1] = res[-1].dup
res.last.raw << a.first.raw
res.concat a[1..-1]
end
end
elsif args and t.type == :punct and t.raw == '#' # map an arg to a qstring
nil while t = b.shift and t.type == :space
t.type = :quoted
t.value = hargs[t.raw].map { |aa| aa.raw }.join
t.value = t.value[1..-1] if t.value[0] == ?\ # delete leading space
t.raw = t.value.inspect
res << t
else
res << t
end
end
res
end | 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 = lexer.readtok_nopp
t3 = lexer.readtok_nopp
t3 = lexer.readtok_nopp while t3 and t3.type == :space
raise @name, 'booh' if not t1 or t1.type != :punct or t1.raw != '.' or
not t2 or t2.type != :punct or t2.raw != '.' or
not t3 or t3.type != :punct or t3.raw != ')'
@varargs = true
break
end
break if tok and tok.type == :punct and tok.raw == ')' and @args.empty? # allow empty list
raise @name, 'invalid arg definition' if not tok or tok.type != :string
@args << tok
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 = lexer.readtok_nopp
t3 = lexer.readtok_nopp
t3 = lexer.readtok_nopp while t3 and t3.type == :space
raise @name, 'booh' if not t1 or t1.type != :punct or t1.raw != '.' or
not t2 or t2.type != :punct or t2.raw != '.' or
not t3 or t3.type != :punct or t3.raw != ')'
@varargs = true
varg = @args.pop.raw
break
end
raise @name, 'invalid arg separator' if not tok or tok.type != :punct or (tok.raw != ')' and tok.raw != ',')
break if tok.raw == ')'
end
else lexer.unreadtok tok
end
nil while tok = lexer.readtok_nopp and tok.type == :space
lexer.unreadtok tok
while tok = lexer.readtok_nopp
tok = tok.dup
case tok.type
when :eol
lexer.unreadtok tok
break
when :space
next if @body.last and @body.last.type == :space
tok.raw = ' '
when :string
tok.raw = '__VA_ARGS__' if varg and tok.raw == varg
when :punct
if tok.raw == '#'
ntok = lexer.readtok_nopp
if ntok and ntok.type == :punct and ntok.raw == '#'
tok.raw << '#'
else
lexer.unreadtok ntok
end
end
end
@body << tok
end
@body.pop if @body.last and @body.last.type == :space
# check macro is correct
invalid_body = nil
if (@body[-1] and @body[-1].raw == '##') or (@body[0] and @body[0].raw == '##')
invalid_body ||= 'cannot have ## at begin or end of macro body'
end
if args
if @args.map { |a| a.raw }.uniq.length != @args.length
invalid_body ||= 'duplicate macro parameter'
end
@body.each_with_index { |tok_, i|
if tok_.type == :punct and tok_.raw == '#'
a = @body[i+1]
a = @body[i+2] if not a or a.type == :space
if not a.type == :string or (not @args.find { |aa| aa.raw == a.raw } and (not varargs or a.raw != '__VA_ARGS__'))
invalid_body ||= 'cannot have # followed by non-argument'
end
end
}
end
if invalid_body
puts "W: #{lexer.filename}:#{lexer.lineno}, in #{@name.raw}: #{invalid_body}" if $VERBOSE
false
else
true
end
end | 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[name]
depend[name] = []
walk[name]
end
end
}
}
list.each { |mname| walk[mname] }
res = []
while not depend.empty?
todo_now = depend.keys.find_all { |k| (depend[k] - [k]).empty? }
if todo_now.empty?
dep_cycle = lambda { |ary|
deps = depend[ary.last]
if deps.include? ary.first; ary
elsif (deps-ary).find { |d| deps = dep_cycle[ary + [d]] }; deps
end
}
if not depend.find { |k, dep| todo_now = dep_cycle[[k]] }
todo_now = depend.keys
end
end
todo_now.sort.each { |k|
res << @definition[k].dump(comment) if @definition[k].kind_of? Macro
depend.delete k
}
depend.each_key { |k| depend[k] -= todo_now }
end
res.join("\n")
end | 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
# @filename[-1] used in trace_macros to distinguish generic/specific files
@filename = "\"#{filename}\""
@lineno = lineno
@pos = 0
@queue = []
@backtrace = []
self
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 line continuation
# TODO portability
if c == ?\\ and (@text[@pos] == ?\n or (@text[@pos] == ?\r and @text[@pos+1] == ?\n))
@lineno += 1
@pos += 1 if @text[@pos] == ?\r
@pos += 1
return getchar
end
if c == ?\r and @text[@pos] == ?\n
@pos += 1
c = ?\n
end
# update lineno
if c == ?\n
@lineno += 1
end
c
end | 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, ?$, ?_
tok.type = :string
raw = tok.raw << c
while c = getchar
case c
when ?a..?z, ?A..?Z, ?0..?9, ?$, ?_
else break
end
raw << c
end
ungetchar
when ?\ , ?\t, ?\r, ?\n, ?\f
tok.type = ((c == ?\ || c == ?\t) ? :space : :eol)
raw = tok.raw << c
while c = getchar
case c
when ?\ , ?\t
when ?\n, ?\f, ?\r; tok.type = :eol
else break
end
raw << c
end
ungetchar
when ?/
raw = tok.raw << c
# comment
case c = getchar
when ?/
# till eol
tok.type = :eol
raw << c
while c = getchar
raw << c
break if c == ?\n
end
when ?*
tok.type = :space
raw << c
seenstar = false
while c = getchar
raw << c
case c
when ?*; seenstar = true
when ?/; break if seenstar # no need to reset seenstar, already false
else seenstar = false
end
end
raise tok, 'unterminated c++ comment' if not c
else
# just a slash
ungetchar
tok.type = :punct
end
else
tok.type = :punct
tok.raw << c
end
tok
end | 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 ?\\
raise tok, 'unterminated escape' if not c = getchar
tok.raw << c
tok.value << \
case c
when ?n; ?\n
when ?r; ?\r
when ?t; ?\t
when ?a; ?\a
when ?b; ?\b
when ?v; ?\v
when ?f; ?\f
when ?e; ?\e
when ?#, ?\\, ?', ?"; c
when ?\n; '' # already handled by getchar
when ?x;
hex = ''
while hex.length < 2
raise tok, 'unterminated escape' if not c = getchar
case c
when ?0..?9, ?a..?f, ?A..?F
else ungetchar; break
end
hex << c
tok.raw << c
end
raise tok, 'unterminated escape' if hex.empty?
hex.hex
when ?0..?7;
oct = '' << c
while oct.length < 3
raise tok, 'unterminated escape' if not c = getchar
case c
when ?0..?7
else ungetchar; break
end
oct << c
tok.raw << c
end
oct.oct
else c # raise tok, 'unknown escape sequence'
end
when ?\n; ungetchar ; raise tok, 'unterminated string'
else tok.value << c
end
end
tok
end | 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.kind_of? ::String and eos?
feed(value, btfile, btlineno)
@definition[name].body << readtok until eos?
elsif value # XXX won't split multi-token defs..
t = Token.new([btfile, btlineno])
t.type = :string
t.raw = value.to_s
@definition[name].body << t
end
end | 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 = readtok_nopp
break tok if not tok or tok.type != :space
end
}
# XXX do not preprocess tokens when searching for :eol, it will trigger preprocessor directive detection from readtok
eol = tok = nil
case cmd.raw
when 'if'
case @ifelse_nesting.last
when :accept, nil
@ifelse_nesting << :testing
raise cmd, 'expr expected' if not test = PPExpression.parse(self)
eol = skipspc[]
raise eol, 'pp syntax error' if eol and eol.type != :eol
unreadtok eol
case test.reduce
when 0; @ifelse_nesting[-1] = :discard
when Integer; @ifelse_nesting[-1] = :accept
else @ifelse_nesting[-1] = :discard
end
when :discard, :discard_all
@ifelse_nesting << :discard_all
end
when 'ifdef'
case @ifelse_nesting.last
when :accept, nil
@ifelse_nesting << :testing
raise eol || tok || cmd, 'pp syntax error' if not tok = skipspc[] or tok.type != :string or (eol = skipspc[] and eol.type != :eol)
unreadtok eol
@ifelse_nesting[-1] = (@definition[tok.raw] ? :accept : :discard)
when :discard, :discard_all
@ifelse_nesting << :discard_all
end
when 'ifndef'
case @ifelse_nesting.last
when :accept, nil
@ifelse_nesting << :testing
raise eol || tok || cmd, 'pp syntax error' if not tok = skipspc[] or tok.type != :string or (eol = skipspc[] and eol.type != :eol)
unreadtok eol
@ifelse_nesting[-1] = (@definition[tok.raw] ? :discard : :accept)
when :discard, :discard_all
@ifelse_nesting << :discard_all
end
when 'elif'
case @ifelse_nesting.last
when :accept
@ifelse_nesting[-1] = :discard_all
when :discard
@ifelse_nesting[-1] = :testing
raise cmd, 'expr expected' if not test = PPExpression.parse(self)
raise eol, 'pp syntax error' if eol = skipspc[] and eol.type != :eol
unreadtok eol
case test.reduce
when 0; @ifelse_nesting[-1] = :discard
when Integer; @ifelse_nesting[-1] = :accept
else @ifelse_nesting[-1] = :discard
end
when :discard_all
else raise cmd, 'pp syntax error'
end
when 'else'
@ifelse_nesting << :testing
@ifelse_nesting.pop
raise eol || cmd, 'pp syntax error' if @ifelse_nesting.empty? or (eol = skipspc[] and eol.type != :eol)
unreadtok eol
case @ifelse_nesting.last
when :accept
@ifelse_nesting[-1] = :discard_all
when :discard
@ifelse_nesting[-1] = :accept
when :discard_all
end
when 'endif'
@ifelse_nesting << :testing
@ifelse_nesting.pop
raise eol || cmd, 'pp syntax error' if @ifelse_nesting.empty? or (eol = skipspc[] and eol.type != :eol)
unreadtok eol
@ifelse_nesting.pop
when 'define'
return if @ifelse_nesting.last and @ifelse_nesting.last != :accept
raise tok || cmd, 'pp syntax error' if not tok = skipspc[] or tok.type != :string
m = Macro.new(tok)
valid = m.parse_definition(self)
if not defined? @defined_strong or not @defined_strong.include? tok.raw
puts "W: pp: redefinition of #{tok.raw} at #{tok.backtrace_str},\n prev def at #{@definition[tok.raw].name.backtrace_str}" if @definition[tok.raw] and $VERBOSE and @warn_redefinition
@definition[tok.raw] = m if valid
end
when 'undef'
return if @ifelse_nesting.last and @ifelse_nesting.last != :accept
raise eol || tok || cmd, 'pp syntax error' if not tok = skipspc[] or tok.type != :string or (eol = skipspc[] and eol.type != :eol)
if not defined? @defined_strong or not @defined_strong.include? tok.raw
@definition.delete tok.raw
unreadtok eol
end
when 'include', 'include_next'
return if @ifelse_nesting.last and @ifelse_nesting.last != :accept
directive_include(cmd, skipspc)
when 'error', 'warning'
return if @ifelse_nesting.last and @ifelse_nesting.last != :accept
msg = ''
while tok = readtok_nopp and tok.type != :eol
msg << tok.raw
end
unreadtok tok
if cmd.raw == 'warning'
puts cmd.exception("#warning#{msg}").message if $VERBOSE
else
raise cmd, "#error#{msg}"
end
when 'line'
return if @ifelse_nesting.last and @ifelse_nesting.last != :accept
raise tok || cmd if not tok = skipspc[] or tok.type != :string
@lineno = Integer(tok.raw) rescue raise(tok, 'bad line number')
raise eol if eol = skipspc[] and eol.type != :eol
unreadtok eol
when 'pragma'
return if @ifelse_nesting.last and @ifelse_nesting.last != :accept
directive_pragma(cmd, skipspc)
else return false
end
# skip #ifndef'd parts of the source
state = 1 # just seen :eol
while @ifelse_nesting.last == :discard or @ifelse_nesting.last == :discard_all
begin
tok = skipspc[]
rescue ParseError
# react as gcc -E: <"> unterminated in #if 0 => ok, </*> unterminated => error (the " will fail at eol)
retry
end
if not tok; raise ocmd, 'pp unterminated conditional'
elsif tok.type == :eol; state = 1
elsif state == 1 and tok.type == :punct and tok.raw == '#'; state = 2
elsif state == 2 and tok.type == :string; state = preprocessor_directive(tok, ocmd) ? 1 : 0
else state = 0
end
end
true
end | 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
ipath = tok.value
if @filename[0] == ?< or @backtrace.find { |btf, *a| btf[0] == ?< }
# XXX local include from a std include... (kikoo windows.h !)
path = nil
if not @include_search_path.find { |d| ::File.exist?(path = ::File.join(d, ipath)) } ||
@include_search_path.find { |d| path = file_exist_nocase(::File.join(d, ipath)) } ||
path = file_exist_nocase(::File.join(::File.dirname(@filename[1..-2]), ipath))
path = nil
end
elsif ipath[0] != ?/
path = ::File.join(::File.dirname(@filename[1..-2]), ipath) if ipath[0] != ?/
path = file_exist_nocase(path || ipath) if not ::File.exist?(path || ipath)
else
path = ipath
path = file_exist_nocase(path) if not ::File.exist? path
end
else
# no more preprocessing : allow comments/multiple space/etc
ipath = ''
while tok = readtok_nopp and (tok.type != :punct or tok.raw != '>')
raise cmd, 'syntax error' if tok.type == :eol
ipath << tok.raw
end
raise cmd, 'pp syntax error, unterminated path' if not tok
if ipath[0] != ?/
path = nil
isp = @include_search_path
if cmd.raw == 'include_next'
raise self, 'include_next sux' if not idx = isp.find { |d| @filename[1, d.length] == d }
isp = isp[isp.index(idx)+1..-1]
end
if not isp.find { |d| ::File.exist?(path = ::File.join(d, ipath)) } ||
isp.find { |d| path = file_exist_nocase(::File.join(d, ipath)) }
path = nil
end
end
end
eol = nil
raise eol if eol = skipspc[] and eol.type != :eol
unreadtok eol
return if cmd.raw == 'include_next' and not path and not @hooked_include[ipath] # XXX
if not @pragma_once[path || ipath]
@backtrace << [@filename, @lineno, @text, @pos, @queue, @ifelse_nesting.length]
# gcc-style autodetect
# XXX the headers we already parsed may have needed a prepare_gcc...
# maybe restart parsing ?
if ipath == 'stddef.h' and not path and not @hooked_include[ipath]
tk = tok.dup
tk.raw = 'prepare_gcc'
@pragma_callback[tk]
if @hooked_include[ipath]
puts "metasm pp: autodetected gcc-style headers" if $VERBOSE
end
end
if @hooked_include[ipath]
path = '<hooked>/'+ipath
puts "metasm preprocessor: including #{path}" if $DEBUG
@text = @hooked_include[ipath]
else
puts "metasm preprocessor: including #{path}" if $DEBUG
raise cmd, "No such file or directory #{ipath.inspect}" if not path or not ::File.exist? path
raise cmd, 'filename too long' if path.length > 4096 # gcc
@text = ::File.read(path)
end
# @filename[-1] used in trace_macros to distinguish generic/specific files
if tok.type == :quoted
@filename = '"' + path + '"'
else
@filename = '<' + path + '>'
end
@lineno = 1
@pos = 0
@queue = []
else
puts "metasm preprocessor: not reincluding #{path} (pragma once)" if $DEBUG
end
end | 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 dir = readtok and dir.type == :space
raise cmd, 'qstring expected' if not dir or dir.type != :quoted
dir = ::File.expand_path dir.value
raise cmd, "invalid path #{dir.inspect}" if not ::File.directory? dir
@include_search_path.unshift dir
when 'push_macro', 'pop_macro'
@pragma_macro_stack ||= []
nil while lp = readtok and lp.type == :space
nil while m = readtok and m.type == :space
nil while rp = readtok and rp.type == :space
raise cmd if not rp or lp.type != :punct or rp.type != :punct or lp.raw != '(' or rp.raw != ')' or m.type != :quoted
if tok.raw == 'push_macro'
@pragma_macro_stack << @definition[m.value]
else
raise cmd, "macro stack empty" if @pragma_macro_stack.empty?
if mbody = @pragma_macro_stack.pop # push undefined macro allowed
@definition[m.value] = mbody
else
@definition.delete m.value
end
end
else
@pragma_callback[tok]
end
eol = nil
raise eol, 'eol expected' if eol = skipspc[] and eol.type != :eol
unreadtok eol
end | 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 temporary redifinition of a macro with later restoration
other directives are forwarded to @pragma_callback | 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 << ntok.raw
else
lexer.unreadtok ntok
end
# may be followed by itself
when '|', '&'
if ntok = lexer.readtok and ntok.type == :punct and ntok.raw == op.raw
op = op.dup
op.raw << ntok.raw
else
lexer.unreadtok ntok
end
# must be followed by '='
when '!', '='
if not ntok = lexer.readtok or ntok.type != :punct and ntok.raw != '='
lexer.unreadtok ntok
lexer.unreadtok tok
return
end
op = op.dup
op.raw << ntok.raw
# ok
when '^', '+', '-', '*', '/', '%', '>>', '<<', '>=', '<=', '||', '&&', '!=', '=='
# unknown
else
lexer.unreadtok tok
return
end
op.value = op.raw.to_sym
op
end | 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
end
val = tok.value[0]
when :punct
case tok.raw
when '('
val = parse(lexer)
nil while ntok = lexer.readtok and ntok.type == :space
raise tok, "')' expected after #{val.inspect} got #{ntok.inspect}" if not ntok or ntok.type != :punct or ntok.raw != ')'
when '!', '+', '-', '~'
nil while ntok = lexer.readtok and ntok.type == :space
lexer.unreadtok ntok
raise tok, 'need expression after unary operator' if not val = parse_value(lexer)
val = Expression[tok.raw.to_sym, val]
when '.'
parse_intfloat(lexer, tok)
if not tok.value
lexer.unreadtok tok
return
end
val = tok.value
else
lexer.unreadtok tok
return
end
else
lexer.unreadtok tok
return
end
nil while tok = lexer.readtok and tok.type == :space
lexer.unreadtok tok
val
end | 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 => Expression[a0, :-, a1] } }
when 'mul'; lambda { |di, a0, a1| { a0 => Expression[a0, :*, a1] } }
when 'div'; lambda { |di, a0, a1| { a0 => Expression[a0, :/, a1] } }
when 'shl'; lambda { |di, a0, a1| { a0 => Expression[a0, :<<, a1] } }
when 'shr'; lambda { |di, a0, a1| { a0 => Expression[a0, :>>, a1] } }
when 'neg'; lambda { |di, a0| { a0 => Expression[:-, a0] } }
when 'msh'; lambda { |di, a0, a1| { a0 => Expression[[a1, :&, 0xf], :<<, 2] } }
when 'jmp', 'jg', 'jge', 'je', 'jtest', 'ret'; lambda { |di, *a| { } }
end
@backtrace_binding[op] ||= binding if binding
}
@backtrace_binding
end | 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|
e_op = { 'add' => :+, 'adc' => :+, 'sub' => :-, 'sbc' => :-, 'and' => :&,
'xor' => :^, 'or' => :|, 'addi' => :+, 'subi' => :- }[op]
ret = Expression[a0, e_op, a1]
ret = Expression[ret, e_op, :flag_c] if op == 'adc' or op == 'sbb'
# optimises eax ^ eax => 0
# avoid hiding memory accesses (to not hide possible fault)
ret = Expression[ret.reduce] if not a0.kind_of? Indirection
{ a0 => ret }
}
when 'cmp', 'test'; lambda { |di, *a| {} }
when 'not'; lambda { |di, a0| { a0 => Expression[a0, :^, mask] } }
when 'call'
lambda { |di, a0| { :sp => Expression[:sp, :-, 2],
Indirection[:sp, 2, di.address] => Expression[di.next_addr] }
}
when 'ret'; lambda { |di, *a| { :sp => Expression[:sp, :+, 2] } }
# TODO callCC, retCC ...
when /^j/; lambda { |di, *a| {} }
end
# TODO flags ?
@backtrace_binding[op] ||= binding if binding
}
@backtrace_binding
end | 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,
:snapshot_addr => faddr, :origin => retaddr)
}
if bt.length != 1
b[r] = Expression::Unknown
else
b[r] = bt.first
end
}
if not wantregs.empty?
wantregs.each(&bt_val)
else
bt_val[:sp]
end
b
end | 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 != :default
btfor
elsif di = dasm.decoded[calladdr] and di.opcode.props[:saveip]
btfor
else []
end
}
df
end | 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|
next if exempt.include? regval
not @state.inuse.find { |val|
case val
when Reg; val.val == regval
when ModRM; (val.b and val.b.val == regval) or (val.i and val.i.val == regval)
when Composite; val.low.val == regval or val.high.val == regval
else raise 'internal error - inuse ' + val.inspect
end
}
}
end | 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 update state.cache here, never recursive
v = raise "find dynamic addr of #{var.name}"
when ::Integer
# stack
# TODO -fomit-frame-pointer ( => state.cache dependant on stack_offset... )
v = ModRM.new(@cpusz, sz, nil, nil, @state.saved_ebp, Expression[-off])
when nil
# global
if @exeformat.cpu.generate_PIC
if not reg = @state.cache.index('metasm_intern_geteip')
@need_geteip_stub = true
if @state.used.include? 6 # esi
reg = findreg
else
reg = getreg 6
end
if reg.val != 0
if @state.used.include? 0
eax = Reg.new(0, @cpusz)
instr 'mov', reg, eax
else
eax = getreg 0
end
end
instr 'call', Expression['metasm_intern_geteip']
if reg.val != 0
if @state.used.include? 0
instr 'xchg', eax, reg
else
instr 'mov', reg, eax
end
end
@state.cache[reg] = 'metasm_intern_geteip'
end
v = ModRM.new(@cpusz, sz, nil, nil, reg, Expression[var.name, :-, 'metasm_intern_geteip'])
else
v = ModRM.new(@cpusz, sz, nil, nil, nil, Expression[var.name])
end
end
case var.type
when C::Array; inuse Address.new(v)
else inuse v
end
end | 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.cache[reg] = e
reg
end | 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_parts e
instr 'mov', e2l, el
instr 'mov', e2h, eh
e2 = inuse Composite.new(e2l, e2h)
unuse e2l, e2h
else
unuse e
n = type.integral? ? type.name : :ptr
if (sz = typesize[n]*8) < @cpusz or sz < rsz or e.sz < rsz
e2 = inuse findreg(rsz)
op = ((type.specifier == :unsigned) ? 'movzx' : 'movsx')
op = 'mov' if e.sz == e2.sz
else
e2 = inuse findreg(sz)
op = 'mov'
end
instr op, e2, e
end
@state.cache[e2] = oldval if oldval and e.kind_of? ModRM
e2
elsif type.float?
raise 'bad float static' + e.inspect if not e.kind_of? ModRM
unuse e
instr 'fld', e
FpReg.new nil
else raise
end
elsif e.kind_of? Address
make_volatile resolve_address(e), type, rsz
elsif e.kind_of? Expression
if type.integral? or type.pointer?
if type.integral? and type.name == :__int64 and @cpusz != 64
e2 = inuse Composite.new(inuse(findreg(32)), findreg(32))
instr 'mov', e2.low, Expression[e, :&, 0xffff_ffff]
instr 'mov', e2.high, Expression[e, :>>, 32]
else
e2 = inuse findreg
instr 'mov', e2, e
end
e2
elsif type.float?
case e.reduce
when 0; instr 'fldz'
when 1; instr 'fld1'
else
esp = Reg.new(4, @cpusz)
instr 'push.i32', Expression[e, :>>, 32]
instr 'push.i32', Expression[e, :&, 0xffff_ffff]
instr 'fild', ModRM.new(@cpusz, 64, nil, nil, esp, nil)
instr 'add', esp, 8
end
FpReg.new nil
end
else
e
end
end | copies the arg e to a volatile location (register/composite) if it is not already
unuses the old storage
may return a register bigger than the type size (eg __int8 are stored in full reg size)
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
[el, eh]
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::BaseType.new(:void), 1)))
else puts "ia32/c_ce_i: unsupported #{expr}" if $VERBOSE
end
end | 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 = c_cexpr_inner(expr.rexpr)
op = expr.op.to_s.chop.to_sym
c_cexpr_inner_arith(l, op, r, expr.type)
instr 'fstp', l if expr.type.float?
l
when :'+', :'-', :'*', :'/', :'%', :'^', :'&', :'|', :'<<', :'>>'
# both sides are already cast to the same type by the precompiler
# XXX expr.type.pointer?
if expr.type.integral? and expr.type.name == :ptr and expr.lexpr.type.kind_of? C::BaseType and
typesize[expr.lexpr.type.name] == typesize[:ptr]
expr.lexpr.type.name = :ptr
end
l = c_cexpr_inner(expr.lexpr)
l = make_volatile(l, expr.type) if not l.kind_of? Address
if expr.type.integral? and expr.type.name == :ptr and l.kind_of? Reg
unuse l
l = Address.new ModRM.new(l.sz, @cpusz, nil, nil, l, nil)
inuse l
end
if l.kind_of? Address and expr.type.integral?
l.modrm.imm = nil if l.modrm.imm and not l.modrm.imm.op and l.modrm.imm.rexpr == 0
if l.modrm.b and l.modrm.i and l.modrm.s == 1 and l.modrm.b.val == l.modrm.i.val
unuse l.modrm.b if l.modrm.b != l.modrm.i
l.modrm.b = nil
l.modrm.s = 2
end
case expr.op
when :+
rexpr = expr.rexpr
rexpr = rexpr.rexpr while rexpr.kind_of? C::CExpression and not rexpr.op and rexpr.type.integral? and
rexpr.rexpr.kind_of? C::CExpression and rexpr.rexpr.type.integral? and
typesize[rexpr.type.name] == typesize[rexpr.rexpr.type.name]
if rexpr.kind_of? C::CExpression and rexpr.op == :* and rexpr.lexpr
r1 = c_cexpr_inner(rexpr.lexpr)
r2 = c_cexpr_inner(rexpr.rexpr)
r1, r2 = r2, r1 if r1.kind_of? Expression
if r2.kind_of? Expression and [1, 2, 4, 8].include?(rr2 = r2.reduce)
case r1
when ModRM, Address, Reg
r1 = make_volatile(r1, rexpr.type) if not r1.kind_of? Reg
if not l.modrm.i or (l.modrm.i.val == r1.val and l.modrm.s == 1 and rr2 == 1)
unuse l, r1, r2
l = Address.new(l.modrm.dup)
inuse l
l.modrm.i = r1
l.modrm.s = (l.modrm.s || 0) + rr2
return l
end
end
end
r = make_volatile(r1, rexpr.type)
c_cexpr_inner_arith(r, :*, r2, rexpr.type)
else
r = c_cexpr_inner(rexpr)
end
r = resolve_address r if r.kind_of? Address
r = make_volatile(r, rexpr.type) if r.kind_of? ModRM
case r
when Reg
unuse l
l = Address.new(l.modrm.dup)
inuse l
if l.modrm.b
if not l.modrm.i or (l.modrm.i.val == r.val and l.modrm.s == 1)
l.modrm.i = r
l.modrm.s = (l.modrm.s || 0) + 1
unuse r
return l
end
else
l.modrm.b = r
unuse r
return l
end
when Expression
unuse l, r
l = Address.new(l.modrm.dup)
inuse l
l.modrm.imm = Expression[l.modrm.imm, :+, r]
return l
end
when :-
r = c_cexpr_inner(expr.rexpr)
r = resolve_address r if r.kind_of? Address
if r.kind_of? Expression
unuse l, r
l = Address.new(l.modrm.dup)
inuse l
l.modrm.imm = Expression[l.modrm.imm, :-, r]
return l
end
when :*
r = c_cexpr_inner(expr.rexpr)
if r.kind_of? Expression and [1, 2, 4, 8].includre?(rr = r.reduce)
if l.modrm.b and not l.modrm.i
if rr != 1
l.modrm.i = l.modrm.b
l.modrm.s = rr
l.modrm.imm = Expression[l.modrm.imm, :*, rr] if l.modrm.imm
end
unuse r
return l
elsif l.modrm.i and not l.modrm.b and l.modrm.s*rr <= 8
l.modrm.s *= rr
l.modrm.imm = Expression[l.modrm.imm, :*, rr] if l.modrm.imm and rr != 1
unuse r
return l
end
end
end
end
l = make_volatile(l, expr.type) if l.kind_of? Address
r ||= c_cexpr_inner(expr.rexpr)
c_cexpr_inner_arith(l, expr.op, r, expr.type)
l
when :'='
r = c_cexpr_inner(expr.rexpr)
l = c_cexpr_inner(expr.lexpr)
raise 'bad lvalue ' + l.inspect if not l.kind_of? ModRM and not @state.bound.index(l)
r = resolve_address r if r.kind_of? Address
r = make_volatile(r, expr.type) if l.kind_of? ModRM and r.kind_of? ModRM
unuse r
if expr.type.integral? or expr.type.pointer?
if expr.type.integral? and expr.type.name == :__int64 and @cpusz != 64
ll, lh = get_composite_parts l
rl, rh = get_composite_parts r
instr 'mov', ll, rl
instr 'mov', lh, rh
elsif r.kind_of? Address
m = r.modrm.dup
m.sz = l.sz
instr 'lea', l, m
else
if l.kind_of? ModRM and r.kind_of? Reg and l.sz != r.sz
raise if l.sz > r.sz
if l.sz == 8 and r.val >= 4
reg = ([0, 1, 2, 3] - @state.used).first
if not reg
eax = Reg.new(0, r.sz)
instr 'push', eax
instr 'mov', eax, r
instr 'mov', l, Reg.new(eax.val, 8)
instr 'pop', eax
else
flushecachereg(reg)
instr 'mov', Reg.new(reg, r.sz), r
instr 'mov', l, Reg.new(reg, 8)
end
else
instr 'mov', l, Reg.new(r.val, l.sz)
end
else
instr 'mov', l, r
end
end
elsif expr.type.float?
r = make_volatile(r, expr.type) if r.kind_of? Expression
instr 'fstp', l
end
l
when :>, :<, :>=, :<=, :==, :'!='
l = c_cexpr_inner(expr.lexpr)
l = make_volatile(l, expr.type)
r = c_cexpr_inner(expr.rexpr)
unuse r
if expr.lexpr.type.integral? or expr.lexpr.type.pointer?
if expr.lexpr.type.integral? and expr.lexpr.type.name == :__int64 and @cpusz != 64
raise # TODO
end
instr 'cmp', l, r
elsif expr.lexpr.type.float?
raise # TODO
instr 'fucompp', l, r
l = inuse findreg
else raise 'bad comparison ' + expr.to_s
end
opcc = getcc(expr.op, expr.type)
if @exeformat.cpu.opcode_list_byname['set'+opcc]
instr 'set'+opcc, Reg.new(l.val, 8)
instr 'and', l, 1
else
instr 'mov', l, Expression[1]
label = new_label('setcc')
instr 'j'+opcc, Expression[label]
instr 'mov', l, Expression[0]
@source << Label.new(label)
end
l
else
raise 'unhandled cexpr ' + expr.to_s
end
end | 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', 'xor'
r = make_volatile(r, type) if l.kind_of? ModRM and r.kind_of? ModRM
unuse r
r = Reg.new(r.val, l.sz) if r.kind_of?(Reg) and l.kind_of?(ModRM) and l.sz and l.sz != r.sz # add byte ptr [eax], bl
instr op, l, r
when 'shr', 'sar', 'shl'
if r.kind_of? Expression
instr op, l, r
else
# XXX bouh
r = make_volatile(r, C::BaseType.new(:__int8, :unsigned))
unuse r
if r.val != 1
ecx = Reg.new(1, 32)
instr 'xchg', ecx, Reg.new(r.val, 32)
l = Reg.new(r.val, l.sz) if l.kind_of? Reg and l.val == 1
@state.used.delete r.val if not @state.used.include? 1
inuse ecx
end
instr op, l, Reg.new(1, 8)
instr 'xchg', ecx, Reg.new(r.val, 32) if r.val != 1
end
when 'mul'
if l.kind_of? ModRM
if r.kind_of? Expression
ll = findreg
instr 'imul', ll, l, r
else
ll = make_volatile(l, type)
unuse ll
instr 'imul', ll, r
end
instr 'mov', l, ll
else
instr 'imul', l, r
end
unuse r
when 'div', 'mod'
lv = l.val if l.kind_of? Reg
eax = Reg.from_str 'eax'
edx = Reg.from_str 'edx'
if @state.used.include? eax.val and lv != eax.val
instr 'push', eax
saved_eax = true
end
if @state.used.include? edx.val and lv != edx.val
instr 'push', edx
saved_edx = true
end
instr 'mov', eax, l if lv != eax.val
if r.kind_of? Expression
instr 'push', r
esp = Reg.from_str 'esp'
r = ModRM.new(@cpusz, 32, nil, nil, esp, nil)
need_pop = true
end
if type.specifier == :unsigned
instr 'mov', edx, Expression[0]
instr 'div', r
else
instr 'cdq'
instr 'idiv', r
end
unuse r
instr 'add', esp, 4 if need_pop
if op == 'div'
instr 'mov', l, eax if lv != eax.val
else
instr 'mov', l, edx if lv != edx.val
end
instr 'pop', edx if saved_edx
instr 'pop', eax if saved_eax
end
end | 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
# 1ULL << 2 -> 2 is not ULL
r = make_volatile(r, C::BaseType.new("__int#{r.sz}".to_sym)) if l.kind_of? ModRM and r.kind_of? ModRM
rl, rh = get_composite_parts(r) if not r.kind_of? Reg
case op
when 'add', 'sub', 'and', 'or', 'xor'
unuse r
instr op, ll, rl
op = {'add' => 'adc', 'sub' => 'sbb'}[op] || op
instr op, lh, rh unless (op == 'or' or op == 'xor') and rh.kind_of?(Expression) and rh.reduce == 0
when 'shl', 'shr', 'sar'
rlc = r.reduce if r.kind_of? Expression
opd = { 'shl' => 'shld', 'shr' => 'shrd', 'sar' => 'shrd' }[op]
ll, lh = lh, ll if op != 'shl' # OMGHAX
llv = ll
if llv.kind_of? ModRM
llv = make_volatile(llv, C::BaseType.new(:__int32))
inuse ll
end
if rlc.kind_of? Integer
case rlc
when 0
when 1..31
instr opd, llv, lh, Expression[rlc]
instr op, ll, Expression[rlc]
when 32..63
instr 'mov', lh, llv
if op == 'sar'
instr 'sar', ll, Expression[31]
else
instr 'mov', ll, Expression[0]
end
instr op, lh, Expression[rlc-32] if rlc != 32
else
if op == 'sar'
instr 'sar', ll, Expression[31]
instr 'mov', lh, llv
else
instr 'mov', ll, Expression[0]
instr 'mov', lh, Expression[0]
end
end
else
r = make_volatile(r, C::BaseType.new(:__int8, :unsigned))
r = r.low if r.kind_of? Composite
rl ||= r
cl = Reg.new(1, 8)
ecx = Reg.new(1, 32)
if r.val != 1
instr 'xchg', ecx, Reg.new(r.val, 32)
lh = Reg.new(r.val, lh.sz) if lh.kind_of?(Reg) and lh.val == 1
ll = Reg.new(r.val, ll.sz) if ll.kind_of?(Reg) and ll.val == 1
llv = Reg.new(r.val, llv.sz) if llv.kind_of?(Reg) and llv.val == 1
@state.used.delete r.val if not @state.used.include? 1
inuse ecx
end
labelh = new_label('shldh')
labeld = new_label('shldd')
instr 'test', ecx, Expression[0x20]
instr 'jnz', Expression[labelh]
instr opd, llv, lh, cl
instr op, ll, cl
instr 'jmp', Expression[labeld]
@source << Label.new(labelh)
instr op, llv, cl
instr 'mov', lh, llv
if op == 'sar'
instr 'sar', ll, Expression[31]
else
instr 'mov', ll, Expression[0]
end
@source << Label.new(labeld)
instr 'xchg', ecx, Reg.new(r.val, 32) if r.val != 1
unuse ecx
unuse r
end
when 'mul'
# high = (low1*high2) + (high1*low2) + (low1*low2).high
t1 = findreg(32)
t2 = findreg(32)
unuse t1, t2, r
instr 'mov', t1, ll
instr 'mov', t2, rl
instr 'imul', t1, rh
instr 'imul', t2, lh
instr 'add', t1, t2
raise # TODO push eax/edx, mul, pop
instr 'mov', eax, ll
if rl.kind_of? Expression
instr 'mov', t2, rl
instr 'mul', t2
else
instr 'mul', rl
end
instr 'add', t1, edx
instr 'mov', lh, t1
instr 'mov', ll, eax
when 'div'
raise # TODO
when 'mod'
raise # TODO
end
end | 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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.