[PATCH] expand: Do not use memcmp on strings

Herbert Xu <[email protected]> Sun, 14 Sep 2025 08:44:10 +0800
Newsgroups org.kernel.vger.dash
Message-ID <[email protected]>
On Sat, Sep 13, 2025 at 03:29:30PM +0100, Harald van Dijk wrote:
>
> Are you sure this is a false positive? memcmp isn't required to stop reading
> once it sees NUL and typical implementations read multiple bytes at a time.
> Reading past the NUL may crash.

You are right.  This patch should fix them up.

Thanks,

---8<---
Using memcmp past the end of a string may crash if it hits a page
boundary.  Fix this by calling strcmp/strncmp instead.

Reported-by: Nathan Mills <[email protected]>
Reported-by: Harald van Dijk <[email protected]>
Signed-off-by: Herbert Xu <[email protected]>

diff --git a/src/expand.c b/src/expand.c
index 35481d6..19edc9d 100644
--- a/src/expand.c
+++ b/src/expand.c
@@ -354,8 +354,7 @@ start:
 			continue;
 		case CTLQUOTEMARK:
 			/* "$@" syntax adherence hack */
-			if (!inquotes && !memcmp(p, dolatstr + 1,
-						 DOLATSTRLEN - 1)) {
+			if (!inquotes && !strcmp(p, dolatstr + 1)) {
 				p = evalvar(p + 1, flag | EXP_QUOTED) + 1;
 				goto start;
 			}
@@ -1552,7 +1551,7 @@ expandmeta(struct strlist *str)
 
 		if (fflag)
 			goto nometa;
-		if (!strpbrk(str->text, "*?]") || !memcmp(str->text, "]", 2))
+		if (!strpbrk(str->text, "*?]") || !strcmp(str->text, "]"))
 			goto nometa;
 		savelastp = exparg.lastp;
 
@@ -1996,7 +1995,7 @@ static int pmatch(char *pattern, const char *string)
 					    chr >= c && chr <= *p)
 						found = 1;
 					p++;
-				} else if (!memcmp(mbs, q, mb))
+				} else if (!strncmp(mbs, q, mb))
 					found = 1;
 			} while ((c = *p++) != ']');
 			if (found == invert)
@@ -2011,7 +2010,7 @@ static int pmatch(char *pattern, const char *string)
 			q += mb & 0xff;
 			mb >>= 8;
 
-			if (memcmp(p - 1, q - 1, mb + 1))
+			if (strncmp(p - 1, q - 1, mb + 1))
 				return 0;
 
 			p += mb;
-- 
Email: Herbert Xu <[email protected]>
Home Page: http://gondor.apana.org.au/~herbert/
PGP Key: http://gondor.apana.org.au/~herbert/pubkey.txt