summaryrefslogtreecommitdiff
path: root/src/fundamental
diff options
context:
space:
mode:
authorLennart Poettering <lennart@poettering.net>2023-01-10 12:39:14 +0100
committerLennart Poettering <lennart@poettering.net>2023-01-16 16:19:07 +0100
commit5040b2cfab1f3d778b6d253b5c5c5f50980f6535 (patch)
tree7dd5e0f00886d72b20a438fb59f567bf812d0136 /src/fundamental
parent692597c84395ad2b3f8e221bb1eca55a9dfc544f (diff)
downloadsystemd-5040b2cfab1f3d778b6d253b5c5c5f50980f6535.tar.gz
memory-util: add CLEANUP_ERASE_PTR() macro and use it
Diffstat (limited to 'src/fundamental')
-rw-r--r--src/fundamental/memory-util-fundamental.h28
1 files changed, 26 insertions, 2 deletions
diff --git a/src/fundamental/memory-util-fundamental.h b/src/fundamental/memory-util-fundamental.h
index 67621fdb42..78e2dbec59 100644
--- a/src/fundamental/memory-util-fundamental.h
+++ b/src/fundamental/memory-util-fundamental.h
@@ -29,6 +29,8 @@ static inline void *explicit_bzero_safe(void *p, size_t l) {
#endif
struct VarEraser {
+ /* NB: This is a pointer to memory to erase in case of CLEANUP_ERASE(). Pointer to pointer to memory
+ * to erase in case of CLEANUP_ERASE_PTR() */
void *p;
size_t size;
};
@@ -38,5 +40,27 @@ static inline void erase_var(struct VarEraser *e) {
}
/* Mark var to be erased when leaving scope. */
-#define CLEANUP_ERASE(var) \
- _cleanup_(erase_var) _unused_ struct VarEraser CONCATENATE(_eraser_, UNIQ) = { .p = &var, .size = sizeof(var) }
+#define CLEANUP_ERASE(var) \
+ _cleanup_(erase_var) _unused_ struct VarEraser CONCATENATE(_eraser_, UNIQ) = { \
+ .p = &(var), \
+ .size = sizeof(var), \
+ }
+
+static inline void erase_varp(struct VarEraser *e) {
+
+ /* Very similar to erase_var(), but assumes `p` is a pointer to a pointer whose memory shall be destructed. */
+ if (!e->p)
+ return;
+
+ explicit_bzero_safe(*(void**) e->p, e->size);
+}
+
+/* Mark pointer so that memory pointed to is erased when leaving scope. Note: this takes a pointer to the
+ * specified pointer, instead of just a copy of it. This is to allow callers to invalidate the pointer after
+ * use, if they like, disabling our automatic erasure (for example because they succeeded with whatever they
+ * wanted to do and now intend to return the allocated buffer to their caller without it being erased). */
+#define CLEANUP_ERASE_PTR(ptr, sz) \
+ _cleanup_(erase_varp) _unused_ struct VarEraser CONCATENATE(_eraser_, UNIQ) = { \
+ .p = (ptr), \
+ .size = (sz), \
+ }