Skip to content

Commit

Permalink
feat: implement Go API for serialization/deserialization
Browse files Browse the repository at this point in the history
  • Loading branch information
plusvic committed Feb 24, 2024
1 parent 74c7854 commit 543a2a6
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
17 changes: 16 additions & 1 deletion go/compiler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,21 @@ func TestNamespaces(t *testing.T) {
assert.Len(t, matchingRules, 2)
}

func TestSerialization(t *testing.T) {
c := NewCompiler()
c.AddSource("rule test { condition: true }")
b, _ := c.Build().Serialize()
r, _ := Deserialize(b)

s := NewScanner(r)
matchingRules, _ := s.Scan([]byte{})

assert.Len(t, matchingRules, 1)

_, err := Deserialize(nil)
assert.NoError(t, err)
}

func TestVariables(t *testing.T) {
c := NewCompiler()

Expand Down Expand Up @@ -51,4 +66,4 @@ func TestError(t *testing.T) {
c := NewCompiler()
err := c.AddSource("rule test { condition: foo }")
assert.Error(t, err)
}
}
30 changes: 30 additions & 0 deletions go/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ package yara_x
// #import <yara-x.h>
import "C"
import (
"errors"
"runtime"
"unsafe"
)
Expand All @@ -25,9 +26,38 @@ func Compile(source string) (*Rules, error) {
return c.Build(), nil
}

func Deserialize(data []byte) (*Rules, error) {
var ptr *C.uint8_t
if len(data) > 0 {
ptr = (*C.uint8_t)(unsafe.Pointer(&(data[0])))
}

r := &Rules{cRules: nil}

runtime.LockOSThread()
defer runtime.UnlockOSThread()

if C.yrx_rules_deserialize(ptr, C.size_t(len(data)), &r.cRules) != C.SUCCESS {
return nil, errors.New(C.GoString(C.yrx_last_error()))
}

return r, nil
}

// Rules represents a set of compiled YARA rules.
type Rules struct{ cRules *C.YRX_RULES }

func (r *Rules) Serialize() ([]byte, error) {
var buf *C.YRX_BUFFER
runtime.LockOSThread()
defer runtime.UnlockOSThread()
if C.yrx_rules_serialize(r.cRules, &buf) != C.SUCCESS {
return nil, errors.New(C.GoString(C.yrx_last_error()))
}
runtime.KeepAlive(r)
return C.GoBytes(unsafe.Pointer(buf.data), C.int(buf.length)), nil
}

// Destroy destroys the compiled YARA rules represented by Rules.
//
// Calling this method directly is not necessary, it will be invoked by the
Expand Down

0 comments on commit 543a2a6

Please sign in to comment.