daemon: Add CLEANUP_* macros which automatically free memory when leaving scope.

cf commit 98b64650c8
This commit is contained in:
Richard W.M. Jones
2013-01-28 15:05:23 +00:00
parent 071de5ccfb
commit 233055974d
2 changed files with 40 additions and 0 deletions

View File

@@ -136,6 +136,11 @@ asprintf_nowarn (char **strp, const char *fmt, ...)
return r;
}
/* Use by the CLEANUP_* macros. */
extern void cleanup_free (void *ptr);
extern void cleanup_free_string_list (void *ptr);
extern void cleanup_unlink_free (void *ptr);
/*-- in names.c (auto-generated) --*/
extern const char *function_names[];
@@ -404,4 +409,15 @@ is_zero (const char *buffer, size_t size)
#define STRCASENEQLEN(a,b,n) (strncasecmp((a),(b),(n)) != 0)
#define STRPREFIX(a,b) (strncmp((a),(b),strlen((b))) == 0)
#ifdef HAVE_ATTRIBUTE_CLEANUP
#define CLEANUP_FREE __attribute__((cleanup(cleanup_free)))
#define CLEANUP_FREE_STRING_LIST \
__attribute__((cleanup(cleanup_free_string_list)))
#define CLEANUP_UNLINK_FREE __attribute__((cleanup(cleanup_unlink_free)))
#else
#define CLEANUP_FREE
#define CLEANUP_FREE_STRING_LIST
#define CLEANUP_UNLINK_FREE
#endif
#endif /* GUESTFSD_DAEMON_H */

View File

@@ -1249,3 +1249,27 @@ udev_settle (void)
{
(void) command (NULL, NULL, str_udevadm, "settle", NULL);
}
/* Use by the CLEANUP_* macros. Do not call these directly. */
void
cleanup_free (void *ptr)
{
free (* (void **) ptr);
}
void
cleanup_free_string_list (void *ptr)
{
free_strings (* (char ***) ptr);
}
void
cleanup_unlink_free (void *ptr)
{
char *filename = * (char **) ptr;
if (filename) {
unlink (filename);
free (filename);
}
}