Skip to content

Commit

Permalink
feat(capi): improve error handling when strings are not valid UTF-8.
Browse files Browse the repository at this point in the history
  • Loading branch information
plusvic committed Feb 28, 2024
1 parent caa1b46 commit d2f6626
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 9 deletions.
1 change: 1 addition & 0 deletions capi/include/yara-x.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ typedef enum YRX_RESULT {
SCAN_TIMEOUT,
INVALID_IDENTIFIER,
INVALID_ARGUMENT,
INVALID_UTF8,
SERIALIZATION_ERROR,
} YRX_RESULT;

Expand Down
1 change: 1 addition & 0 deletions capi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ pub enum YRX_RESULT {
SCAN_TIMEOUT,
INVALID_IDENTIFIER,
INVALID_ARGUMENT,
INVALID_UTF8,
SERIALIZATION_ERROR,
}

Expand Down
24 changes: 15 additions & 9 deletions capi/src/scanner.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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();
Expand All @@ -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.
Expand Down

0 comments on commit d2f6626

Please sign in to comment.