Skip to contentSkip to conversation

string: strl(cat|cpy)

PATCH New Sean Anderson 3 participants 18 messages Mar 11, 2021 – Apr 13, 2021

Subsystems (5)
lore
Share & tools
lore
#0 lore raw

v2 cover string: strl(cat|cpy)

This series adds support for strl(cat|cpy), and brings their implementations in-line with what is documented in the Linux man pages. It also fixes some potential (actual) fastboot bugs. Lastly, it adds a patman check to suggest using these functions over strn(cat|cpy). I think these functions provide a much better interface, which removes some footguns from U-Boot.

Changes in v2:
- Fix strlcpy return value
- Add implementation of strlcat
- Add test for strlcat
- Fix bug in fastboot
- Move check to u_boot_line

Sean Anderson (5):
lib: string: Fix strlcpy return value
lib: string: Implement strlcat
test: Add test for strlcat
fastboot: Fix possible buffer overrun
checkpatch: Add warnings for using strn(cat|cpy)

 drivers/fastboot/fb_mmc.c       |   6 +-
 drivers/usb/dwc3/linux-compat.h |   6 --
 include/linux/string.h          |   3 +
 lib/string.c                    |  31 +++++++-
 scripts/checkpatch.pl           |   6 ++
 test/lib/Makefile               |   1 +
 test/lib/strlcat.c              | 126 ++++++++++++++++++++++++++++++++
 tools/patman/test_checkpatch.py |  14 +++-
 8 files changed, 179 insertions(+), 14 deletions(-)
 create mode 100644 test/lib/strlcat.c
Signature · 1 line
2.30.1
#1 lore raw

PATCH v2 1/5 lib: string: Fix strlcpy return value

strlcpy should always return the number of bytes copied. We were accidentally missing the nul-terminator. We also always used to return a non-zero value, even if we did not actually copy anything.

Fixes 23cd138503 ("Integrate USB gadget layer and USB CDC driver layer")

---

Changes in v2:
- New

 lib/string.c | 12 ++++++++----
 1 file changed, 8 insertions(+), 4 deletions(-)
lib/string.c +8 -4
index 73b984123d..1b867ac09d 100644
@@ -114,17 +114,21 @@ char * strncpy(char * dest,const char *src,size_t count)
  * NUL-terminated string that fits in the buffer (unless,
  * of course, the buffer size is zero). It does not pad
  * out the result like strncpy() does.
+ *
+ * Return: the number of bytes copied
  */
 size_t strlcpy(char *dest, const char *src, size_t size)
 {
-	size_t ret = strlen(src);
-
 	if (size) {
-		size_t len = (ret >= size) ? size - 1 : ret;
+		size_t srclen = strlen(src);
+		size_t len = (srclen >= size) ? size - 1 : srclen;
+
 		memcpy(dest, src, len);
 		dest[len] = '\0';
+		return len + 1;
 	}
-	return ret;
+
+	return 0;
 }
 #endif
 
Signature · 1 line
2.30.1
#2 lore raw

PATCH v2 1/5 lib: string: Fix strlcpy return value

Hi Sean,

Quoted 7 lines · Sean Anderson

strlcpy should always return the number of bytes copied. We were accidentally missing the nul-terminator. We also always used to return a non-zero value, even if we did not actually copy anything.

Fixes 23cd138503 ("Integrate USB gadget layer and USB CDC driver layer")
Quoted 8 lines

---

Changes in v2:
- New

 lib/string.c | 12 ++++++++----
 1 file changed, 8 insertions(+), 4 deletions(-)

Please can you add a test while you are here? Might be easier on the -next branch.

Regards,
Simon

#3 lore raw

PATCH v2 1/5 lib: string: Fix strlcpy return value

Quoted 13 lines · Simon Glass

Hi Sean,

Quoted 10 lines · Sean Anderson

strlcpy should always return the number of bytes copied. We were accidentally missing the nul-terminator. We also always used to return a non-zero value, even if we did not actually copy anything.

Fixes 23cd138503 ("Integrate USB gadget layer and USB CDC driver layer")

---

Quoted 8 lines
Quoted 5 lines

Changes in v2:
- New

  lib/string.c | 12 ++++++++----
  1 file changed, 8 insertions(+), 4 deletions(-)

Please can you add a test while you are here? Might be easier on the -next branch.

This is tested in patch 3 as strlcat is implemented with strlcpy. Though it looks like I will need to change the implementation...

--Sean

Quoted 4 lines

Regards,
Simon

#4 lore raw

PATCH v2 1/5 lib: string: Fix strlcpy return value

Hi Sean,

Quoted 18 lines · Sean Anderson
Quoted 16 lines · Simon Glass

Hi Sean,

Quoted 13 lines · Sean Anderson

strlcpy should always return the number of bytes copied. We were accidentally missing the nul-terminator. We also always used to return a non-zero value, even if we did not actually copy anything.

Fixes 23cd138503 ("Integrate USB gadget layer and USB CDC driver layer")

---

Changes in v2:
- New

Quoted 8 lines
Quoted 5 lines
Quoted 2 lines
  lib/string.c | 12 ++++++++----
  1 file changed, 8 insertions(+), 4 deletions(-)

Please can you add a test while you are here? Might be easier on the -next branch.

This is tested in patch 3 as strlcat is implemented with strlcpy. Though it looks like I will need to change the implementation...

Yes but I still think it is good to have a few simple test for this function .Transitive tests are quite a bit harder to understand. Perhaps just 3-4 cases?

Regards,
Simon

#5 lore raw

PATCH v2 1/5 lib: string: Fix strlcpy return value

In reply to Sean Anderson
Quoted 2 lines · Sean Anderson

strlcpy should always return the number of bytes copied. We were accidentally missing the nul-terminator. We also always used to return a

It looks like I was a bit bullish in assuming a mistake. After reviewing the man page, it looks like the nul-terminator is intentionally excluded.

Quoted 5 lines

The strlcpy() and strlcat() functions return the total length of the string they tried to create. For strlcpy() that means the length of src. For strlcat() that means the initial length of dst plus the length of src. While this may seem somewhat confusing, it was done to make truncation detection simple.

In particular, we should return the length of the string, which may be different from the amount of bytes copied. However, the non-zero return value should be fixed.

Quoted 44 lines

non-zero value, even if we did not actually copy anything.

Fixes 23cd138503 ("Integrate USB gadget layer and USB CDC driver layer")

---

Changes in v2:
- New

  lib/string.c | 12 ++++++++----
  1 file changed, 8 insertions(+), 4 deletions(-)
lib/string.c +8 -4
index 73b984123d..1b867ac09d 100644
@@ -114,17 +114,21 @@ char * strncpy(char * dest,const char *src,size_t count)
   * NUL-terminated string that fits in the buffer (unless,
   * of course, the buffer size is zero). It does not pad
   * out the result like strncpy() does.
+ *
+ * Return: the number of bytes copied
   */
  size_t strlcpy(char *dest, const char *src, size_t size)
  {
-	size_t ret = strlen(src);
-
  	if (size) {
-		size_t len = (ret >= size) ? size - 1 : ret;
+		size_t srclen = strlen(src);
+		size_t len = (srclen >= size) ? size - 1 : srclen;
+
  		memcpy(dest, src, len);
  		dest[len] = '\0';
+		return len + 1;
  	}
-	return ret;
+
+	return 0;
  }
  #endif
 
#6 lore raw

PATCH v2 1/5 lib: string: Fix strlcpy return value

In reply to Sean Anderson
Quoted 7 lines · Sean Anderson

strlcpy should always return the number of bytes copied. We were accidentally missing the nul-terminator. We also always used to return a non-zero value, even if we did not actually copy anything.

Fixes 23cd138503 ("Integrate USB gadget layer and USB CDC driver layer")

Applied to u-boot/master, thanks!

Signature · 8 lines
Tom
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 659 bytes
Desc: not available
URL: <https://lists.denx.de/pipermail/u-boot/attachments/20210413/5b008d73/attachment.sig>
#7 lore raw

PATCH v2 2/5 lib: string: Implement strlcat

In reply to Sean Anderson

This introduces strlcat, which provides a safer interface than strncat. It never copies more than its size bytes, including the terminating nul. In addition, it never reads past dest[size - 1], even if dest is not nul-terminated.

This also removes the stub for dwc3 now that we have a proper implementation.

---

Changes in v2:
- New

 drivers/usb/dwc3/linux-compat.h |  6 ------
 include/linux/string.h          |  3 +++
 lib/string.c                    | 19 +++++++++++++++++++
 3 files changed, 22 insertions(+), 6 deletions(-)
drivers/usb/dwc3/linux-compat.h +0 -6
index 82793765be..3bb0bda5a6 100644
@@ -13,10 +13,4 @@
 
 #define dev_WARN(dev, format, arg...)	debug(format, ##arg)
 
