Ruby 2.0 Bytecode Export / Import

大兔子大兔子 提交于 2019-12-04 18:17:26

问题


I've been reading about the new ruby 2.0 features, and found that it will support bytecode import / export:

Ruby 2.0 is expected to make it simple to save pre-compiled Ruby scripts to bytecode representations and to then run these directly.

I've installed ruby-2.0.0-p0, but I didn't find any information on how to export the bytecode (or generally documentation on that matter). Is this feature already implemented, and if so, how do I use it?

I'm also wondering about some of the details. Is YARV-bytecode supposed to be platform-independent? Are all gems automatically included in the bytecode?


回答1:


Until someone with better information looks at this question, I did some research:

Is this feature already implemented, and if so, how do I use it?

It is implemented, but it doesn't seem to be exposed (e.g ruby --dump-bytecode doesn't exist). Also there's not very much documentation. As far as I can tell, what you are looking for is something like:

seq = RubyVM::InstructionSequence.compile_file("./example.rb")

seq.disassemble will give you a nicely formatted string that you could dump to a file, or seq.to_a will generate an an array that looks like:

["YARVInstructionSequence/SimpleDataFormat",
 2,
 0,
 1,
 {:arg_size=>0, :local_size=>1, :stack_max=>2},
 "<main>",
 "./example.rb",
 "./example.rb",
 1,
 :top,
 [],
 0,
 [],
 [[:trace, 1],
  [:putspecialobject, 3],
  [:putnil],
  [:defineclass,
   :User,
   ["YARVInstructionSequence/SimpleDataFormat",
    2,
    0,
    1,
    {:arg_size=>0, :local_size=>1, :stack_max=>6},
    "<class:User>",
    ....

If you want to persist this to a file, you can do something like:

File.write("out.dump", Marshal.dump(seq.to_a))

And then to load again:

arr = Marshal.load(File.read("out.dump"))

Unfortunately I can't seem to figure out how to create a new InstructionSequence given the array loaded above.

I'm also wondering about some of the details. Is YARV-bytecode supposed to be platform-independent? Are all gems automatically included in the bytecode?

In the example above, gems are not included. Your InstructionSequence would include the bytecode equivalent of a require 'active_record' or what have you. I suspect that if dumping and loading of bytecode were provided directly by a ruby executable, this behavior would stay the same.

If anyone else has more information I'd love to see it!




回答2:


Unfortunately it looks like the verifier didn't get implemented in 2.0-p0, and as a result the load functionality is still commented out (from iseq.c, line 2260):

/* disable this feature because there is no verifier. */
/* rb_define_singleton_method(rb_cISeq, "load", iseq_s_load, -1); */


来源:https://stackoverflow.com/questions/14398964/ruby-2-0-bytecode-export-import

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!