| 1 | /* |
| 2 | * SPDX-License-Identifier: LGPL-2.1-only |
| 3 | * |
| 4 | * Copyright (C) 2016 Mathieu Desnoyers <mathieu.desnoyers@efficios.com> |
| 5 | */ |
| 6 | |
| 7 | #define _LGPL_SOURCE |
| 8 | #include <limits.h> |
| 9 | #include <stdio.h> |
| 10 | #include <sys/types.h> |
| 11 | #include <unistd.h> |
| 12 | #include <ust-fd.h> |
| 13 | #include <dlfcn.h> |
| 14 | |
| 15 | #include <ust-helper.h> |
| 16 | |
| 17 | static int (*__lttng_ust_fd_plibc_close)(int fd); |
| 18 | static int (*__lttng_ust_fd_plibc_fclose)(FILE *stream); |
| 19 | |
| 20 | static |
| 21 | int _lttng_ust_fd_libc_close(int fd) |
| 22 | { |
| 23 | if (!__lttng_ust_fd_plibc_close) { |
| 24 | __lttng_ust_fd_plibc_close = dlsym(RTLD_NEXT, "close"); |
| 25 | if (!__lttng_ust_fd_plibc_close) { |
| 26 | fprintf(stderr, "%s\n", dlerror()); |
| 27 | return -1; |
| 28 | } |
| 29 | } |
| 30 | return lttng_ust_safe_close_fd(fd, __lttng_ust_fd_plibc_close); |
| 31 | } |
| 32 | |
| 33 | static |
| 34 | int _lttng_ust_fd_libc_fclose(FILE *stream) |
| 35 | { |
| 36 | if (!__lttng_ust_fd_plibc_fclose) { |
| 37 | __lttng_ust_fd_plibc_fclose = dlsym(RTLD_NEXT, "fclose"); |
| 38 | if (!__lttng_ust_fd_plibc_fclose) { |
| 39 | fprintf(stderr, "%s\n", dlerror()); |
| 40 | return -1; |
| 41 | } |
| 42 | } |
| 43 | return lttng_ust_safe_fclose_stream(stream, |
| 44 | __lttng_ust_fd_plibc_fclose); |
| 45 | } |
| 46 | |
| 47 | int close(int fd) |
| 48 | { |
| 49 | return _lttng_ust_fd_libc_close(fd); |
| 50 | } |
| 51 | |
| 52 | /* |
| 53 | * Note: fcloseall() is not an issue because it fcloses only the |
| 54 | * streams it knows about, which differs from the problems caused by |
| 55 | * gnulib close_stdout(), which does an explicit fclose(stdout). |
| 56 | */ |
| 57 | int fclose(FILE *stream) |
| 58 | { |
| 59 | return _lttng_ust_fd_libc_fclose(stream); |
| 60 | } |
| 61 | |
| 62 | #if defined(__sun__) || defined(__FreeBSD__) |
| 63 | /* Solaris and FreeBSD. */ |
| 64 | void closefrom(int lowfd) |
| 65 | { |
| 66 | (void) lttng_ust_safe_closefrom_fd(lowfd, __lttng_ust_fd_plibc_close); |
| 67 | } |
| 68 | #elif defined(__NetBSD__) || defined(__OpenBSD__) |
| 69 | /* NetBSD and OpenBSD. */ |
| 70 | int closefrom(int lowfd) |
| 71 | { |
| 72 | return lttng_ust_safe_closefrom_fd(lowfd, __lttng_ust_fd_plibc_close); |
| 73 | } |
| 74 | #else |
| 75 | /* As far as we know, this OS does not implement closefrom. */ |
| 76 | #endif |