From: Yu Watanabe Date: Fri, 7 Apr 2023 02:39:20 +0000 (+0900) Subject: fileio: use take_fdopen() and friends X-Git-Tag: v254-rc1~773^2~1 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=0f585d4116a815430924b2a6b53a57d4ba87a8fa;p=thirdparty%2Fsystemd.git fileio: use take_fdopen() and friends --- diff --git a/src/basic/fileio.c b/src/basic/fileio.c index 340f9b48607..0622d527381 100644 --- a/src/basic/fileio.c +++ b/src/basic/fileio.c @@ -267,7 +267,8 @@ int write_string_file_ts_at( const struct timespec *ts) { _cleanup_fclose_ FILE *f = NULL; - int q, r, fd; + _cleanup_close_ int fd = -EBADF; + int q, r; assert(fn); assert(line); @@ -304,11 +305,9 @@ int write_string_file_ts_at( goto fail; } - r = fdopen_unlocked(fd, "w", &f); - if (r < 0) { - safe_close(fd); + r = take_fdopen_unlocked(&fd, "w", &f); + if (r < 0) goto fail; - } if (flags & WRITE_STRING_FILE_DISABLE_BUFFER) setvbuf(f, NULL, _IONBF, 0); @@ -808,11 +807,9 @@ int read_full_file_full( if (shutdown(sk, SHUT_WR) < 0) return -errno; - f = fdopen(sk, "r"); + f = take_fdopen(&sk, "r"); if (!f) return -errno; - - TAKE_FD(sk); } (void) __fsetlocking(f, FSETLOCKING_BYCALLER); @@ -922,8 +919,7 @@ int get_proc_field(const char *filename, const char *pattern, const char *termin } DIR *xopendirat(int fd, const char *name, int flags) { - int nfd; - DIR *d; + _cleanup_close_ int nfd = -EBADF; assert(!(flags & O_CREAT)); @@ -934,13 +930,7 @@ DIR *xopendirat(int fd, const char *name, int flags) { if (nfd < 0) return NULL; - d = fdopendir(nfd); - if (!d) { - safe_close(nfd); - return NULL; - } - - return d; + return take_fdopendir(&nfd); } int fopen_mode_to_flags(const char *mode) { @@ -994,12 +984,16 @@ int xfopenat(int dir_fd, const char *path, const char *mode, int flags, FILE **r /* A combination of fopen() with openat() */ - if (dir_fd == AT_FDCWD && flags == 0) { + assert(dir_fd >= 0 || dir_fd == AT_FDCWD); + assert(path); + assert(mode); + assert(ret); + + if (dir_fd == AT_FDCWD && flags == 0) f = fopen(path, mode); - if (!f) - return -errno; - } else { - int fd, mode_flags; + else { + _cleanup_close_ int fd = -EBADF; + int mode_flags; mode_flags = fopen_mode_to_flags(mode); if (mode_flags < 0) @@ -1009,12 +1003,10 @@ int xfopenat(int dir_fd, const char *path, const char *mode, int flags, FILE **r if (fd < 0) return -errno; - f = fdopen(fd, mode); - if (!f) { - safe_close(fd); - return -errno; - } + f = take_fdopen(&fd, mode); } + if (!f) + return -errno; *ret = f; return 0; @@ -1040,11 +1032,10 @@ int fdopen_independent(int fd, const char *mode, FILE **ret) { if (copy_fd < 0) return copy_fd; - f = fdopen(copy_fd, mode); + f = take_fdopen(©_fd, mode); if (!f) return -errno; - TAKE_FD(copy_fd); *ret = TAKE_PTR(f); return 0; }