Skip to content

Instantly share code, notes, and snippets.

@tenderlove
Created May 3, 2022 23:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tenderlove/8148b08fa26d3a6782638d203bf7c915 to your computer and use it in GitHub Desktop.
Save tenderlove/8148b08fa26d3a6782638d203bf7c915 to your computer and use it in GitHub Desktop.
require "fisk"
require "aarch64"
require "jit_buffer"
require "fiddle"
x86 = Fisk.new
x86.put_label(:foo)
x86.mov(x86.rax, x86.imm(42))
x86.ret
x86.jmp(x86.label(:foo))
arm = AArch64::Assembler.new
# This movz is specially crafted to use the same bytes as
# the `jmp` in the x86 code
arm.movz(AArch64::Registers::X11, 0x7b7)
# This movz just puts 43 in the return register
arm.movz(AArch64::Registers::X0, 43)
arm.ret
# The last two bytes of the x86 code are the same as
# the first two bytes of the ARM code.
data = x86.to_binary.bytes + arm.to_binary.bytes.drop(2)
jit = JITBuffer.new 4096
jit.writeable!
jit.write data.pack("C*")
jit.executable!
func = Fiddle::Function.new(jit.to_i + 8, [], Fiddle::TYPE_INT)
# This returns 43 when run on ARM, returns 42 on x86
p func.call
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment