Skip to content

Instantly share code, notes, and snippets.

@ivg
Created January 28, 2021 21:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivg/d3d844f75a7783545bbc8cfb6dc3d1e1 to your computer and use it in GitHub Desktop.
Save ivg/d3d844f75a7783545bbc8cfb6dc3d1e1 to your computer and use it in GitHub Desktop.
implements a `lisp-demo` command in bap that translates lisp programs into BIL programs
open Core_kernel
open Bap.Std
open Bap_core_theory
open Bap_main
open Bap_primus.Std
open KB.Syntax
let show name =
Toplevel.exec @@ begin
Primus.Lisp.Unit.create Theory.Target.unknown >>= fun unit ->
KB.Object.scoped Theory.Program.cls @@ fun obj ->
KB.sequence [
KB.provide Theory.Label.unit obj (Some unit);
KB.provide Theory.Label.name obj (Some name);
] >>= fun () ->
KB.collect Theory.Semantics.slot obj >>| fun sema ->
Format.eprintf "%s:@ %a@." name Bil.pp (Insn.bil sema)
end
let () =
let open Extension in
let names = Command.arguments Type.string in
Extension.Command.(declare "lisp-demo" (args $ names))
@@ fun names _ctxt ->
List.iter ~f:show names;
Ok ()
@ivg
Copy link
Author

ivg commented Jan 28, 2021

Building

bapbuild -pkg bap-primus lisp_demo.plugin && bapbundle install lisp_demo.plugin 

Running

  1. create a lisp file with some Primus Lisp definitions in it, e.g.,
;; file demo.lisp

(defun example1 (x)
  (set R0 1)
  (set R1 2)
  (set R3 (+ R1 R2 (* R1 R2 3)))
  (set F1:1 (< R0 R1))
  (set F2:1 (< R0 R1 R2 R3 R4))
  (set F3:1 (< R0 (+ R0 R3)))
  (set R4 (memory-read (+ R1 (* 8 (/ (word-width) 4)))))
  (memory-write R4 (+ R3 R1))
  (malloc R0)
  (if (> R0 (* R0 R0))
      (exec-addr 0xDEADBEEF)
    (set R0 (* R0 R2 R3))
    (malloc (* R3 R0))))
  1. run bap specifying this file via the --primus-lisp-load parameter and passing the list of definitions that you like to be printed,
bap lisp-demo --primus-lisp-load=demo example1

It shall print something like this (give the example above),

example1:
{
  R0 := 1
  R1 := 2
  R3 := R1 + R2 + R1 * R2 * 3
  F1 := R0 < R1
  F2 := R0 < R1 & R1 < R2 & R2 < R3 & R3 < R4
  F3 := R0 < R0 + R3
  R4 := pad:32[mem[R1 + 0x40]]
  mem := mem with [R4, be]:u32 <- R3 + R1
  bap:call(malloc)
  #1 := R0 * R0 < R0
  if (#1) {
    jmp 0xDEADBEEF
  }
  else {
    R0 := R0 * R2 * R3
    bap:call(malloc)
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment