Linux Hardening
 help / color / mirror / Atom feed
* [PATCH v1 1/1] lib/string_helpers: Don't copy a tail in kstrdup_and_replace() if 'new' is \0
@ 2023-09-13  9:45 Andy Shevchenko
  2023-09-14 18:37 ` Andy Shevchenko
  0 siblings, 1 reply; 2+ messages in thread
From: Andy Shevchenko @ 2023-09-13  9:45 UTC (permalink / raw)
  To: Andy Shevchenko, linux-hardening, linux-kernel; +Cc: Kees Cook, Andy Shevchenko

The kstrdup_and_replace() takes two characters, old and new, to replace
former with latter after the copying of the original string. But in case
when new is a NUL, there is no point to copy the rest of the string,
the contract with the callers is that that the function returns a
NUL-terminated string and not a buffer of the size filled with a given
data. With this we can optimize the memory consumption by copying only
meaningful part of the original string and drop the rest.

Signed-off-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
---

The first user of this is pending:
https://lore.kernel.org/platform-driver-x86/20230913092701.440959-1-andriy.shevchenko@linux.intel.com/

 lib/string_helpers.c | 6 ++++++
 1 file changed, 6 insertions(+)

diff --git a/lib/string_helpers.c b/lib/string_helpers.c
index 7713f73e66b0..e385bf3cc2de 100644
--- a/lib/string_helpers.c
+++ b/lib/string_helpers.c
@@ -723,11 +723,17 @@ EXPORT_SYMBOL_GPL(kstrdup_quotable_file);
 
 /*
  * Returns duplicate string in which the @old characters are replaced by @new.
+ *
+ * If @new is NUL, copy the string up to the first occurrence of @old, which
+ * will be replaced by a NUL.
  */
 char *kstrdup_and_replace(const char *src, char old, char new, gfp_t gfp)
 {
 	char *dst;
 
+	if (new == '\0')
+		return kmemdup_nul(src, strchrnul(src, old) - src, gfp);
+
 	dst = kstrdup(src, gfp);
 	if (!dst)
 		return NULL;
-- 
2.40.0.1.gaa8946217a0b


^ permalink raw reply related	[flat|nested] 2+ messages in thread

end of thread, other threads:[~2023-09-14 18:37 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2023-09-13  9:45 [PATCH v1 1/1] lib/string_helpers: Don't copy a tail in kstrdup_and_replace() if 'new' is \0 Andy Shevchenko
2023-09-14 18:37 ` Andy Shevchenko

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox