]> git.ipfire.org Git - thirdparty/linux.git/commitdiff
file: add take_fd() cleanup helper
authorChristian Brauner <brauner@kernel.org>
Thu, 27 Jun 2024 14:11:39 +0000 (16:11 +0200)
committerChristian Brauner <brauner@kernel.org>
Fri, 28 Jun 2024 08:36:45 +0000 (10:36 +0200)
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>
include/linux/cleanup.h
include/linux/file.h

index c2d09bc4f9768cc3321dbb4490216fd0a2699320..80c4181e194aa7a1ca5d29f3c3ded4b59a777487 100644 (file)
 
 #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)
 
index 45d0f4800abd417a6fdd9be58988046cb5430ac8..237931f20739f3840fecdfcce122a5984b81e8cd 100644 (file)
@@ -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);