Monday, January 09, 2006

Ruby interpreter crashes with invalid input

Last week I found a bug in ruby's parser, NULL pointer reference will happen when the following program is parsed:


C:\ruby-1.8.4-i386-mswin32\bin>ruby -e 'def a=.a=;end'
-e:1: identifier a= is not valid
-e:1: [BUG] Segmentation fault ruby 1.8.4 (2005-12-24) [i386-mswin32]
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.


Now it was fixed in CVS.

This is not a serious security problem. I tried to find if it will result in a remote DOS vulnerability in Ruby on Rails, but find nothing.

Friday, January 06, 2006

Why "undef" is keyword in ruby

undef is a keyword in ruby. But its syntax:
"undef method-name (, method-name)*", looks just like a normal command call (function call without parameter, e.g. print "hello"). Then why not just implement it as a built-in method? As we know, "private", "protected" and "public", which are keywords in lots of other language, are just implemented as plain method in ruby.

What makes "undef" special is in attribute methods. In ruby we can define method like this:

class A
  def a=(value)
    @value = value
  end
end


And later, we can undefine "a=" with "undef":

undef a=


"a=" is not a valid identifier(because of the '=') unless the parser is expecting a method name, for example, after "alias", "def" or "undef".

Note ":a=" is valid symbol. "private", "protected" and "public" are normal methods since they only accept symbols:


class MyClass

  def method1
  end

  public :method1
  #This is invalid: public method1
end


Since "undef" is followed by method name, it has to be implemented as a keyword, so the parser/lexer knows when to change its state to accept the extra '='.