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

Handle "stack overflow" panic on huge input with regex functions #525

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
19 changes: 13 additions & 6 deletions pm/pm.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@ import (
"fmt"
)

const EOS = -1
const _UNKNOWN = -2
const (
EOS = -1
_UNKNOWN = -2
maxRecursionLevel = 100000
)

/* Error {{{ */

Expand Down Expand Up @@ -524,7 +527,11 @@ func compilePattern(p pattern, ps ...*iptr) []inst {

// Simple recursive virtual machine based on the
// "Regular Expression Matching: the Virtual Machine Approach" (https://swtch.com/~rsc/regexp/regexp2.html)
func recursiveVM(src []byte, insts []inst, pc, sp int, ms ...*MatchData) (bool, int, *MatchData) {
func recursiveVM(src []byte, insts []inst, pc, sp, recLevel int, ms ...*MatchData) (bool, int, *MatchData) {
recLevel++
if recLevel > maxRecursionLevel {
panic(newError(_UNKNOWN, "pattern/input too complex"))
}
var m *MatchData
if len(ms) == 0 {
m = newMatchState()
Expand All @@ -549,14 +556,14 @@ redo:
pc = inst.Operand1
goto redo
case opSplit:
if ok, nsp, _ := recursiveVM(src, insts, inst.Operand1, sp, m); ok {
if ok, nsp, _ := recursiveVM(src, insts, inst.Operand1, sp, recLevel, m); ok {
return true, nsp, m
}
pc = inst.Operand2
goto redo
case opSave:
s := m.setCapture(inst.Operand1, sp)
if ok, nsp, _ := recursiveVM(src, insts, pc+1, sp, m); ok {
if ok, nsp, _ := recursiveVM(src, insts, pc+1, sp, recLevel, m); ok {
return true, nsp, m
}
m.restoreCapture(inst.Operand1, s)
Expand Down Expand Up @@ -620,7 +627,7 @@ func Find(p string, src []byte, offset, limit int) (matches []*MatchData, err er
insts := compilePattern(pat)
matches = []*MatchData{}
for sp := offset; sp <= len(src); {
ok, nsp, ms := recursiveVM(src, insts, 0, sp)
ok, nsp, ms := recursiveVM(src, insts, 0, sp, 0)
sp++
if ok {
if sp < nsp {
Expand Down