49978a8
From: Liviu Chircu <liviu@opensips.org>
49978a8
Date: Fri, 2 Feb 2018 16:21:23 +0200
49978a8
Subject: [PATCH] ut.h: Minor additions
49978a8
49978a8
    * add shm_str_sync() and shm_str_clean()
49978a8
    * improve robustness during error states
49978a8
49978a8
(cherry picked from commit 664aee60dabb0f9a4454b0d4a090d81c6b7a6fc4)
49978a8
49978a8
diff --git a/ut.h b/ut.h
49978a8
index d3c39f380..3476a5832 100644
49978a8
--- a/ut.h
49978a8
+++ b/ut.h
49978a8
@@ -595,6 +595,7 @@ static inline int shm_str_dup(str* dst, const str* src)
49978a8
 	dst->s = shm_malloc(src->len);
49978a8
 	if (!dst->s) {
49978a8
 		LM_ERR("no shared memory left\n");
49978a8
+		dst->len = 0;
49978a8
 		return -1;
49978a8
 	}
49978a8
 
49978a8
@@ -603,6 +604,7 @@ static inline int shm_str_dup(str* dst, const str* src)
49978a8
 	return 0;
49978a8
 }
49978a8
 
49978a8
+
49978a8
 /*
49978a8
  * Make a copy of an str structure using shm_malloc
49978a8
  *	  + an additional '\0' byte, so you can make use of dst->s
49978a8
@@ -617,6 +619,7 @@ static inline int shm_nt_str_dup(str* dst, const str* src)
49978a8
 	dst->s = shm_malloc(src->len + 1);
49978a8
 	if (!dst->s) {
49978a8
 		LM_ERR("no shared memory left\n");
49978a8
+		dst->len = 0;
49978a8
 		return -1;
49978a8
 	}
49978a8
 
49978a8
@@ -661,15 +664,49 @@ static inline int shm_str_resize(str *in, int size)
49978a8
 	return 0;
49978a8
 }
49978a8
 
49978a8
+
49978a8
+/*
49978a8
+ * Ensure "dst" matches the content of "src" without leaking memory
49978a8
+ *
49978a8
+ * Note: if you just want to dup a string, use "shm_str_dup()" instead
49978a8
+ */
49978a8
+static inline int shm_str_sync(str* dst, const str* src)
49978a8
+{
49978a8
+	if (!src || !src->s || src->len == 0) {
49978a8
+		if (dst->s)
49978a8
+			shm_free(dst->s);
49978a8
+		memset(dst, 0, sizeof *dst);
49978a8
+		return 0;
49978a8
+	}
49978a8
+
49978a8
+	if (shm_str_resize(dst, src->len) != 0) {
49978a8
+		LM_ERR("oom\n");
49978a8
+		return -1;
49978a8
+	}
49978a8
+
49978a8
+	memcpy(dst->s, src->s, src->len);
49978a8
+	dst->len = src->len;
49978a8
+	return 0;
49978a8
+}
49978a8
+
49978a8
+
49978a8
+static inline void shm_str_clean(str* dst)
49978a8
+{
49978a8
+	if (dst->s)
49978a8
+		shm_free(dst->s);
49978a8
+	memset(dst, 0, sizeof *dst);
49978a8
+}
49978a8
+
49978a8
+
49978a8
 /*
49978a8
  * Make a copy of a str structure using pkg_malloc
49978a8
  */
49978a8
 static inline int pkg_str_dup(str* dst, const str* src)
49978a8
 {
49978a8
 	dst->s = pkg_malloc(src->len);
49978a8
-	if (dst->s==NULL)
49978a8
-	{
49978a8
+	if (!dst->s) {
49978a8
 		LM_ERR("no private memory left\n");
49978a8
+		dst->len = 0;
49978a8
 		return -1;
49978a8
 	}
49978a8