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