Skip to content

Commit

Permalink
Fix panic in Python 3.12 line number handling
Browse files Browse the repository at this point in the history
The read_varint function would panic when trying to read past the end of
the line table. This fix adds bounds checking and returns Option<usize>
to handle this case gracefully.

Fixes benfred#735
  • Loading branch information
openhands-agent committed Dec 11, 2024
1 parent 1fa3a6d commit e01bbfa
Showing 1 changed file with 14 additions and 8 deletions.
22 changes: 14 additions & 8 deletions src/python_interpreters.rs
Original file line number Diff line number Diff line change
Expand Up @@ -246,28 +246,34 @@ macro_rules! PythonCodeObjectImpl {
};
}

fn read_varint(index: &mut usize, table: &[u8]) -> usize {
fn read_varint(index: &mut usize, table: &[u8]) -> Option<usize> {
if *index >= table.len() {
return None;
}
let mut ret: usize;
let mut byte = table[*index];
let mut shift = 0;
*index += 1;
ret = (byte & 63) as usize;

while byte & 64 != 0 {
if *index >= table.len() {
return None;
}
byte = table[*index];
*index += 1;
shift += 6;
ret += ((byte & 63) as usize) << shift;
}
ret
Some(ret)
}

fn read_signed_varint(index: &mut usize, table: &[u8]) -> isize {
let unsigned_val = read_varint(index, table);
fn read_signed_varint(index: &mut usize, table: &[u8]) -> Option<isize> {
let unsigned_val = read_varint(index, table)?;
if unsigned_val & 1 != 0 {
-((unsigned_val >> 1) as isize)
Some(-((unsigned_val >> 1) as isize))
} else {
(unsigned_val >> 1) as isize
Some((unsigned_val >> 1) as isize)
}
}

Expand Down Expand Up @@ -322,13 +328,13 @@ macro_rules! CompactCodeObjectImpl {
let line_delta = match code {
15 => 0,
14 => {
let delta = read_signed_varint(&mut index, table);
let delta = read_signed_varint(&mut index, table).unwrap_or(0);
read_varint(&mut index, table); // end line
read_varint(&mut index, table); // start column
read_varint(&mut index, table); // end column
delta
}
13 => read_signed_varint(&mut index, table),
13 => read_signed_varint(&mut index, table).unwrap_or(0),
10..=12 => {
index += 2; // start column / end column
(code - 10).into()
Expand Down

0 comments on commit e01bbfa

Please sign in to comment.