Skip to content

Commit

Permalink
file: add take_fd() cleanup helper
Browse files Browse the repository at this point in the history
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.org
Reviewed-by: Jeff Layton <jlayton@kernel.org>
Reviewed-by: Josef Bacik <josef@toxicpanda.com>
Reviewed-by: Alexander Mikhalitsyn <aleksandr.mikhalitsyn@canonical.com>
Signed-off-by: Christian Brauner <brauner@kernel.org>
  • Loading branch information
Christian Brauner committed Jun 28, 2024
1 parent ff2c570 commit c626914
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
13 changes: 8 additions & 5 deletions include/linux/cleanup.h
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down
20 changes: 20 additions & 0 deletions include/linux/file.h
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down

0 comments on commit c626914

Please sign in to comment.