-static inline size_t strlcat(char *dest, const char *src, size_t n)
-{
-	strcat(dest, src);
-	return strlen(dest) + strlen(src);
-}
-
 #endif
include/linux/string.h +3 -0
index d67998e5c4..dd255f2163 100644
@@ -35,6 +35,9 @@ extern char * strcat(char *, const char *);
 #ifndef __HAVE_ARCH_STRNCAT
 extern char * strncat(char *, const char *, __kernel_size_t);
 #endif
+#ifndef __HAVE_ARCH_STRLCAT
+size_t strlcat(char *, const char *, size_t);
+#endif
 #ifndef __HAVE_ARCH_STRCMP
 extern int strcmp(const char *,const char *);
 #endif
lib/string.c +19 -0
index 1b867ac09d..a0cff8fe88 100644
@@ -180,6 +180,25 @@ char * strncat(char *dest, const char *src, size_t count)
 }
 #endif
 
+#ifndef __HAVE_ARCH_STRLCAT
+/**
+ * strlcat - Append a length-limited, %NUL-terminated string to another
+ * @dest: The string to be appended to
+ * @src: The string to append to it
+ * @size: The size of @dest
+ *
+ * Compatible with *BSD: the result is always a valid NUL-terminated string that
+ * fits in the buffer (unless, of course, the buffer size is zero). It does not
+ * write past @size like strncat() does.
+ */
+size_t strlcat(char *dest, const char *src, size_t size)
+{
+	size_t len = strnlen(dest, size);
+
+	return len + strlcpy(dest + len, src, size - len);
+}
+#endif
+
 #ifndef __HAVE_ARCH_STRCMP
 /**
  * strcmp - Compare two strings
Signature · 1 line
2.30.1
#8 lore raw

PATCH v2 2/5 lib: string: Implement strlcat

Quoted 12 lines · Sean Anderson

This introduces strlcat, which provides a safer interface than strncat. It never copies more than its size bytes, including the terminating nul. In addition, it never reads past dest[size - 1], even if dest is not nul-terminated.

This also removes the stub for dwc3 now that we have a proper implementation.

---

Quoted 7 lines

Changes in v2:
- New

 drivers/usb/dwc3/linux-compat.h |  6 ------
 include/linux/string.h          |  3 +++
 lib/string.c                    | 19 +++++++++++++++++++
 3 files changed, 22 insertions(+), 6 deletions(-)
#9 lore raw

PATCH v2 2/5 lib: string: Implement strlcat

In reply to Sean Anderson
Quoted 10 lines · Sean Anderson

This introduces strlcat, which provides a safer interface than strncat. It never copies more than its size bytes, including the terminating nul. In addition, it never reads past dest[size - 1], even if dest is not nul-terminated.

This also removes the stub for dwc3 now that we have a proper implementation.

Applied to u-boot/master, thanks!

Signature · 8 lines
Tom
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 659 bytes
Desc: not available
URL: <https://lists.denx.de/pipermail/u-boot/attachments/20210413/99e7e408/attachment.sig>
#10 lore raw

PATCH v2 3/5 test: Add test for strlcat

In reply to Sean Anderson

This test is adapted from glibc, which is very concerned about alignment. It also tests strlcpy by dependency.

---

Changes in v2:
- New

 test/lib/Makefile  |   1 +
 test/lib/strlcat.c | 126 +++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 127 insertions(+)
 create mode 100644 test/lib/strlcat.c
test/lib/Makefile +1 -0
index 97c11e35a8..685d1c95d8 100644
@@ -10,6 +10,7 @@ obj-y += lmb.o
 obj-$(CONFIG_CONSOLE_RECORD) += test_print.o
 obj-$(CONFIG_SSCANF) += sscanf.o
 obj-y += string.o
+obj-y += strlcat.o
 obj-$(CONFIG_ERRNO_STR) += test_errno_str.o
 obj-$(CONFIG_UT_LIB_ASN1) += asn1.o
 obj-$(CONFIG_UT_LIB_RSA) += rsa.o
test/lib/strlcat.c new file +126 -0

126 lines not on this page · raw message

Signature · 1 line
2.30.1
#11 lore raw

PATCH v2 3/5 test: Add test for strlcat

Hi Sean,

Quoted 7 lines · Sean Anderson

This test is adapted from glibc, which is very concerned about alignment. It also tests strlcpy by dependency.

---

Quoted 7 lines

Changes in v2:
- New

 test/lib/Makefile  |   1 +
 test/lib/strlcat.c | 126 +++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 127 insertions(+)
 create mode 100644 test/lib/strlcat.c

Gosh, it certainly is.

I do wonder whether you are better just using ut_asserteq_str() since people get the line number and that is normally enough to repeat and find the failure.

- Simon

#12 lore raw

PATCH v2 3/5 test: Add test for strlcat

In reply to Sean Anderson
Quoted 5 lines · Sean Anderson

This test is adapted from glibc, which is very concerned about alignment. It also tests strlcpy by dependency.

Applied to u-boot/master, thanks!

Signature · 8 lines
Tom
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 659 bytes
Desc: not available
URL: <https://lists.denx.de/pipermail/u-boot/attachments/20210413/82430c3b/attachment.sig>
#13 lore raw

PATCH v2 4/5 fastboot: Fix possible buffer overrun

In reply to Sean Anderson

This fixes several uses of strn(cpy|cat) which did not terminate their destinations properly.

Fixes de1728ce4c ("fastboot: Allow u-boot-style partitions")

Reported-by Coverity Scan

---

Changes in v2:
- New

 drivers/fastboot/fb_mmc.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
drivers/fastboot/fb_mmc.c +3 -3
index 8e74e50e91..2f3837e559 100644
@@ -40,7 +40,7 @@ static int raw_part_get_info_by_name(struct blk_desc *dev_desc,
 
 	/* check for raw partition descriptor */
 	strcpy(env_desc_name, "fastboot_raw_partition_");
-	strncat(env_desc_name, name, PART_NAME_LEN);
+	strlcat(env_desc_name, name, PART_NAME_LEN);
 	raw_part_desc = strdup(env_get(env_desc_name));
 	if (raw_part_desc == NULL)
 		return -ENODEV;
@@ -61,7 +61,7 @@ static int raw_part_get_info_by_name(struct blk_desc *dev_desc,
 	info->start = simple_strtoul(argv[0], NULL, 0);
 	info->size = simple_strtoul(argv[1], NULL, 0);
 	info->blksz = dev_desc->blksz;
-	strncpy((char *)info->name, name, PART_NAME_LEN);
+	strlcpy((char *)info->name, name, PART_NAME_LEN);
 
 	if (raw_part_desc) {
 		if (strcmp(strsep(&raw_part_desc, " "), "mmcpart") == 0) {
@@ -114,7 +114,7 @@ static int part_get_info_by_name_or_alias(struct blk_desc **dev_desc,
 
 		/* check for alias */
 		strcpy(env_alias_name, "fastboot_partition_alias_");
-		strncat(env_alias_name, name, PART_NAME_LEN);
+		strlcat(env_alias_name, name, PART_NAME_LEN);
 		aliased_part_name = env_get(env_alias_name);
 		if (aliased_part_name != NULL)
 			ret = do_get_part_info(dev_desc, aliased_part_name,
Signature · 1 line
2.30.1
#14 lore raw

PATCH v2 4/5 fastboot: Fix possible buffer overrun

Quoted 7 lines · Sean Anderson

This fixes several uses of strn(cpy|cat) which did not terminate their destinations properly.

Fixes de1728ce4c ("fastboot: Allow u-boot-style partitions")

Reported-by Coverity Scan

Applied to u-boot/master, thanks!

Signature · 8 lines
Tom
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 659 bytes
Desc: not available
URL: <https://lists.denx.de/pipermail/u-boot/attachments/20210413/5cb22c8a/attachment.sig>
#15 lore raw

PATCH v2 5/5 checkpatch: Add warnings for using strn(cat|cpy)

In reply to Sean Anderson

strn(cat|cpy) has a bad habit of not nul-terminating the destination, resulting in constructions like

	strncpy(foo, bar, sizeof(foo) - 1);
	foo[sizeof(foo) - 1] = '\0';

However, it is very easy to forget about this behavior and accidentally leave a string unterminated. This has shown up in some recent coverity scans [1, 2] (including code recently touched by yours truly).

Fortunately, the guys at OpenBSD came up with strl(cat|cpy), which always nul-terminate strings. These functions are already in U-Boot, so we should encourage new code to use them instead of strn(cat|cpy).

[1] https://lists.denx.de/pipermail/u-boot/2021-March/442888.html
[2] https://lists.denx.de/pipermail/u-boot/2021-January/438073.html

---

Changes in v2:
- Move check to u_boot_line

 scripts/checkpatch.pl           |  6 ++++++
 tools/patman/test_checkpatch.py | 14 +++++++++++++-
 2 files changed, 19 insertions(+), 1 deletion(-)
scripts/checkpatch.pl +6 -0
index 755f4802a4..4e047586a6 100755
@@ -2365,6 +2365,12 @@ sub u_boot_line {
 		     "Use 'if (IS_ENABLED(CONFIG...))' instead of '#if or #ifdef' where possible\n" . $herecurr);
 	}
 
+	# prefer strl(cpy|cat) over strn(cpy|cat)
+	if ($line =~ /\bstrn(cpy|cat)\s*\(/) {
+		WARN("STRL",
+		     "strl$1 is preferred over strn$1 because it always produces a nul-terminated string\n" . $herecurr);
+	}
+
 	# use defconfig to manage CONFIG_CMD options
 	if ($line =~ /\+\s*#\s*(define|undef)\s+(CONFIG_CMD\w*)\b/) {
 		ERROR("DEFINE_CONFIG_CMD",
tools/patman/test_checkpatch.py +13 -1
index a4fec1d4c1..56af5265cc 100644
@@ -353,7 +353,7 @@ index 0000000..2234c87
 
         Args:
             pm: PatchMaker object to use
-            msg" Expected message (e.g. 'LIVETREE')
+            msg: Expected message (e.g. 'LIVETREE')
             pmtype: Type of problem ('error', 'warning')
         """
         result = pm.run_checkpatch()
@@ -439,6 +439,18 @@ index 0000000..2234c87
         self.check_struct('per_device_auto', '_priv', 'DEVICE_PRIV_AUTO')
         self.check_struct('per_device_plat_auto', '_plat', 'DEVICE_PLAT_AUTO')
 
+    def check_strl(self, func):
+        """Check one of the checks for strn(cpy|cat)"""
+        pm = PatchMaker()
+        pm.add_line('common/main.c', "strn%s(foo, bar, sizeof(foo));" % func)
+        self.checkSingleMessage(pm, "STRL",
+            "strl%s is preferred over strn%s because it always produces a nul-terminated string\n"
+            % (func, func))
+
+    def testStrl(self):
+        """Check for uses of strn(cat|cpy)"""
+        self.check_strl("cat");
+        self.check_strl("cpy");
 
 if __name__ == "__main__":
     unittest.main()
Signature · 1 line
2.30.1
#16 lore raw

PATCH v2 5/5 checkpatch: Add warnings for using strn(cat|cpy)

Quoted 19 lines · Sean Anderson

strn(cat|cpy) has a bad habit of not nul-terminating the destination, resulting in constructions like

        strncpy(foo, bar, sizeof(foo) - 1);
        foo[sizeof(foo) - 1] = '\0';

However, it is very easy to forget about this behavior and accidentally leave a string unterminated. This has shown up in some recent coverity scans [1, 2] (including code recently touched by yours truly).

Fortunately, the guys at OpenBSD came up with strl(cat|cpy), which always nul-terminate strings. These functions are already in U-Boot, so we should encourage new code to use them instead of strn(cat|cpy).

[1] https://lists.denx.de/pipermail/u-boot/2021-March/442888.html
[2] https://lists.denx.de/pipermail/u-boot/2021-January/438073.html

Quoted 8 lines

---

Changes in v2:
- Move check to u_boot_line

 scripts/checkpatch.pl           |  6 ++++++
 tools/patman/test_checkpatch.py | 14 +++++++++++++-
 2 files changed, 19 insertions(+), 1 deletion(-)
#17 lore raw

PATCH v2 5/5 checkpatch: Add warnings for using strn(cat|cpy)

In reply to Sean Anderson
Quoted 14 lines · Sean Anderson

strn(cat|cpy) has a bad habit of not nul-terminating the destination, resulting in constructions like

	strncpy(foo, bar, sizeof(foo) - 1);
	foo[sizeof(foo) - 1] = '\0';

However, it is very easy to forget about this behavior and accidentally leave a string unterminated. This has shown up in some recent coverity scans [1, 2] (including code recently touched by yours truly).

Fortunately, the guys at OpenBSD came up with strl(cat|cpy), which always nul-terminate strings. These functions are already in U-Boot, so we should encourage new code to use them instead of strn(cat|cpy).

Quoted 5 lines

[1] https://lists.denx.de/pipermail/u-boot/2021-March/442888.html
[2] https://lists.denx.de/pipermail/u-boot/2021-January/438073.html

Applied to u-boot/master, thanks!

Signature · 8 lines
Tom
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 659 bytes
Desc: not available
URL: <https://lists.denx.de/pipermail/u-boot/attachments/20210413/13bfa119/attachment.sig>