From b690371bbf97794b4a1d3f295d4fb9a8b05d402d Mon Sep 17 00:00:00 2001
From: "K.Kosako" <kosako@sofnec.co.jp>
Date: Wed, 24 May 2017 10:27:04 +0900
Subject: [PATCH] fix #59 : access to invalid address by reg->dmax value

---
 regexec.c |   27 +++++++++++++++++----------
 1 file changed, 17 insertions(+), 10 deletions(-)

--- end of original header

CVE: CVE-2017-9229

Upstream-Status: Inappropriate [not author]
Signed-off-by: Joe Slater <joe.slater@windriver.com>

diff --git a/regexec.c b/regexec.c
index 49bcc50..c0626ef 100644
--- a/regexec.c
+++ b/regexec.c
@@ -3756,18 +3756,25 @@ forward_search_range(regex_t* reg, const
     }
     else {
       if (reg->dmax != ONIG_INFINITE_DISTANCE) {
-	*low = p - reg->dmax;
-	if (*low > s) {
-	  *low = onigenc_get_right_adjust_char_head_with_prev(reg->enc, s,
-							      *low, end, (const UChar** )low_prev);
-	  if (low_prev && IS_NULL(*low_prev))
-	    *low_prev = onigenc_get_prev_char_head(reg->enc,
-						   (pprev ? pprev : s), *low, end);
+        if (p - str < reg->dmax) {
+          *low = (UChar* )str;
+          if (low_prev)
+            *low_prev = onigenc_get_prev_char_head(reg->enc, str, *low, end);
 	}
 	else {
-	  if (low_prev)
-	    *low_prev = onigenc_get_prev_char_head(reg->enc,
-					       (pprev ? pprev : str), *low, end);
+          *low = p - reg->dmax;
+          if (*low > s) {
+            *low = onigenc_get_right_adjust_char_head_with_prev(reg->enc, s,
+                                                 *low, end, (const UChar** )low_prev);
+            if (low_prev && IS_NULL(*low_prev))
+              *low_prev = onigenc_get_prev_char_head(reg->enc,
+                                                     (pprev ? pprev : s), *low, end);
+          }
+          else {
+            if (low_prev)
+              *low_prev = onigenc_get_prev_char_head(reg->enc,
+                                                     (pprev ? pprev : str), *low, end);
+          }
 	}
       }
     }
-- 
1.7.9.5

