Skip to content

Commit

Permalink
fix: read error while invoking formatter API from Python
Browse files Browse the repository at this point in the history
The `pyo3-file` crate doesn't accept buffers that are shorter than 4 bytes (https://github.com/omerbenamram/pyo3-file/blob/415def8ebdc93899aa130cc23d75afa8baf0349b/src/lib.rs#L102-L106), this causes an issue when an empty vector is passed to the `read` function implemented by `pyo3-file`. This happens at https://github.com/VirusTotal/yara-x/blob/18e2707e2824440ba7878ee6e80308daf75c631c/fmt/src/lib.rs#L344.

The issue is fixed by forcing the vector to have some initial capacity larger than 4 bytes.

Closes #299
  • Loading branch information
plusvic committed Feb 3, 2025
1 parent 18e2707 commit d1ccbf8
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 11 deletions.
6 changes: 3 additions & 3 deletions fmt/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,11 @@ mod tests;
#[allow(clippy::large_enum_variant)]
pub enum Error {
/// Error while reading from input.
#[error("read error")]
#[error("read error: {0}")]
ReadError(io::Error),

/// Error while writing to output.
#[error("write error")]
#[error("write error: {0}")]
WriteError(io::Error),

/// The input file contained invalid UTF-8.
Expand Down Expand Up @@ -339,7 +339,7 @@ impl Formatter {
W: io::Write,
{
let mut invalid_utf8 = Option::None;
let mut in_buf = Vec::new();
let mut in_buf = Vec::with_capacity(256);

input.read_to_end(&mut in_buf).map_err(Error::ReadError)?;

Expand Down
26 changes: 18 additions & 8 deletions py/tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -275,12 +275,22 @@ def callback(msg):
scanner.scan(b'')
assert ok


def test_format():
import io
expected_output = "rule test {\n condition:\n true\n}\n"
inp = io.StringIO("rule test {condition: true}")
output = io.StringIO()
fmt = yara_x.Formatter()
fmt.format(inp, output)
result = output.getvalue()
assert result == expected_output
import io
expected_output = (
'''rule test {
strings:
$a = "foo"
condition:
$a at 0
}
''')
inp = io.StringIO(
'rule test { strings: $a = "foo" condition: $a at 0 }')
output = io.StringIO()
fmt = yara_x.Formatter()
fmt.format(inp, output)
result = output.getvalue()
assert result == expected_output

0 comments on commit d1ccbf8

Please sign in to comment.