From c827c6dcb58cbaa489424c0cfb9a2dfe438c941e Mon Sep 17 00:00:00 2001 From: "Victor M. Alvarez" Date: Sat, 14 Sep 2024 20:41:47 +0200 Subject: [PATCH] refactor(capi): `yrx_rule_patterns` returns null when the rule doesn't have any patterns. --- capi/include/yara_x.h | 3 ++- capi/src/lib.rs | 7 ++++++- go/main.go | 11 ++++++++++- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/capi/include/yara_x.h b/capi/include/yara_x.h index 8e73e975..30cdb652 100644 --- a/capi/include/yara_x.h +++ b/capi/include/yara_x.h @@ -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. diff --git a/capi/src/lib.rs b/capi/src/lib.rs index da495597..d83b50d8 100644 --- a/capi/src/lib.rs +++ b/capi/src/lib.rs @@ -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, @@ -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 { diff --git a/go/main.go b/go/main.go index bdfdebd3..4741fa7d 100644 --- a/go/main.go +++ b/go/main.go @@ -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) } @@ -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)