[PATCH v2 1/2] libbb: add xopen_as() helper

Rasmus Villemoes rasmus.villemoes at prevas.dk
Thu Mar 4 21:02:48 UTC 2021


xmove_fd(xopen(...), ...) is a common pattern. Add a helper for
that. On x86-64, this compiles to 18 bytes, so just a few call sites
need to be converted for a net win.

Signed-off-by: Rasmus Villemoes <rasmus.villemoes at prevas.dk>
---
 include/libbb.h       | 1 +
 libbb/xfuncs_printf.c | 6 ++++++
 2 files changed, 7 insertions(+)

diff --git a/include/libbb.h b/include/libbb.h
index ece03e7d8..bdd99403d 100644
--- a/include/libbb.h
+++ b/include/libbb.h
@@ -608,6 +608,7 @@ int open3_or_warn(const char *pathname, int flags, int mode) FAST_FUNC;
 int open_or_warn(const char *pathname, int flags) FAST_FUNC;
 int xopen3(const char *pathname, int flags, int mode) FAST_FUNC;
 int xopen(const char *pathname, int flags) FAST_FUNC;
+void xopen_as(const char *pathname, int flags, int fd) FAST_FUNC;
 int xopen_nonblocking(const char *pathname) FAST_FUNC;
 int xopen_as_uid_gid(const char *pathname, int flags, uid_t u, gid_t g) FAST_FUNC;
 int open_or_warn_stdin(const char *pathname) FAST_FUNC;
diff --git a/libbb/xfuncs_printf.c b/libbb/xfuncs_printf.c
index f0399ca45..255e80190 100644
--- a/libbb/xfuncs_printf.c
+++ b/libbb/xfuncs_printf.c
@@ -160,6 +160,12 @@ int FAST_FUNC xopen(const char *pathname, int flags)
 	return xopen3(pathname, flags, 0666);
 }
 
+// Die if we can't open a file as a given fd.
+void FAST_FUNC xopen_as(const char *pathname, int flags, int fd)
+{
+	return xmove_fd(xopen(pathname, flags), fd);
+}
+
 // Warn if we can't open a file and return a fd.
 int FAST_FUNC open3_or_warn(const char *pathname, int flags, int mode)
 {
-- 
2.29.2



More information about the busybox mailing list