Skip to content

Instantly share code, notes, and snippets.

@nuclearace
Last active January 4, 2019 18:56
Show Gist options
  • Select an option

  • Save nuclearace/43df2f7a2b94cf384e85cfbcd67733a2 to your computer and use it in GitHub Desktop.

Select an option

Save nuclearace/43df2f7a2b94cf384e85cfbcd67733a2 to your computer and use it in GitHub Desktop.
Executable memory
import Foundation
typealias TwoIntsOneInt = @convention(c) (Int, Int) -> Int
let code = [
0x55, // push rbp
0x48, 0x89, 0xE5, // mov rbp, rsp
0x48, 0x8D, 0x04, 0x37, // lea rax, [rdi + rsi]
0x5D, // pop rbp
0xC3 // ret
] as [UInt8]
func fudge(x: Int, y: Int) -> Int {
let buf = mmap(nil, code.count, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_ANON, -1, 0)
memcpy(buf, code, code.count)
let fun = unsafeBitCast(buf, to: TwoIntsOneInt.self)
let ret = fun(x, y)
munmap(buf, code.count)
return ret
}
print(fudge(x: 7, y: 12))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment