summaryrefslogtreecommitdiff
path: root/core/regexp.zig
diff options
context:
space:
mode:
Diffstat (limited to 'core/regexp.zig')
-rw-r--r--core/regexp.zig39
1 files changed, 39 insertions, 0 deletions
diff --git a/core/regexp.zig b/core/regexp.zig
index 3f4bb391..2936b491 100644
--- a/core/regexp.zig
+++ b/core/regexp.zig
@@ -219,6 +219,11 @@ pub const Regex = struct {
if (body[j] == '\\') {
const len: usize = if (j + 1 < body.len and body[j + 1] == 'x') 4 else 2;
if (j + len > body.len) return error.Bad;
+ // An escape holding a non-ASCII byte (`[\` then a lone 0xc3,
+ // `[\x` then one) would be written back as it came: a class
+ // that still holds one, which compile rewrites again, without
+ // end (the stack overflows).
+ for (body[j..][0..len]) |b| if (b >= 0x80) return error.Bad;
// An escape at one end of a range whose other end is a rune.
if (j + len + 1 < body.len and body[j + len] == '-' and body[j + len + 1] >= 0x80) return error.Bad;
if (n + len > ascii.len) return error.TooLong;
@@ -642,3 +647,37 @@ test "`$` may end any alternative, not only the last" {
var only = try Regex.compile("h$|zz");
try std.testing.expectEqual(null, try only.find("hx", 0, 2, 2));
}
+
+test "a pattern that stops inside a count or an escape is refused, not read past its end" {
+ // Each read mvzr 0.3.9 made past the end of what it is handed (patched
+ // as it is fetched: build/patches.zig), as a typed search reaches them:
+ // `a{` is the second key of a search for `a{2}`, `fn main() {` a line
+ // of code.
+ std.testing.log_level = .err; // mvzr warns of each bad string
+ for ([_][]const u8{ "a{", "fn main() {", "a{,1", "a{1", "a{1,", "a{1,2", "{\\\\x", "a{1\\\\x1", "[\\\\x]" }) |pat|
+ try std.testing.expectError(error.Bad, Regex.compile(pat));
+ // A class escape holding a byte no rune starts with was rewritten
+ // without end.
+ for ([_][]const u8{ "[\\\xc3]", "a[\\x\xa9c]" }) |pat|
+ try std.testing.expectError(error.Bad, Regex.compile(pat));
+ // What still compiles: the counts and escapes that end.
+ for ([_][]const u8{ "a{2}", "a{,1}", "a{1,}", "a{1,2}", "a\\{", "{a", "\\x7b" }) |pat|
+ _ = try Regex.compile(pat);
+ // Every pattern up to five characters over these, 66,429 of them,
+ // 4,516 of which read past their end at one of mvzr's six reads that
+ // a pattern reaches through here before the patch: none panics.
+ const alphabet = "{},1\\x[]a";
+ var pat: [5]u8 = undefined;
+ for (1..pat.len + 1) |len| {
+ var n: usize = 1;
+ for (0..len) |_| n *= alphabet.len;
+ for (0..n) |k| {
+ var rest = k;
+ for (pat[0..len]) |*c| {
+ c.* = alphabet[rest % alphabet.len];
+ rest /= alphabet.len;
+ }
+ _ = Regex.compile(pat[0..len]) catch {};
+ }
+ }
+}