util: Avoid localised underflow
authorMartin Schwenke <martin@meltin.net>
Mon, 1 Jul 2019 11:28:43 +0000 (21:28 +1000)
committerAndrew Bartlett <abartlet@samba.org>
Fri, 5 Jul 2019 01:05:21 +0000 (01:05 +0000)
Avoid parenthesising an unsigned subtraction that can be negative and,
therefore, underflow.  There is no need for the parentheses and
removing them results in an expression that is evaluated left-to-right
and can not underflow.

It isn't clear that the underflow matters.  lp <= ls, so if (li - lp)
underflows then ls + (li - lp) will always overflow.  This should
produce the correct answer.  However, depending on this seems wrong.

Signed-off-by: Martin Schwenke <martin@meltin.net>
Reviewed-by: Andrew Bartlett <abartlet@samba.org>
lib/util/substitute.c

index 2249035f7047ee8ff71f2bb3a0f15e42c2c9f295..0ddab17958847143d630939dc1921b151aa48982 100644 (file)
@@ -65,10 +65,10 @@ static void string_sub2(char *s,const char *pattern, const char *insert, size_t
                len = ls + 1; /* len is number of *bytes* */
 
        while (lp <= ls && (p = strstr_m(s,pattern))) {
-               if (ls + (li-lp) >= len) {
+               if (ls + li - lp >= len) {
                        DEBUG(0,("ERROR: string overflow by "
                                "%d in string_sub(%.50s, %d)\n",
-                                (int)(ls + (li-lp) - len),
+                                (int)(ls + li - lp - len),
                                 pattern, (int)len));
                        break;
                }
@@ -105,7 +105,7 @@ static void string_sub2(char *s,const char *pattern, const char *insert, size_t
                        }
                }
                s = p + li;
-               ls += (li-lp);
+               ls = ls + li - lp;
 
                if (replace_once)
                        break;
@@ -192,10 +192,10 @@ _PUBLIC_ void all_string_sub(char *s,const char *pattern,const char *insert, siz
                len = ls + 1; /* len is number of *bytes* */
 
        while (lp <= ls && (p = strstr_m(s,pattern))) {
-               if (ls + (li-lp) >= len) {
+               if (ls + li - lp >= len) {
                        DEBUG(0,("ERROR: string overflow by "
                                "%d in all_string_sub(%.50s, %d)\n",
-                                (int)(ls + (li-lp) - len),
+                                (int)(ls + li - lp - len),
                                 pattern, (int)len));
                        break;
                }
@@ -204,6 +204,6 @@ _PUBLIC_ void all_string_sub(char *s,const char *pattern,const char *insert, siz
                }
                memcpy(p, insert, li);
                s = p + li;
-               ls += (li-lp);
+               ls = ls + li - lp;
        }
 }