This post originated from an RSS feed registered with Ruby Buzz
by Ryan Davis.
Original Post: RubyToRubyC - ruby's first real obfuscator?
Feed Title: Polishing Ruby
Feed URL: http://blog.zenspider.com/index.rdf
Feed Description: Musings on Ruby and the Ruby Community...
Eric did something very very cool the other day. He wrote a new tail to the ruby2c pipeline that outputs Ruby C instead of generic C. As a result, he is able to automatically translate the following:
$ cat demo/factorial.rb
class F
def factorial(n)
f = 1
n.downto(2) { |x| f *= x }
return f
end
def main # horrid but funny hack
return factorial(5)
end
end
into:
// BEGIN METARUBY PREAMBLE
#include <ruby.h>
#define case_equal_long(x, y) (rb_funcall((x), rb_intern("==="), 1, (y)))
// END METARUBY PREAMBLE
// class F < Object
static VALUE
rrc_cF_factorial(VALUE __self, VALUE n) {
VALUE f;
VALUE x;
f = LONG2FIX(1);
x = n;
while (RTEST(rb_funcall(x, rb_intern(">="), 1, LONG2FIX(2)))) {
f = rb_funcall(f, rb_intern("*"), 1, x);
x = rb_funcall(x, rb_intern("-"), 1, LONG2FIX(1));
};
return f;
}
void
Init_F() {
VALUE rrc_cF = rb_define_class("F", rb_path2class("Object"));
rb_define_method(rrc_cF, "factorial", rrc_cF_factorial, 1);
}
As a result, pretty much any ruby code can be automatically translated to C with no real effort on our part. We can even bypass the type inference engine (for now at least). I think this is the first real step towards a ruby obfuscator.