Skip to content

Instantly share code, notes, and snippets.

@shihgianlee
Created July 23, 2011 13:02
Show Gist options
  • Save shihgianlee/1101398 to your computer and use it in GitHub Desktop.
Save shihgianlee/1101398 to your computer and use it in GitHub Desktop.
require 'java'
require 'rubygems'
require 'mvn:org.jruby.extras:jnr-x86asm'
require 'ffi'
require 'udis86'
Asm = Java::jnr.x86asm.Asm
PM = Java::com.kenai.jffi.PageManager
# Create a simple native function that returns 0xdeadbeef
asm = Java::jnr.x86asm.Assembler.new Asm::X86_64
asm.mov Asm::rax, Asm::imm(0xdeadbeef)
asm.ret
# Get some native memory to write the code into
pg = PM.instance.allocate_pages(1, PM::PROT_READ | PM::PROT_WRITE)
buf = java.nio.ByteBuffer.allocate(asm.code_size)
asm.reloc_code(buf, pg)
buf.flip
code = FFI::Pointer.new(pg)
code.put_bytes(0, String.from_java_bytes(buf.array), 0, asm.code_size)
# Make the page executable (and non-writable, since some OS require that)
PM.instance.protect_pages(pg, 1, PM::PROT_READ | PM::PROT_EXEC)
puts "disassembly:"
FFI::UDis86::UD.create(:mode => 64, :syntax => :intel, :buffer => code.get_bytes(0, asm.code_size)).disas do |insn|
puts "\t#{insn}"
end
puts
# Wire up the function via FFI, and call it
fptr = FFI::Function.new :ulong, [ ], code
puts "function returns: #{fptr.call.to_s(16)}"
$ env LD_LIBRARY_PATH=/opt/local/lib jruby -J-d64 asm_test.rb
disassembly:
mov rax, 0xdeadbeef
ret
function returns: deadbeef
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment