File size: 2,428 Bytes
4eaabb5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 | diff --git a/regexp.c b/regexp.c
index 01c18a3..4a5948b 100644
--- a/regexp.c
+++ b/regexp.c
@@ -16,6 +16,7 @@
#define REPINF 255
#define MAXTHREAD 1000
#define MAXSUB REG_MAXSUB
+#define MAXPROG (32 << 10)
typedef struct Reclass Reclass;
typedef struct Renode Renode;
@@ -595,23 +596,25 @@ struct Reinst {
Reinst *y;
};
-static int count(Renode *node)
+static int count(struct cstate *g, Renode *node)
{
- int min, max;
+ int min, max, n;
if (!node) return 0;
switch (node->type) {
default: return 1;
- case P_CAT: return count(node->x) + count(node->y);
- case P_ALT: return count(node->x) + count(node->y) + 2;
+ case P_CAT: return count(g, node->x) + count(g, node->y);
+ case P_ALT: return count(g, node->x) + count(g, node->y) + 2;
case P_REP:
min = node->m;
max = node->n;
- if (min == max) return count(node->x) * min;
- if (max < REPINF) return count(node->x) * max + (max - min);
- return count(node->x) * (min + 1) + 2;
- case P_PAR: return count(node->x) + 2;
- case P_PLA: return count(node->x) + 2;
- case P_NLA: return count(node->x) + 2;
+ if (min == max) n = count(g, node->x) * min;
+ else if (max < REPINF) n = count(g, node->x) * max + (max - min);
+ else n = count(g, node->x) * (min + 1) + 2;
+ if (n < 0 || n > MAXPROG) die(g, "program too large");
+ return n;
+ case P_PAR: return count(g, node->x) + 2;
+ case P_PLA: return count(g, node->x) + 2;
+ case P_NLA: return count(g, node->x) + 2;
}
}
@@ -813,7 +816,7 @@ Reprog *regcompx(void *(*alloc)(void *ctx, void *p, int n), void *ctx,
struct cstate g;
Renode *node;
Reinst *split, *jump;
- int i;
+ int i, n;
g.pstart = NULL;
g.prog = NULL;
@@ -847,8 +850,17 @@ Reprog *regcompx(void *(*alloc)(void *ctx, void *p, int n), void *ctx,
if (g.lookahead != 0)
die(&g, "syntax error");
+#ifdef TEST
+ dumpnode(node);
+ putchar('\n');
+#endif
+
+ n = 6 + count(&g, node);
+ if (n < 0 || n > MAXPROG)
+ die(&g, "program too large");
+
g.prog->nsub = g.nsub;
- g.prog->start = g.prog->end = alloc(ctx, NULL, (count(node) + 6) * sizeof (Reinst));
+ g.prog->start = g.prog->end = alloc(ctx, NULL, n * sizeof (Reinst));
if (!g.prog->start)
die(&g, "cannot allocate regular expression instruction list");
@@ -864,8 +876,6 @@ Reprog *regcompx(void *(*alloc)(void *ctx, void *p, int n), void *ctx,
emit(g.prog, I_END);
#ifdef TEST
- dumpnode(node);
- putchar('\n');
dumpprog(g.prog);
#endif |