From cdcf00f35c4b6367dc35ef6a31e9579de7479a05 Mon Sep 17 00:00:00 2001 From: Calvin Rose Date: Thu, 29 Oct 2026 18:18:39 -0500 Subject: [PATCH] make peg check more paranoid, check at runtime too --- src/core/peg.c | 5 +---- test/suite-peg.janet | 2 ++ 2 files changed, 3 insertions(+), 4 deletions(-) diff --git a/src/core/peg.c b/src/core/peg.c index 2d8a7e04..82ea208d 100644 --- a/src/core/peg.c +++ b/src/core/peg.c @@ -426,7 +426,7 @@ tail: case RULE_ARGUMENT: { int32_t index = ((int32_t *)rule)[1]; - Janet capture = (index >= s->extrac) ? janet_wrap_nil() : s->extrav[index]; + Janet capture = (index >= s->extrac || index < 0) ? janet_wrap_nil() : s->extrav[index]; pushcap(s, capture, rule[2]); return text; } @@ -1764,9 +1764,6 @@ static void *peg_unmarshal(JanetMarshalContext *ctx) { case RULE_ARGUMENT: /* [argument-index, tag] */ OVERFLOW_CHECK(3); - /* index is read as a signed int32 at match time and only - * bounds-checked against extrac on the high side, so a - * negative index would read before extrav */ if (((int32_t) rule[1]) < 0) goto bad; i += 3; break; diff --git a/test/suite-peg.janet b/test/suite-peg.janet index 9819bc38..e70798e0 100644 --- a/test/suite-peg.janet +++ b/test/suite-peg.janet @@ -963,6 +963,8 @@ ```)) +(assert-error "negative argument" (peg/compile ~(argument -1))) + # A matchtime or replacement callback that grows the buffer being matched # reallocates its storage. The matcher kept pointing at the old allocation, # so the rest of the match read freed memory.