add stuff for error-handling
[libjh.git] / io.c
1 // Copyright (2013) Jann Horn <jann@thejh.net>
2 // This code is licensed under the AGPLv3.
3
4 HEADER #include <sys/types.h>
5 #include <unistd.h>
6 #include <errno.h>
7 #include <stdlib.h>
8 #include <stdbool.h>
9 #include <sys/stat.h>
10 #include <fcntl.h>
11 #include <string.h>
12 #include <assert.h>
13 #include <sys/mman.h>
14
15 // Wrapper for `read` that retries on partial reads.
16 // If last_res is non-NULL, it will be filled with the
17 // result of the last read() call (but all positive numbers
18 // become 1). In other words:
19 //  - -1: error
20 //  - 0: stream ended
21 //  - 1: no problems occured
22 PUBLIC_FN ssize_t read_nointr(int fd, void *buf, size_t count, int *last_res) {
23   errno = 0;
24   size_t done = 0;
25   while (done < count) {
26     ssize_t part_res = read(fd, buf+done, count-done);
27     if (part_res == -1 && errno == EINTR) continue;
28     if (part_res <= 0) {
29       if (last_res) *last_res = part_res;
30       if (done) return done;
31       return part_res;
32     }
33     done += part_res;
34   }
35   if (last_res) *last_res = 1;
36   return done;
37 }
38
39 // Wrapper for `write` that retries on partial writes.
40 // If last_res is non-NULL, it will be filled with the
41 // result of the last write() call (but all positive numbers
42 // become 1). In other words:
43 //  - -1: error
44 //  - 0: stream ended
45 //  - 1: no problems occured
46 PUBLIC_FN ssize_t write_nointr(int fd, void *buf, size_t count, int *last_res) {
47   errno = 0;
48   size_t done = 0;
49   while (done < count) {
50     ssize_t part_res = write(fd, buf+done, count-done);
51     if (part_res == -1 && errno == EINTR) continue;
52     if (part_res <= 0) {
53       if (last_res) *last_res = part_res;
54       if (done) return done;
55       return part_res;
56     }
57     done += part_res;
58   }
59   if (last_res) *last_res = 1;
60   return done;
61 }
62
63 // Read all data from the given file descriptor. Tries fstat()+read()
64 // first, but if fstat() doesn't work, falls back to multiple read()s.
65 // Specify JH_NO_STAT to prevent the fstat() call.
66 // The return value is a malloc'd buffer.
67 // The buffer will be null-terminated, so you can read text files with
68 // this and can specify len_out as NULL.
69 PUBLIC_CONST JH_SLURP_NO_STAT 1
70 PUBLIC_CONST JH_SLURP_REALLOC 2 /* realloc result block if it saves RAM */
71 PUBLIC_CONST JH_SLURP_8BYTE_PAD 4 /* pad buffer with eight nullbytes, not one */
72 PUBLIC_CONST JH_SLURP_FIXSIZE 8 /* len_out is actually input and specifies
73 HEADER                             the expected length. if there is more data,
74 HEADER                             that might be ignored silently. */
75 PUBLIC_FN void *slurp_fd(int fd, size_t *len_out, int flags) {
76   int errno_;
77   
78   // Let's just guess that the file is 1023 bytes. Will become 1024 with
79   // the nullbyte.
80   size_t size_guess = 1023;
81   bool trusted_guess = false; /* can we rely on the guess? */
82   
83   if (flags&JH_SLURP_FIXSIZE) {
84     size_guess = *len_out;
85     trusted_guess = true;
86     // if we want a fixed size, of course we don't want to stat
87     flags |= JH_SLURP_NO_STAT;
88   }
89   
90   int padlen = (flags&JH_SLURP_8BYTE_PAD)?8:1;
91   
92   // If we can determine the exact size, we don't have to guess. So try
93   // to determine the exact size.
94   if (!(flags&JH_SLURP_NO_STAT)) {
95     struct stat st;
96     if (fstat(fd, &st) == 0) {
97       if (st.st_size > 0) {
98         size_guess = st.st_size;
99         trusted_guess = true;
100       }
101     }
102   }
103   
104   char *buf = NULL;
105   int done = 0;
106   
107   while (1) {
108     buf = realloc(buf, size_guess+padlen);
109     if (buf == NULL) return NULL;
110     int last_res;
111     ssize_t read_res = read_nointr(fd, buf+done, size_guess-done, &last_res);
112     if (last_res == -1) { errno_=errno; free(buf); errno=errno_; return NULL; }
113     done += read_res;
114     if (last_res == 0 || trusted_guess) {
115       // out
116       if (padlen == 1) {
117         buf[done] = '\0';
118       } else {
119         *(uint64_t*)(buf+done) = 0;
120       }
121       if (done != size_guess && (flags&JH_SLURP_REALLOC)) {
122         // Well, it'd be weird if shrinking could fail... but meh, I can't find
123         // an explicit statement about this being disallowed, so try staying on
124         // the safe side.
125         char *buf_ = realloc(buf, done+padlen);
126         if (buf_) buf = buf_;
127       }
128       if (done != size_guess && (flags&JH_SLURP_FIXSIZE)) {
129         free(buf);
130         // not the most correct error message ever, but whatever.
131         errno = EFBIG;
132         return NULL;
133       }
134       if (len_out) *len_out = done;
135       return buf;
136     }
137     size_guess<<=1; // try two times the buffer size
138   }
139 }
140
141 PUBLIC_FN void *slurp_file(char *path, size_t *len_out, int flags) {
142   int fd = open(path, O_RDONLY|O_CLOEXEC);
143   if (fd == -1) return NULL;
144   char *res = slurp_fd(fd, len_out, flags);
145   int errno_ = errno;
146   close(fd);
147   errno = errno_;
148   return res;
149 }
150
151 // Write data into a file. len can be -1; that means that
152 // the real length is strlen(buf).
153 PUBLIC_FN int write_file(char *path, void *buf, ssize_t len, int open_flags) {
154   if (len == -1) len = strlen(buf);
155   
156   int fd = open(path, open_flags|O_CLOEXEC|O_WRONLY, 0777);
157   if (fd == -1) return 1;
158   ssize_t write_res = write_nointr(fd, buf, len, NULL);
159   int write_errno = errno;
160   int close_res = close(fd);
161   if (write_res != len) {
162     errno = write_errno;
163     return 1;
164   }
165   if (close_res) return 1;
166   return 0;
167 }
168
169 PUBLIC_FN void *mmap_file(void *addr, size_t length, int prot, int flags, char *path, off_t offset) {
170   assert((flags&MAP_ANONYMOUS) == 0);
171   assert(prot&(PROT_EXEC|PROT_READ|PROT_WRITE));
172   int open_flags = O_CLOEXEC;
173   if ((prot & (PROT_READ|PROT_EXEC)) && !(prot&PROT_WRITE)) open_flags |= O_RDONLY;
174   else if ((prot & (PROT_READ|PROT_EXEC))) open_flags |= O_RDWR;
175   else open_flags |= O_WRONLY;
176   int fd = open(path, open_flags);
177   if (fd == -1) return NULL;
178   void *r = mmap(addr, length, prot, flags, fd, offset);
179   int errno_ = errno;
180   close(fd);
181   errno = errno_;
182   return (r==MAP_FAILED) ? NULL : r;
183 }