| Line | Branch | Exec | Source |
|---|---|---|---|
| 1 | #include <errno.h> | ||
| 2 | #include <limits.h> | ||
| 3 | #include <stdlib.h> | ||
| 4 | #include <sys/stat.h> | ||
| 5 | #include "readfile.h" | ||
| 6 | #include "xreadwrite.h" | ||
| 7 | |||
| 8 | // Read the contents of a file into memory, if smaller than `size_limit` | ||
| 9 | 204 | ssize_t read_file(const char *filename, char **bufp, size_t size_limit) | |
| 10 | { | ||
| 11 | 204 | int fd = xopen(filename, O_RDONLY | O_CLOEXEC, 0); | |
| 12 |
2/2✓ Branch 3 → 4 taken 64 times.
✓ Branch 3 → 5 taken 140 times.
|
204 | if (fd == -1) { |
| 13 | 64 | goto error_noclose; | |
| 14 | } | ||
| 15 | |||
| 16 | 140 | struct stat st; | |
| 17 |
1/2✗ Branch 6 → 7 not taken.
✓ Branch 6 → 8 taken 140 times.
|
140 | if (unlikely(fstat(fd, &st) == -1)) { |
| 18 | ✗ | goto error; | |
| 19 | } | ||
| 20 |
2/2✓ Branch 8 → 9 taken 1 time.
✓ Branch 8 → 10 taken 139 times.
|
140 | if (unlikely(S_ISDIR(st.st_mode))) { |
| 21 | 1 | errno = EISDIR; | |
| 22 | 1 | goto error; | |
| 23 | } | ||
| 24 | |||
| 25 | 139 | off_t size = st.st_size; | |
| 26 |
2/2✓ Branch 10 → 11 taken 69 times.
✓ Branch 10 → 12 taken 70 times.
|
139 | size_limit = size_limit ? MIN(size_limit, SSIZE_MAX) : SSIZE_MAX; |
| 27 |
2/2✓ Branch 12 → 13 taken 1 time.
✓ Branch 12 → 14 taken 138 times.
|
139 | if (unlikely(size > size_limit)) { |
| 28 | 1 | errno = EFBIG; | |
| 29 | 1 | goto error; | |
| 30 | } | ||
| 31 | |||
| 32 | 138 | char *buf = malloc(size + 1); | |
| 33 |
1/2✗ Branch 14 → 15 not taken.
✓ Branch 14 → 16 taken 138 times.
|
138 | if (unlikely(!buf)) { |
| 34 | ✗ | goto error; | |
| 35 | } | ||
| 36 | |||
| 37 | 138 | ssize_t r = xread_all(fd, buf, size); | |
| 38 |
1/2✗ Branch 17 → 18 not taken.
✓ Branch 17 → 19 taken 138 times.
|
138 | if (unlikely(r < 0)) { |
| 39 | ✗ | free(buf); | |
| 40 | ✗ | goto error; | |
| 41 | } | ||
| 42 | |||
| 43 | 138 | buf[r] = '\0'; | |
| 44 | 138 | *bufp = buf; | |
| 45 | 138 | xclose(fd); | |
| 46 | 138 | return r; | |
| 47 | |||
| 48 | 2 | error: | |
| 49 | 2 | xclose(fd); | |
| 50 | 66 | error_noclose: | |
| 51 | 66 | *bufp = NULL; | |
| 52 | 66 | return -1; | |
| 53 | } | ||
| 54 |