File: cleanup.h

package info (click to toggle)
drgn 0.1.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 7,852 kB
  • sloc: python: 74,992; ansic: 54,589; awk: 423; makefile: 351; sh: 99
file content (67 lines) | stat: -rw-r--r-- 1,566 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Copyright (c) Meta Platforms, Inc. and affiliates.
// SPDX-License-Identifier: LGPL-2.1-or-later

/**
 * @file
 *
 * Cleanup functions.
 */

#ifndef DRGN_CLEANUP_H
#define DRGN_CLEANUP_H

#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

#define _cleanup_(x) __attribute__((__cleanup__(x)))

/** Call @c free() when the variable goes out of scope. */
#define _cleanup_free_ _cleanup_(freep)
static inline void freep(void *p)
{
	free(*(void **)p);
}

/** Call @c fclose() when the variable goes out of scope. */
#define _cleanup_fclose_ _cleanup_(fclosep)
static inline void fclosep(FILE **fp)
{
	if (*fp)
		fclose(*fp);
}

/** Call @c close() when the variable goes out of scope. */
#define _cleanup_close_ _cleanup_(closep)
static inline void closep(int *fd)
{
	if (*fd >= 0)
		close(*fd);
}

/** Call @c closedir() when the variable goes out of scope. */
#define _cleanup_closedir_ _cleanup_(closedirp)
static inline void closedirp(DIR **dirp)
{
	if (*dirp)
		closedir(*dirp);
}

/**
 * Get the value of a pointer variable and reset it to @c NULL.
 *
 * This can be used to avoid freeing a variable declared with @ref
 * _cleanup_free_ or another scope guard that is a no-op for @c NULL.
 */
#define no_cleanup_ptr(p) ({ __auto_type __ptr = (p); (p) = NULL; __ptr; })

/**
 * Return a pointer declared with @ref _cleanup_free_ without freeing it.
 *
 * This can also be used for other scope guards that are a no-op for @c NULL.
 */
#define return_ptr(p) return no_cleanup_ptr(p)

#endif /* DRGN_CLEANUP_H */