From 4097828d7cc87589864fecf452f2cd46c5f37180 Mon Sep 17 00:00:00 2001
From: "K.Kosako" <kosako@sofnec.co.jp>
Date: Mon, 29 Jul 2019 12:52:56 +0900
Subject: [PATCH] fix #147: Stack Exhaustion Problem caused by some parsing
 functions in regcomp.c making recursive calls to themselves.

---
 regparse.c | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)
 
diff --git a/regparse.c b/regparse.c
index f7177db..c07fccd 100644
--- a/regparse.c
+++ b/regparse.c
@@ -4568,6 +4568,7 @@ parse_char_class(Node** np, Node** asc_np, OnigToken* tok, UChar** src, UChar* e
   env->parse_depth++;
   if (env->parse_depth > ParseDepthLimit)
     return ONIGERR_PARSE_DEPTH_LIMIT_OVER;
+
   prev_cc = asc_prev_cc = (CClassNode* )NULL;
   r = fetch_token_in_cc(tok, src, end, env);
   if (r == TK_CHAR && tok->u.c == '^' && tok->escaped == 0) {
@@ -6514,14 +6515,18 @@ static int
 parse_exp(Node** np, OnigToken* tok, int term,
 	  UChar** src, UChar* end, ScanEnv* env)
 {
-  int r, len, group = 0;
+  int r, len, group;
   Node* qn;
   Node** targetp;
+  unsigned int parse_depth;
 
+  group = 0;
   *np = NULL;
   if (tok->type == (enum TokenSyms )term)
     goto end_of_token;
 
+  parse_depth = env->parse_depth;
+
   switch (tok->type) {
   case TK_ALT:
   case TK_EOT:
@@ -6832,6 +6837,10 @@ parse_exp(Node** np, OnigToken* tok, int term,
       if (is_invalid_quantifier_target(*targetp))
 	return ONIGERR_TARGET_OF_REPEAT_OPERATOR_INVALID;
 
+      parse_depth++;
+      if (parse_depth > ParseDepthLimit)
+        return ONIGERR_PARSE_DEPTH_LIMIT_OVER;
+
       qn = node_new_quantifier(tok->u.repeat.lower, tok->u.repeat.upper,
 			       (r == TK_INTERVAL ? 1 : 0));
       CHECK_NULL_RETURN_MEMERR(qn);
-- 
1.8.3.1
 
