]> git.ipfire.org Git - thirdparty/coreutils.git/commitdiff
maint: basenc: consistently check buffer bounds when encoding
authorPádraig Brady <P@draigBrady.com>
Tue, 19 Mar 2024 15:55:18 +0000 (15:55 +0000)
committerPádraig Brady <P@draigBrady.com>
Tue, 19 Mar 2024 23:43:53 +0000 (23:43 +0000)
* src/basenc.c (base16_encode, base2msbf_encode, base2lsbf_encode):
Ensure we don't overflow the output buffer, whose length is
passed in the OUTLEN parameter.  This issue was flagged by clang
with -Wunused-but-set-parameter.

src/basenc.c

index 903c623b7d028d9a32b7ca2dcdca743e0492e527..ba3186a2225f305d6c67c21971a96699f002aa91 100644 (file)
@@ -630,12 +630,14 @@ base16_encode (char const *restrict in, idx_t inlen,
 {
   static const char base16[16] = "0123456789ABCDEF";
 
-  while (inlen--)
+  while (inlen && outlen)
     {
       unsigned char c = *in;
       *out++ = base16[c >> 4];
       *out++ = base16[c & 0x0F];
       ++in;
+      inlen--;
+      outlen -= 2;
     }
 }
 
@@ -904,7 +906,7 @@ inline static void
 base2msbf_encode (char const *restrict in, idx_t inlen,
                   char *restrict out, idx_t outlen)
 {
-  while (inlen--)
+  while (inlen && outlen)
     {
       unsigned char c = *in;
       for (int i = 0; i < 8; i++)
@@ -912,6 +914,7 @@ base2msbf_encode (char const *restrict in, idx_t inlen,
           *out++ = c & 0x80 ? '1' : '0';
           c <<= 1;
         }
+      inlen--;
       outlen -= 8;
       ++in;
     }
@@ -921,7 +924,7 @@ inline static void
 base2lsbf_encode (char const *restrict in, idx_t inlen,
                   char *restrict out, idx_t outlen)
 {
-  while (inlen--)
+  while (inlen && outlen)
     {
       unsigned char c = *in;
       for (int i = 0; i < 8; i++)
@@ -929,6 +932,7 @@ base2lsbf_encode (char const *restrict in, idx_t inlen,
           *out++ = c & 0x01 ? '1' : '0';
           c >>= 1;
         }
+      inlen--;
       outlen -= 8;
       ++in;
     }