Skip to content
Merged
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
13 changes: 13 additions & 0 deletions crates/bashkit/src/interpreter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6900,18 +6900,27 @@ impl Interpreter {
}

/// Remove prefix/suffix using glob_match for patterns with brackets or extglob.
///
/// THREAT[TM-DOS]: Cap glob_match invocations to prevent O(n^2) CPU
/// exhaustion on long strings with bracket/extglob patterns.
fn remove_pattern_glob(
&self,
value: &str,
pattern: &str,
prefix: bool,
longest: bool,
) -> String {
const MAX_GLOB_MATCH_CALLS: usize = 10_000;
let chars: Vec<char> = value.chars().collect();
let mut calls = 0usize;
if prefix {
// Try each prefix length; shortest = first match, longest = last match
let mut last_match = None;
for i in 0..=chars.len() {
calls += 1;
if calls > MAX_GLOB_MATCH_CALLS {
break;
}
let candidate: String = chars[..i].iter().collect();
if self.glob_match(&candidate, pattern) {
if !longest {
Expand All @@ -6927,6 +6936,10 @@ impl Interpreter {
// Suffix removal: try each suffix length
let mut last_match = None;
for i in (0..=chars.len()).rev() {
calls += 1;
if calls > MAX_GLOB_MATCH_CALLS {
break;
}
let candidate: String = chars[i..].iter().collect();
if self.glob_match(&candidate, pattern) {
if !longest {
Expand Down
35 changes: 35 additions & 0 deletions crates/bashkit/tests/spec_cases/bash/glob_match_cap.test.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# Glob match cap in remove_pattern_glob
# Regression tests for issue #994

### bracket_prefix_removal_works
# Normal bracket pattern prefix removal still works
x="abcdef"
echo "${x#[a]*}"
### expect
bcdef
### end

### bracket_suffix_removal_works
# Normal bracket pattern suffix removal still works
x="abcdef"
echo "${x%[f]}"
### expect
abcde
### end

### bracket_longest_prefix_removal_works
# Longest bracket pattern prefix removal still works
x="aaabbb"
result="${x##[a]*}"
echo "result=${#result}"
### expect
result=0
### end

### normal_prefix_removal_unaffected
# Standard patterns still work correctly
x="hello_world"
echo "${x#hello_}"
### expect
world
### end
Loading