Skip to content

Commit

Permalink
Fix issue while serializing unary operators to protobuf.
Browse files Browse the repository at this point in the history
  • Loading branch information
plusvic committed Jan 11, 2022
1 parent 835d877 commit 8a06e34
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
20 changes: 20 additions & 0 deletions serialize.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,11 @@ var stringSetKeywords = map[pb.StringSetKeyword]string{
pb.StringSetKeyword_THEM: "them",
}

var unaryOperators = map[pb.UnaryExpression_Operator]string{
pb.UnaryExpression_BITWISE_NOT: "~",
pb.UnaryExpression_UNARY_MINUS: "-",
}

var operators = map[pb.BinaryExpression_Operator]string{
pb.BinaryExpression_MATCHES: "matches",
pb.BinaryExpression_CONTAINS: "contains",
Expand Down Expand Up @@ -566,6 +571,8 @@ func (ys *YaraSerializer) SerializeExpression(e *pb.Expression) error {
return ys.serializeForOfExpression(e.GetForOfExpression())
case *pb.Expression_BinaryExpression:
return ys.serializeBinaryExpression(e.GetBinaryExpression())
case *pb.Expression_UnaryExpression:
return ys.serializeUnaryExpression(e.GetUnaryExpression())
case *pb.Expression_Text:
if err := ys.writeString(`"`); err != nil {
return err
Expand Down Expand Up @@ -886,6 +893,19 @@ func (ys *YaraSerializer) serializeStringSetKeyword(e pb.StringSetKeyword) error
return ys.writeString(kw)
}

func (ys *YaraSerializer) serializeUnaryExpression(e *pb.UnaryExpression) error {
op, ok := unaryOperators[e.GetOperator()]
if !ok {
return fmt.Errorf(`Unknown unary operator "%v"`, e.GetOperator())
}

if err := ys.writeString(op); err != nil {
return err
}

return ys.SerializeExpression(e.GetExpression())
}

// Serializes a BinaryExpression.
func (ys *YaraSerializer) serializeBinaryExpression(e *pb.BinaryExpression) error {
if getExpressionPrecedence(e.Left) < getBinaryExpressionPrecedence(e) {
Expand Down
10 changes: 10 additions & 0 deletions tests/grammar_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,16 @@ rule BASIC_BOOL2 {
false
}
rule OPERATORS1 {
condition:
(1 + 1 - 1) * 2 == 4 % 2
}
rule OPERATORS2 {
condition:
-1 != 0
}
rule HEX_STRING1 {
strings:
$h1 = { 01 23 45 67 89 AB }
Expand Down

0 comments on commit 8a06e34

Please sign in to comment.