Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ debugid = {version = "0.8.0", features = ["serde"] }
base64-simd = { version = "0.8" }
bitvec = "1.0.1"
rustc-hash = "2.1.1"
fallible-iterator = "0.3.0"

[features]
ram_bundle = ["scroll"]
Expand Down
53 changes: 28 additions & 25 deletions src/decoder/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@ use std::io::{BufReader, Read};
use bitvec::field::BitField;
use bitvec::order::Lsb0;
use bitvec::vec::BitVec;
use fallible_iterator::FallibleIterator;
use serde_json::Value;

use crate::errors::{Error, Result};
use crate::hermes::decode_hermes;
use crate::jsontypes::RawSourceMap;
use crate::types::{DecodedMap, RawToken, SourceMap, SourceMapIndex, SourceMapSection};
use crate::vlq::parse_vlq_segment_into;
use crate::vlq;

mod scope;

Expand Down Expand Up @@ -148,14 +149,14 @@ fn decode_rmi(rmi_str: &str, val: &mut BitVec<u8, Lsb0>) -> Result<()> {
}

pub fn decode_regular(rsm: RawSourceMap) -> Result<SourceMap> {
let mut dst_col;
let mut dst_col: u32;

// Source IDs, lines, columns, and names are "running" values.
// Each token (except the first) contains the delta from the previous value.
let mut running_src_id = 0;
let mut running_src_line = 0;
let mut running_src_col = 0;
let mut running_name_id = 0;
let mut running_src_id: u32 = 0;
let mut running_src_line: u32 = 0;
let mut running_src_col: u32 = 0;
let mut running_name_id: u32 = 0;

let names = rsm.names.unwrap_or_default();
let sources = rsm.sources.unwrap_or_default();
Expand All @@ -164,7 +165,6 @@ pub fn decode_regular(rsm: RawSourceMap) -> Result<SourceMap> {
let allocation_size = mappings.matches(&[',', ';'][..]).count() + 10;
let mut tokens = Vec::with_capacity(allocation_size);

let mut nums = Vec::with_capacity(6);
let mut rmi = BitVec::new();

for (dst_line, (line, rmi_str)) in mappings
Expand All @@ -185,14 +185,10 @@ pub fn decode_regular(rsm: RawSourceMap) -> Result<SourceMap> {
continue;
}

nums.clear();
parse_vlq_segment_into(segment, &mut nums)?;
match nums.len() {
1 | 4 | 5 => {}
_ => return Err(Error::BadSegmentSize(nums.len() as u32)),
}
let mut vlqs = vlq::decode_vlqs(segment);

dst_col = (i64::from(dst_col) + nums[0]) as u32;
// The `dst_col` must always exist.
dst_col = dst_col.saturating_add_signed(vlqs.next_required()?.signed());

// The source file , source line, source column, and name
// may not be present in the current token. We use `u32::MAX`
Expand All @@ -202,29 +198,36 @@ pub fn decode_regular(rsm: RawSourceMap) -> Result<SourceMap> {
let mut current_src_col = !0;
let mut current_name_id = !0;

if nums.len() > 1 {
running_src_id = (i64::from(running_src_id) + nums[1]) as u32;
if let Some(running_src_id_incr) = vlqs.next()? {
// If the `running_src_id` exists, so must the `running_src_line` and the `running_src_col`.
running_src_id = running_src_id.saturating_add_signed(running_src_id_incr.signed());
running_src_line =
running_src_line.saturating_add_signed(vlqs.next_required()?.signed());
running_src_col =
running_src_col.saturating_add_signed(vlqs.next_required()?.signed());

if running_src_id >= sources.len() as u32 {
return Err(Error::BadSourceReference(running_src_id));
}

running_src_line = (i64::from(running_src_line) + nums[2]) as u32;
running_src_col = (i64::from(running_src_col) + nums[3]) as u32;

current_src_id = running_src_id;
current_src_line = running_src_line;
current_src_col = running_src_col;
}

if nums.len() > 4 {
running_name_id = (i64::from(running_name_id) + nums[4]) as u32;
if running_name_id >= names.len() as u32 {
return Err(Error::BadNameReference(running_name_id));
}
current_name_id = running_name_id;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Negative source or name deltas clamp to zero

Low Severity

running_src_id and running_name_id now update via saturating_add_signed, so a negative delta that underflows below 0 silently clamps to index 0 instead of failing the bounds check with Error::BadSourceReference or Error::BadNameReference.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 7f90cc0. Configure here.

if let Some(running_name_id_incr) = vlqs.next()? {
running_name_id =
running_name_id.saturating_add_signed(running_name_id_incr.signed());

if running_name_id >= names.len() as u32 {
return Err(Error::BadNameReference(running_name_id));
}

current_name_id = running_name_id;
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved
}

vlqs.finished()?;

let is_range = rmi.get(line_index).map(|v| *v).unwrap_or_default();

tokens.push(RawToken {
Expand Down
78 changes: 14 additions & 64 deletions src/decoder/scope.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use crate::types::{OriginalScopes, RawOriginalScope};
use crate::{vlq, Error, Result};
use crate::vlq;
use crate::{Error, Result};

#[derive(Debug, Clone, Default)]
struct PositionAccumulator {
Expand Down Expand Up @@ -30,24 +31,6 @@ impl IndexAccumulator {
}
}

#[derive(Debug, Clone, Default)]
struct VlqBuffer(Vec<i64>);

impl VlqBuffer {
fn inner_mut(&mut self) -> &mut Vec<i64> {
self.0.clear();
&mut self.0
}

fn get(&self, index: usize) -> Result<i32> {
let n = self
.0
.get(index)
.ok_or(Error::BadSegmentSize(self.0.len() as u32))?;
Ok(*n as i32)
}
}

/// Running state for decoding the scopes for a source.
#[derive(Debug, Clone, Default)]
struct DecodeScopeState {
Expand All @@ -57,15 +40,6 @@ struct DecodeScopeState {
name_idx: IndexAccumulator,
/// The running kind index.
kind_idx: IndexAccumulator,
/// Buffer for decoding VLQs.
vlq_buffer: VlqBuffer,
}

impl DecodeScopeState {
fn decode_vlq(&mut self, segment: &str) -> Result<&VlqBuffer> {
vlq::parse_vlq_segment_into(segment, self.vlq_buffer.inner_mut())?;
Ok(&self.vlq_buffer)
}
}

/// Scope start entries are of the form
Expand All @@ -87,26 +61,26 @@ fn decode_scope_start(item: &str, state: &mut DecodeScopeState) -> Result<RawOri
// Indicates that this scope creates a stack frame.
const STACKFRAME_FLAG: u32 = 0x4;

let nums = state.decode_vlq(item)?;
let mut vlqs = vlq::decode_vlqs(item);

let flags = unsigned(nums.get(0)?);
let line = unsigned(nums.get(1)?);
let column = unsigned(nums.get(2)?);
let flags = vlqs.next_required()?.unsigned();
let line = vlqs.next_required()?.unsigned();
let column = vlqs.next_required()?.unsigned();

let has_name = (flags & NAME_FLAG) > 0;
let has_kind = (flags & KIND_FLAG) > 0;
let is_stack_frame = (flags & STACKFRAME_FLAG) > 0;

let (name_id, kind_id) = match (has_name, has_kind) {
(false, false) => (None, None),
(true, false) => (Some(nums.get(3)?), None),
(false, true) => (None, Some(nums.get(3)?)),
(true, true) => (Some(nums.get(3)?), Some(nums.get(4)?)),
(true, false) => (Some(vlqs.next_required()?), None),
(false, true) => (None, Some(vlqs.next_required()?)),
(true, true) => (Some(vlqs.next_required()?), Some(vlqs.next_required()?)),
};

let (start_line, start_col) = state.position.advance(line, column);
let name_id = name_id.map_or(u32::MAX, |name_incr| state.name_idx.add(name_incr));
let kind_id = kind_id.map_or(u32::MAX, |kind_incr| state.kind_idx.add(kind_incr));
let name_id = name_id.map_or(u32::MAX, |name_incr| state.name_idx.add(name_incr.signed()));
let kind_id = kind_id.map_or(u32::MAX, |kind_incr| state.kind_idx.add(kind_incr.signed()));

Ok(RawOriginalScope {
start_line,
Expand All @@ -130,9 +104,9 @@ fn decode_scope_start(item: &str, state: &mut DecodeScopeState) -> Result<RawOri
/// This returns a `line` and `column` that are used to fill in the end position
/// of the scope closed by this record.
fn decode_scope_end(item: &str, state: &mut DecodeScopeState) -> Result<(u32, u32)> {
let nums = state.decode_vlq(item)?;
let line = unsigned(nums.get(0)?);
let column = unsigned(nums.get(1)?);
let mut vlqs = vlq::decode_vlqs(item);
let line = vlqs.next_required()?.unsigned();
let column = vlqs.next_required()?.unsigned();

Ok(state.position.advance(line, column))
}
Expand Down Expand Up @@ -217,27 +191,3 @@ pub fn decode_scopes(items: &str) -> Result<OriginalScopes> {

Ok(out)
}

/// Reinterprets a signed VLQ as an unsigned number.
///
/// This reverts the operation described in
/// <https://tc39.es/ecma426/branch/proposal-scopes/#sec-VLQSignedValue>.
fn unsigned(mut vlq: i32) -> u32 {
if vlq == i32::MIN {
return 1;
}

let neg = vlq < 0;

if neg {
vlq = -vlq;
}

vlq <<= 1;

if neg {
vlq |= 1;
}

vlq as u32
}
12 changes: 7 additions & 5 deletions src/encoder.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::fmt::Write as _;
use std::io::Write;

use bitvec::field::BitField;
Expand All @@ -8,7 +9,7 @@ use serde_json::Value;
use crate::errors::Result;
use crate::jsontypes::{RawSection, RawSectionOffset, RawSourceMap};
use crate::types::{DecodedMap, SourceMap, SourceMapIndex};
use crate::vlq::encode_vlq;
use crate::vlq::Vlq;

pub trait Encodable {
fn as_raw_sourcemap(&self) -> RawSourceMap;
Expand All @@ -20,10 +21,6 @@ pub fn encode<M: Encodable, W: Write>(sm: &M, mut w: W) -> Result<()> {
Ok(())
}

fn encode_vlq_diff(out: &mut String, a: u32, b: u32) {
encode_vlq(out, i64::from(a) - i64::from(b))
}

fn encode_rmi(out: &mut Vec<u8>, data: &[u8]) {
fn encode_byte(b: u8) -> u8 {
match b {
Expand Down Expand Up @@ -102,6 +99,11 @@ fn serialize_range_mappings(sm: &SourceMap) -> Option<String> {
Some(String::from_utf8(buf).expect("invalid utf8"))
}

fn encode_vlq_diff(out: &mut String, x: u32, y: u32) {
let vlq = Vlq::from_signed((i64::from(x) - i64::from(y)) as i32);
let _ = write!(out, "{vlq}");
}

fn serialize_mappings(sm: &SourceMap) -> String {
let mut rv = String::new();
// dst == minified == generated
Expand Down
3 changes: 3 additions & 0 deletions src/errors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ pub enum Error {
VlqNoValues,
/// Overflow in Vlq handling
VlqOverflow,
/// Encoded VLQ data ended in a number that should have continued.
VlqTruncated,
/// a mapping segment had an unsupported size
BadSegmentSize(u32),
/// a reference to a non existing source was encountered
Expand Down Expand Up @@ -114,6 +116,7 @@ impl fmt::Display for Error {
Error::VlqLeftover => write!(f, "leftover cur/shift in vlq decode"),
Error::VlqNoValues => write!(f, "vlq decode did not produce any values"),
Error::VlqOverflow => write!(f, "vlq decode caused an overflow"),
Error::VlqTruncated => write!(f, "vlq decode encountered a truncated number"),
Error::BadSegmentSize(size) => write!(f, "got {size} segments, expected 4 or 5"),
Error::BadSourceReference(id) => write!(f, "bad reference to source #{id}"),
Error::BadNameReference(id) => write!(f, "bad reference to name #{id}"),
Expand Down
31 changes: 18 additions & 13 deletions src/hermes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@ use crate::errors::{Error, Result};
use crate::jsontypes::{FacebookScopeMapping, FacebookSources, RawSourceMap};
use crate::types::{DecodedMap, RewriteOptions, SourceMap};
use crate::utils::greatest_lower_bound;
use crate::vlq::parse_vlq_segment_into;
use crate::Token;
use crate::{vlq, Token};

use std::io::{Read, Write};
use std::ops::{Deref, DerefMut};

use fallible_iterator::FallibleIterator;

/// These are starting locations of scopes.
/// The `name_index` represents the index into the `HermesFunctionMap.names` vec,
/// which represents the function names/scopes.
Expand Down Expand Up @@ -164,8 +166,6 @@ pub fn decode_hermes(mut rsm: RawSourceMap) -> Result<SourceMapHermes> {
// This is basically the logic from here:
// https://github.com/facebook/metro/blob/63b523eb20e7bdf62018aeaf195bb5a3a1a67f36/packages/metro-symbolicate/src/SourceMetadataMapConsumer.js#L182-L202

let mut nums = Vec::with_capacity(4);

let function_maps = x_facebook_sources
.iter()
.map(|v| {
Expand All @@ -175,28 +175,33 @@ pub fn decode_hermes(mut rsm: RawSourceMap) -> Result<SourceMapHermes> {
} = v.as_ref()?.iter().next()?;

let mut mappings = vec![];
let mut line = 1;
let mut name_index = 0;
let mut line: u32 = 1;
let mut name_index: u32 = 0;

for line_mapping in raw_mappings.split(';') {
if line_mapping.is_empty() {
continue;
}

let mut column = 0;
let mut column: u32 = 0;

for mapping in line_mapping.split(',') {
if mapping.is_empty() {
continue;
}

nums.clear();
parse_vlq_segment_into(mapping, &mut nums).ok()?;
let mut nums = nums.iter().copied();
let mut vlqs = vlq::decode_vlqs(mapping);

// `column_incr` must exist, `name_index_incr` and `line_incr`
// are assumed zero if they're missing.
let column_incr = vlqs.next_required().ok()?.signed();
let name_index_incr = vlqs.next().ok()?.map(|n| n.signed()).unwrap_or(0);
let line_incr = vlqs.next().ok()?.map(|n| n.signed()).unwrap_or(0);

column = column.saturating_add_signed(column_incr);
name_index = name_index.saturating_add_signed(name_index_incr);
line = line.saturating_add_signed(line_incr);

column = (i64::from(column) + nums.next()?) as u32;
name_index = (i64::from(name_index) + nums.next().unwrap_or(0)) as u32;
line = (i64::from(line) + nums.next().unwrap_or(0)) as u32;
mappings.push(HermesScopeOffset {
column,
line,
Expand Down
2 changes: 1 addition & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,4 +75,4 @@ mod utils;

#[cfg(feature = "ram_bundle")]
pub mod ram_bundle;
pub mod vlq;
mod vlq;
Loading
Loading