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 | 203 | ssize_t read_file(const char *filename, char **bufp, size_t size_limit) | |
10 | { | ||
11 | 203 | int fd = xopen(filename, O_RDONLY | O_CLOEXEC, 0); | |
12 |
2/2✓ Branch 0 (3→4) taken 64 times.
✓ Branch 1 (3→5) taken 139 times.
|
203 | if (fd == -1) { |
13 | 64 | goto error_noclose; | |
14 | } | ||
15 | |||
16 | 139 | int saved_errno; | |
17 | 139 | struct stat st; | |
18 |
1/2✗ Branch 0 (6→7) not taken.
✓ Branch 1 (6→8) taken 139 times.
|
139 | if (unlikely(fstat(fd, &st) == -1)) { |
19 | ✗ | goto error; | |
20 | } | ||
21 |
2/2✓ Branch 0 (8→9) taken 1 times.
✓ Branch 1 (8→10) taken 138 times.
|
139 | if (unlikely(S_ISDIR(st.st_mode))) { |
22 | 1 | errno = EISDIR; | |
23 | 1 | goto error; | |
24 | } | ||
25 | |||
26 | 138 | off_t size = st.st_size; | |
27 |
2/2✓ Branch 0 (10→11) taken 68 times.
✓ Branch 1 (10→12) taken 70 times.
|
138 | size_limit = size_limit ? MIN(size_limit, SSIZE_MAX) : SSIZE_MAX; |
28 |
2/2✓ Branch 0 (12→13) taken 1 times.
✓ Branch 1 (12→14) taken 137 times.
|
138 | if (unlikely(size > size_limit)) { |
29 | 1 | errno = EFBIG; | |
30 | 1 | goto error; | |
31 | } | ||
32 | |||
33 | 137 | char *buf = malloc(size + 1); | |
34 |
1/2✗ Branch 0 (14→15) not taken.
✓ Branch 1 (14→16) taken 137 times.
|
137 | if (unlikely(!buf)) { |
35 | ✗ | goto error; | |
36 | } | ||
37 | |||
38 | 137 | ssize_t r = xread_all(fd, buf, size); | |
39 |
1/2✗ Branch 0 (17→18) not taken.
✓ Branch 1 (17→19) taken 137 times.
|
137 | if (unlikely(r < 0)) { |
40 | ✗ | free(buf); | |
41 | ✗ | goto error; | |
42 | } | ||
43 | |||
44 | 137 | buf[r] = '\0'; | |
45 | 137 | *bufp = buf; | |
46 | 137 | xclose(fd); | |
47 | 137 | return r; | |
48 | |||
49 | 2 | error: | |
50 | 2 | saved_errno = errno; | |
51 | 2 | xclose(fd); | |
52 | 2 | errno = saved_errno; | |
53 | 66 | error_noclose: | |
54 | 66 | *bufp = NULL; | |
55 | 66 | return -1; | |
56 | } | ||
57 |