From d2f662685e678a07c242bba2aaa9736fd7a652c5 Mon Sep 17 00:00:00 2001 From: "Victor M. Alvarez" Date: Wed, 28 Feb 2024 09:27:32 +0100 Subject: [PATCH] feat(capi): improve error handling when strings are not valid UTF-8. --- capi/include/yara-x.h | 1 + capi/src/lib.rs | 1 + capi/src/scanner.rs | 24 +++++++++++++++--------- 3 files changed, 17 insertions(+), 9 deletions(-) diff --git a/capi/include/yara-x.h b/capi/include/yara-x.h index a4b07befb..09dd4fa03 100644 --- a/capi/include/yara-x.h +++ b/capi/include/yara-x.h @@ -23,6 +23,7 @@ typedef enum YRX_RESULT { SCAN_TIMEOUT, INVALID_IDENTIFIER, INVALID_ARGUMENT, + INVALID_UTF8, SERIALIZATION_ERROR, } YRX_RESULT; diff --git a/capi/src/lib.rs b/capi/src/lib.rs index ade9e2ada..80c4b5380 100644 --- a/capi/src/lib.rs +++ b/capi/src/lib.rs @@ -43,6 +43,7 @@ pub enum YRX_RESULT { SCAN_TIMEOUT, INVALID_IDENTIFIER, INVALID_ARGUMENT, + INVALID_UTF8, SERIALIZATION_ERROR, } diff --git a/capi/src/scanner.rs b/capi/src/scanner.rs index e1d3edc89..32a319fb5 100644 --- a/capi/src/scanner.rs +++ b/capi/src/scanner.rs @@ -193,7 +193,10 @@ pub unsafe extern "C" fn yrx_scanner_set_module_output( let module_name = match CStr::from_ptr(name).to_str() { Ok(name) => name, - Err(_) => return YRX_RESULT::INVALID_ARGUMENT, + Err(err) => { + LAST_ERROR.set(Some(CString::new(err.to_string()).unwrap())); + return YRX_RESULT::INVALID_UTF8; + } }; let data = match slice_from_ptr_and_len(data, len) { @@ -228,7 +231,10 @@ unsafe extern "C" fn yrx_scanner_set_global< let ident = match CStr::from_ptr(ident).to_str() { Ok(ident) => ident, - Err(_) => return YRX_RESULT::INVALID_ARGUMENT, + Err(err) => { + LAST_ERROR.set(Some(CString::new(err.to_string()).unwrap())); + return YRX_RESULT::INVALID_UTF8; + } }; let scanner = scanner.as_mut().unwrap(); @@ -252,13 +258,13 @@ pub unsafe extern "C" fn yrx_scanner_set_global_str( ident: *const c_char, value: *const c_char, ) -> YRX_RESULT { - let value = if let Ok(value) = CStr::from_ptr(value).to_str() { - value - } else { - return YRX_RESULT::INVALID_ARGUMENT; - }; - - yrx_scanner_set_global(scanner, ident, value) + match CStr::from_ptr(value).to_str() { + Ok(value) => yrx_scanner_set_global(scanner, ident, value), + Err(err) => { + LAST_ERROR.set(Some(CString::new(err.to_string()).unwrap())); + YRX_RESULT::INVALID_UTF8 + } + } } /// Sets the value of a global variable of type bool.