| 1 |
// Copyright (c) Meta Platforms, Inc. and affiliates. |
| 2 |
// SPDX-License-Identifier: LGPL-2.1-or-later |
| 3 |
|
| 4 |
#include <errno.h> |
| 5 |
#include <limits.h> |
| 6 |
#include <unistd.h> |
| 7 |
|
| 8 |
#include "cleanup.h" |
| 9 |
#include "io.h" |
| 10 |
#include "util.h" |
| 11 |
|
| 12 |
ssize_t read_all(int fd, void *buf, size_t count) |
| 13 |
{ |
| 14 |
if (count > SSIZE_MAX) { |
| 15 |
errno = EINVAL; |
| 16 |
return -1; |
| 17 |
} |
| 18 |
size_t n = 0; |
| 19 |
while (n < count) { |
| 20 |
ssize_t r = read(fd, (char *)buf + n, count - n); |
| 21 |
if (r < 0) { |
| 22 |
if (errno == EINTR) |
| 23 |
continue; |
| 24 |
return r; |
| 25 |
} else if (r == 0) { |
| 26 |
break; |
| 27 |
} |
| 28 |
n += r; |
| 29 |
} |
| 30 |
return n; |
| 31 |
} |
| 32 |
|
| 33 |
int write_all(int fd, const void *buf, size_t count) |
| 34 |
{ |
| 35 |
size_t n = 0; |
| 36 |
while (n < count) { |
| 37 |
ssize_t r = write(fd, (const char *)buf + n, count - n); |
| 38 |
if (r < 0) { |
| 39 |
if (errno == EINTR) |
| 40 |
continue; |
| 41 |
return -1; |
| 42 |
} |
| 43 |
n += r; |
| 44 |
} |
| 45 |
return 0; |
| 46 |
} |
| 47 |
|
| 48 |
ssize_t pread_all(int fd, void *buf, size_t count, off_t offset) |
| 49 |
{ |
| 50 |
if (count > SSIZE_MAX) { |
| 51 |
errno = EINVAL; |
| 52 |
return -1; |
| 53 |
} |
| 54 |
size_t n = 0; |
| 55 |
while (n < count) { |
| 56 |
ssize_t r = pread(fd, (char *)buf + n, count - n, offset + n); |
| 57 |
if (r < 0) { |
| 58 |
if (errno == EINTR) |
| 59 |
continue; |
| 60 |
return r; |
| 61 |
} else if (r == 0) { |
| 62 |
break; |
| 63 |
} |
| 64 |
n += r; |
| 65 |
} |
| 66 |
return n; |
| 67 |
} |
| 68 |
|
| 69 |
char *fd_canonical_path(int fd, const char *path) |
| 70 |
{ |
| 71 |
#define FORMAT "/proc/self/fd/%d" |
| 72 |
char fd_path[sizeof(FORMAT) |
| 73 |
- (sizeof("%d") - 1) |
| 74 |
+ max_decimal_length(int)]; |
| 75 |
snprintf(fd_path, sizeof(fd_path), FORMAT, fd); |
| 76 |
#undef FORMAT |
| 77 |
|
| 78 |
size_t buf_size = PATH_MAX; |
| 79 |
_cleanup_free_ char *buf = malloc(buf_size); |
| 80 |
if (!buf) |
| 81 |
return NULL; |
| 82 |
|
| 83 |
for (;;) { |
| 84 |
ssize_t r = readlink(fd_path, buf, buf_size); |
| 85 |
if (r < 0) { |
| 86 |
if (!path) |
| 87 |
return strdup(fd_path); |
| 88 |
char *real = realpath(path, NULL); |
| 89 |
if (real) |
| 90 |
return real; |
| 91 |
return strdup(path); |
| 92 |
} |
| 93 |
|
| 94 |
if (r < buf_size) { |
| 95 |
buf[r] = '\0'; |
| 96 |
// The path is likely to be much smaller than PATH_MAX, |
| 97 |
// so try shrinking it. |
| 98 |
if (r + 1 < buf_size) { |
| 99 |
char *tmp = realloc(buf, r + 1); |
| 100 |
if (tmp) |
| 101 |
buf = tmp; |
| 102 |
} |
| 103 |
return_ptr(buf); |
| 104 |
} |
| 105 |
|
| 106 |
if (__builtin_mul_overflow(buf_size, 2U, &buf_size)) |
| 107 |
return NULL; |
| 108 |
free(buf); |
| 109 |
buf = malloc(buf_size); |
| 110 |
if (!buf) |
| 111 |
return NULL; |
| 112 |
} |
| 113 |
} |