From c73f752e46494b64f054a5c539dfe5b5ad145518 Mon Sep 17 00:00:00 2001 From: Peter Krempa Date: Feb 22 2019 09:05:45 +0000 Subject: util: alloc: Introduce 'VIR_AUTOCLEAN' macros for clearing stack'd structs The new utility macros are useful for variables we put on the stack but require some cleanup. The most prominent of those is virBuffer which is used almost exclusively in that way. Signed-off-by: Peter Krempa Reviewed-by: Eric Blake --- diff --git a/src/util/viralloc.h b/src/util/viralloc.h index 1d67fff..15451d4 100644 --- a/src/util/viralloc.h +++ b/src/util/viralloc.h @@ -613,7 +613,24 @@ void virAllocTestHook(void (*func)(int, void*), void *data); if (*_ptr) \ (func)(*_ptr); \ *_ptr = NULL; \ - } \ + } + +# define VIR_AUTOCLEAN_FUNC_NAME(type) type##AutoClean + +/** + * VIR_DEFINE_AUTOCLEAN_FUNC: + * @type: type of the variable to be cleared automatically + * @func: cleanup function to be automatically called + * + * This macro defines a function for automatic clearing of + * resources in a stack'd variable of type @type. This newly + * defined function works as a necessary wrapper around @func. + */ +# define VIR_DEFINE_AUTOCLEAN_FUNC(type, func) \ + static inline void VIR_AUTOCLEAN_FUNC_NAME(type)(type *_ptr) \ + { \ + (func)(_ptr); \ + } /** * VIR_AUTOFREE: @@ -638,6 +655,19 @@ void virAllocTestHook(void (*func)(int, void*), void *data); __attribute__((cleanup(VIR_AUTOPTR_FUNC_NAME(type)))) type * /** + * VIR_AUTOCLEAN: + * @type: type of the variable to be cleared automatically + * + * Macro to automatically call clearing function registered for variable of @type + * when the variable goes out of scope. + * The cleanup function is registered by VIR_DEFINE_AUTOCLEAN_FUNC macro for + * the given type. + */ +# define VIR_AUTOCLEAN(type) \ + __attribute__((cleanup(VIR_AUTOCLEAN_FUNC_NAME(type)))) type + + +/** * VIR_AUTOUNREF: * @type: type of an virObject subclass to be unref'd automatically *