Skip to content

Bug Report: Out of Bounds Access in Scanner::peek Method #122

Open
@lwz23

Description

@lwz23

Description

The peek method in the Scanner struct does not handle out-of-bounds accesses properly. When the internal offset (ofs) exceeds the length of the buffer, it causes a panic instead of handling the situation gracefully. This can lead to unexpected application crashes.

Reproduce

Use the following code to create a simple Rust project:

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);

    // Move the offset to an out-of-bounds index (without using unsafe)
    // Keep calling peek enough times to eventually exceed buffer range
    for _ in 0..=valid_utf8_bytes.len() { // Loop beyond the valid size
        let char_result = scanner.peek();

        // Print the character result (can be removed if not needed)
        println!("Peeked character: {}", char_result);
        
        // Increment the ofs manually to go out-of-bounds
        scanner.ofs += 1; // This will eventually create an out-of-bounds access
    }
}

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`
Peeked character: H
Peeked character: e
Peeked character: l
Peeked character: l
Peeked character: o
Peeked character: ,
Peeked character:  
Peeked character: w
Peeked character: o
Peeked character: r
Peeked character: l
Peeked character: d
Peeked character: !
Peeked character: 
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.
已中止 (核心已转储)

This panic behavior could lead to program crashes in real applications, affecting user experience and stability. It's encouraged to add input validation and error handling in the peek method to improve the resilience of the library.

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