[Libguestfs] [PATCH v3 01/22] common/mlpcre: Raise Invalid_argument if PCRE.sub n parameter is negative.

Richard W.M. Jones rjones at redhat.com
Fri Sep 22 07:36:02 UTC 2017


---
 common/mlpcre/pcre-c.c      | 7 +++++--
 common/mlpcre/pcre_tests.ml | 7 +++++++
 2 files changed, 12 insertions(+), 2 deletions(-)

diff --git a/common/mlpcre/pcre-c.c b/common/mlpcre/pcre-c.c
index 6fae0e6f4..da9b50d34 100644
--- a/common/mlpcre/pcre-c.c
+++ b/common/mlpcre/pcre-c.c
@@ -201,6 +201,7 @@ value
 guestfs_int_pcre_sub (value nv)
 {
   CAMLparam1 (nv);
+  int n = Int_val (nv);
   CAMLlocal1 (strv);
   int len;
   CLEANUP_FREE char *str = NULL;
@@ -209,8 +210,10 @@ guestfs_int_pcre_sub (value nv)
   if (m == NULL)
     raise_pcre_error ("PCRE.sub called without calling PCRE.matches", 0);
 
-  len = pcre_get_substring (m->subject, m->vec, m->r, Int_val (nv),
-                            (const char **) &str);
+  if (n < 0)
+    caml_invalid_argument ("PCRE.sub: n must be >= 0");
+
+  len = pcre_get_substring (m->subject, m->vec, m->r, n, (const char **) &str);
 
   if (len == PCRE_ERROR_NOSUBSTRING)
     caml_raise_not_found ();
diff --git a/common/mlpcre/pcre_tests.ml b/common/mlpcre/pcre_tests.ml
index e5214eab8..2b18f462f 100644
--- a/common/mlpcre/pcre_tests.ml
+++ b/common/mlpcre/pcre_tests.ml
@@ -69,6 +69,13 @@ let () =
   | PCRE.Error (msg, code) ->
      failwith (sprintf "PCRE error: %s (PCRE error code %d)" msg code)
 
+(* Run some out of range [sub] calls to ensure an exception is thrown. *)
+let () =
+  let re2 = compile "(a+)(b*)" in
+  ignore (matches re2 "ccac");
+  (try ignore (sub 3) with Not_found -> ());
+  (try ignore (sub (-1)) with Invalid_argument _ -> ())
+
 (* Compile some bad regexps and check that an exception is thrown.
  * It would be nice to check the error message is right but
  * that involves dealing with language and future changes of
-- 
2.13.2




More information about the Libguestfs mailing list