Skip to content

Commit

Permalink
refactor(capi): yrx_rule_patterns returns null when the rule doesn'…
Browse files Browse the repository at this point in the history
…t have any patterns.
  • Loading branch information
plusvic committed Sep 14, 2024
1 parent 67aa2e6 commit c827c6d
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 3 deletions.
3 changes: 2 additions & 1 deletion capi/include/yara_x.h
Original file line number Diff line number Diff line change
Expand Up @@ -283,7 +283,8 @@ void yrx_metadata_destroy(struct YRX_METADATA *metadata);
// object that must be destroyed with [`yrx_patterns_destroy`] when not needed
// anymore.
//
// This function returns a null pointer when `rule` is null.
// This function returns a null pointer when `rule` is null or when the rule
// doesn't have any patterns.
struct YRX_PATTERNS *yrx_rule_patterns(const struct YRX_RULE *rule);

// Destroys a [`YRX_PATTERNS`] object.
Expand Down
7 changes: 6 additions & 1 deletion capi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -629,7 +629,8 @@ pub unsafe extern "C" fn yrx_metadata_destroy(metadata: *mut YRX_METADATA) {
/// object that must be destroyed with [`yrx_patterns_destroy`] when not needed
/// anymore.
///
/// This function returns a null pointer when `rule` is null.
/// This function returns a null pointer when `rule` is null or the rule doesn't
/// have any patterns.
#[no_mangle]
pub unsafe extern "C" fn yrx_rule_patterns(
rule: *const YRX_RULE,
Expand All @@ -640,6 +641,10 @@ pub unsafe extern "C" fn yrx_rule_patterns(
return std::ptr::null_mut();
};

if patterns_iter.len() == 0 {
return std::ptr::null_mut();
}

let mut patterns = Vec::with_capacity(patterns_iter.len());

for pattern in patterns_iter {
Expand Down
11 changes: 10 additions & 1 deletion go/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,9 @@ func newRule(cRule *C.YRX_RULE) *Rule {
}

func (r *Rule) destroy() {
C.yrx_patterns_destroy(r.cPatterns)
if r.cPatterns != nil {
C.yrx_patterns_destroy(r.cPatterns)
}
if r.cMetadata != nil {
C.yrx_metadata_destroy(r.cMetadata)
}
Expand Down Expand Up @@ -359,6 +361,13 @@ func (r *Rule) Patterns() []Pattern {
return r.patterns
}

// if cPatterns is nil the rule doesn't have any patterns, return an
// empty list.
if r.cPatterns == nil {
r.patterns = make([]Pattern, 0)
return r.patterns
}

numPatterns := int(r.cPatterns.num_patterns)
cPatterns := unsafe.Slice(r.cPatterns.patterns, numPatterns)
r.patterns = make([]Pattern, numPatterns)
Expand Down

0 comments on commit c827c6d

Please sign in to comment.