Skip to content

Instantly share code, notes, and snippets.

@williballenthin
Last active July 29, 2017 03:25
Show Gist options
  • Save williballenthin/9af9bdb737b66f2e9017cf6d90b9225f to your computer and use it in GitHub Desktop.
Save williballenthin/9af9bdb737b66f2e9017cf6d90b9225f to your computer and use it in GitHub Desktop.
demo of using capstone from clojure
(ns capstone-clj.core-test
(:require [clojure.test :refer :all])
(:import [capstone.Capstone]))
(deftest basic-capstone
"
this is the example from:
http://www.capstone-engine.org/lang_java.html
"
(testing "basic capstone"
(let [arch capstone.Capstone/CS_ARCH_X86
mode capstone.Capstone/CS_MODE_64
flavor capstone.Capstone/CS_OPT_SYNTAX_INTEL
cs (capstone.Capstone. arch mode)
_ (.setSyntax cs flavor)
_ (.setDetail cs 1)]
(let [code (byte-array [0x55
0x48
0x8b
0x05
0xb8
0x13
0x00
0x00])
insns (.disasm cs code 0x1000)]
(testing "disassemble"
(is (= (alength insns) 2))
(doseq [[i insn] (map-indexed vector insns)]
(let [addr (.-address insn)
mnem (.-mnemonic insn)
op (.-opStr insn)]
(printf "0x%x:\t%s\t%s\n" addr mnem op)
(condp = i
0 (testing "first opcode"
(is (= addr 0x1000))
(is (= mnem "push")))
1 (testing "second opcode"
(is (= addr 0x1001))
(is (= mnem "mov")))))))))))
(ns unicorn-clj.core-test
(:require [clojure.test :refer :all])
(:import [unicorn]))
(deftest basic-unicorn
"
this is the example from:
http://www.unicorn-engine.org/docs/tutorial.html
"
(testing "basic unicorn"
(let [arch unicorn.Unicorn/UC_ARCH_X86
mode unicorn.Unicorn/UC_MODE_32
mu (unicorn.Unicorn. arch mode)
code (byte-array [0x41 0x4a])
addr 0x1000000]
(doto mu
(.mem_map addr (* 2 1024 1024) unicorn.Unicorn/UC_PROT_EXEC)
(.mem_write addr code)
(.reg_write unicorn.Unicorn/UC_X86_REG_ECX 0x1234)
(.reg_write unicorn.Unicorn/UC_X86_REG_EDX 0x7890)
(.emu_start addr (+ addr (alength code)) 0 0))
(let [ecx (bit-and 0xFFFFFFFF (.reg_read mu unicorn.Unicorn/UC_X86_REG_ECX))
edx (bit-and 0xFFFFFFFF (.reg_read mu unicorn.Unicorn/UC_X86_REG_EDX))]
(printf "ecx: 0x%x\n" ecx)
(printf "edx: 0x%x\n" edx)
(testing "emulation"
(is (= ecx 0x1235))
(is (= edx 0x788f)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment