diff mbox series

Introduce strlcpy() as string copy replacement

Message ID 20200405122321.16884-1-sbabic@denx.de
State Accepted
Headers show
Series Introduce strlcpy() as string copy replacement | expand

Commit Message

Stefano Babic April 5, 2020, 12:23 p.m. UTC
strncpy() is often considered not safe becuase it can leave the
a null terminated string in the destination. Add strlcpy() from FreeBSD
(function will be built for linux only).

Signed-off-by: Stefano Babic <sbabic@denx.de>
---
 core/util.c    | 16 ++++++++++++++++
 include/util.h |  5 +++++
 2 files changed, 21 insertions(+)
diff mbox series

Patch

diff --git a/core/util.c b/core/util.c
index 33d6bb9..78a57fc 100644
--- a/core/util.c
+++ b/core/util.c
@@ -214,6 +214,22 @@  char *substring(const char *src, int first, int len) {
 	return s;
 }
 
+#if defined(__linux__)
+size_t
+strlcpy(char *dst, const char * src, size_t size)
+{
+
+    size_t len = strlen(src);
+    if (len < size) {
+        memcpy(dst, src, len + 1);
+    } else if (len) {
+        memcpy(dst, src, len - 1);
+	/* Add C string terminator */
+        dst[len - 1] = '\0';
+    }
+    return len;
+}
+#endif
 
 int openfileoutput(const char *filename)
 {
diff --git a/include/util.h b/include/util.h
index f397113..8d1757f 100644
--- a/include/util.h
+++ b/include/util.h
@@ -169,6 +169,11 @@  int copy_write(void *out, const void *buf, unsigned int len);
 #if defined(__FreeBSD__)
 int copy_write_padded(void *out, const void *buf, unsigned int len);
 #endif
+#if defined(__linux__)
+/* strlcpy was originally developped in FreeBSD, not present in glibc */
+size_t
+strlcpy(char *dst, const char * src, size_t size);
+#endif
 int copyfile(int fdin, void *out, unsigned int nbytes, unsigned long *offs,
 	unsigned long long seek,
 	int skip_file, int compressed, uint32_t *checksum,