Commit c6269149 authored by Christian Brauner's avatar Christian Brauner

file: add take_fd() cleanup helper

Add a helper that returns the file descriptor and ensures that the old
variable contains a negative value. This makes it easy to rely on
CLASS(get_unused_fd).

Link: https://lore.kernel.org/r/20240627-work-pidfs-v1-1-7e9ab6cc3bb1@kernel.orgReviewed-by: default avatarJeff Layton <jlayton@kernel.org>
Reviewed-by: default avatarJosef Bacik <josef@toxicpanda.com>
Reviewed-by: default avatarAlexander Mikhalitsyn <aleksandr.mikhalitsyn@canonical.com>
Signed-off-by: default avatarChristian Brauner <brauner@kernel.org>
parent ff2c570e
......@@ -63,17 +63,20 @@
#define __free(_name) __cleanup(__free_##_name)
#define __get_and_null_ptr(p) \
({ __auto_type __ptr = &(p); \
__auto_type __val = *__ptr; \
*__ptr = NULL; __val; })
#define __get_and_null(p, nullvalue) \
({ \
__auto_type __ptr = &(p); \
__auto_type __val = *__ptr; \
*__ptr = nullvalue; \
__val; \
})
static inline __must_check
const volatile void * __must_check_fn(const volatile void *val)
{ return val; }
#define no_free_ptr(p) \
((typeof(p)) __must_check_fn(__get_and_null_ptr(p)))
((typeof(p)) __must_check_fn(__get_and_null(p, NULL)))
#define return_ptr(p) return no_free_ptr(p)
......
......@@ -97,6 +97,26 @@ extern void put_unused_fd(unsigned int fd);
DEFINE_CLASS(get_unused_fd, int, if (_T >= 0) put_unused_fd(_T),
get_unused_fd_flags(flags), unsigned flags)
/*
* take_fd() will take care to set @fd to -EBADF ensuring that
* CLASS(get_unused_fd) won't call put_unused_fd(). This makes it
* easier to rely on CLASS(get_unused_fd):
*
* struct file *f;
*
* CLASS(get_unused_fd, fd)(O_CLOEXEC);
* if (fd < 0)
* return fd;
*
* f = dentry_open(&path, O_RDONLY, current_cred());
* if (IS_ERR(f))
* return PTR_ERR(fd);
*
* fd_install(fd, f);
* return take_fd(fd);
*/
#define take_fd(fd) __get_and_null(fd, -EBADF)
extern void fd_install(unsigned int fd, struct file *file);
int receive_fd(struct file *file, int __user *ufd, unsigned int o_flags);
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment