]> git.ipfire.org Git - thirdparty/libvirt.git/commitdiff
util: virstring: Always copy string in virStrcpy
authorPeter Krempa <pkrempa@redhat.com>
Tue, 2 Mar 2021 10:00:23 +0000 (11:00 +0100)
committerPeter Krempa <pkrempa@redhat.com>
Fri, 5 Mar 2021 14:01:29 +0000 (15:01 +0100)
15 out of 72 invocations of virStrcpy(Static) ignore the return value as
it's either impossible to fail or in certain cases a truncated copy is
still good enough. Unfortunately virStrcpy doesn't copy anything in
such case as the checks are done first.

Fix this by using g_strlcpy for the implementation and removing
G_GNUC_WARN_UNUSED_RESULT from the function so that callers can decide
when it's okay.

Signed-off-by: Peter Krempa <pkrempa@redhat.com>
Reviewed-by: Ján Tomko <jtomko@redhat.com>
src/util/virstring.c
src/util/virstring.h

index c3e64007fefadee3bc3ea13bd906e41740aab4ed..a35cd8ba763393d962e7ab1bdc57fab6f31268a3 100644 (file)
@@ -503,16 +503,18 @@ virStrncpy(char *dest, const char *src, size_t n, size_t destbytes)
  * @src: source buffer
  * @destbytes: number of bytes the destination can accommodate
  *
- * Copies @src to @dest.
+ * Copies @src to @dest. @dest is guaranteed to be 'nul' terminated if
+ * destbytes is 1 or more.
  *
- * See virStrncpy() for more information.
- *
- * Returns: 0 on success, <0 on failure.
+ * Returns: 0 on success, -1 if @src doesn't fit into @dest and was truncated.
  */
 int
 virStrcpy(char *dest, const char *src, size_t destbytes)
 {
-    return virStrncpy(dest, src, -1, destbytes);
+    if (g_strlcpy(dest, src, destbytes) >= destbytes)
+        return -1;
+
+    return 0;
 }
 
 /**
index 45aead1838657e5a466c217766791d9308d2ad50..da1fe86ffcae19e3f1c60163944e200adf16819c 100644 (file)
@@ -99,8 +99,7 @@ bool virStringIsEmpty(const char *str);
 
 int virStrncpy(char *dest, const char *src, size_t n, size_t destbytes)
     G_GNUC_WARN_UNUSED_RESULT;
-int virStrcpy(char *dest, const char *src, size_t destbytes)
-    G_GNUC_WARN_UNUSED_RESULT;
+int virStrcpy(char *dest, const char *src, size_t destbytes);
 #define virStrcpyStatic(dest, src) virStrcpy((dest), (src), sizeof(dest))
 
 int virStringSortCompare(const void *a, const void *b);