Implement lttng_strncpy safe string copy
authorMathieu Desnoyers <mathieu.desnoyers@efficios.com>
Tue, 17 May 2016 01:42:40 +0000 (21:42 -0400)
committerJérémie Galarneau <jeremie.galarneau@efficios.com>
Fri, 20 May 2016 20:35:29 +0000 (16:35 -0400)
Signed-off-by: Mathieu Desnoyers <mathieu.desnoyers@efficios.com>
Signed-off-by: Jérémie Galarneau <jeremie.galarneau@efficios.com>
src/common/macros.h

index fc159c0af3c707102d7bb853a49360d16e01c1d1..a03b02ac4ab96122a4ab32794069aced3972fcf0 100644 (file)
@@ -20,6 +20,7 @@
 #define _MACROS_H
 
 #include <stdlib.h>
+#include <string.h>
 
 /*
  * Takes a pointer x and transform it so we can use it to access members
 #define LTTNG_HIDDEN __attribute__((visibility("hidden")))
 #endif
 
+/*
+ * lttng_strncpy returns 0 on success, or nonzero on failure.
+ * It checks that the @src string fits into @dst_len before performing
+ * the copy. On failure, no copy has been performed.
+ *
+ * dst_len includes the string's trailing NULL.
+ */
+static inline
+int lttng_strncpy(char *dst, const char *src, size_t dst_len)
+{
+       if (strnlen(src, dst_len) == dst_len) {
+               /* Fail since copying would result in truncation. */
+               return -1;
+       }
+       strncpy(dst, src, dst_len);
+       /*
+        * Be extra careful and put final \0 at the end after strncpy(),
+        * even though we checked the length before. This makes Coverity
+        * happy.
+        */
+       dst[dst_len - 1] = '\0';
+       return 0;
+}
+
 #endif /* _MACROS_H */
This page took 0.026036 seconds and 4 git commands to generate.