Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
lwz23 opened this issue Nov 11, 2024 · 0 comments
Open

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

lwz23 opened this issue Nov 11, 2024 · 0 comments

Comments

@lwz23
Copy link

lwz23 commented Nov 11, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant