Skip to content

Bug Report: Invalid Input Handling in Scanner::peek_newline Method #123

@lwz23

Description

@lwz23

Description

The peek_newline method in the Scanner struct fails to handle cases where the internal offset ofs exceeds the size of the buffer, leading to a panic. This behavior indicates a potential design flaw, as it does not properly handle invalid input, impacting the stability of the application.

Reproduce

consider the following code:

extern crate n2;

use n2::scanner::Scanner;

fn main() {
    // Prepare a valid UTF-8 byte array
    let valid_utf8_bytes: &[u8] = b"Hello, world!\0";

    // Create Scanner instance
    let mut scanner = Scanner::new(valid_utf8_bytes);

    // Manually set ofs to the last character index
    scanner.ofs = valid_utf8_bytes.len() - 1; // Move to the last character (the exclamation mark)

    // Now call peek_newline multiple times which will reach out of range
    for _ in 0..=1 { // Loop one additional time to induce potential out-of-bounds access
        let result = scanner.peek_newline();

        // Print the result (this can help in debugging)
        println!("peek_newline result: {}", result);
        
        // Increment the ofs to cause an out-of-bounds access in the next iteration
        scanner.ofs += 1; // This should lead to an out-of-bounds access on the next call
    }
}

In my platform, it shows the following result.

Compiling ne-test v0.1.0 (/home/lwz/github/ne-test)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.28s
     Running `target/debug/ne-test`
peek_newline result: false
thread 'main' panicked at core/src/panicking.rs:221:5:
unsafe precondition(s) violated: slice::get_unchecked requires that the index is within the slice
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
thread caused non-unwinding panic. aborting.
已中止 (核心已转储)

Expected Outcome
It is expected that the method handles input errors gracefully instead of panicking. For instance, the function could return a Result type or some other form of error handling.

I notice this PoC causes program aborting without 'unsafe' block, so I think maybe it is a Bug. This panic behavior could lead to program crashes in real applications, Sorry for if I am wrong.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions