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