fix getdelim to set the error indicator on all failures
[oweals/musl.git] / src / stdio / getdelim.c
1 #include "stdio_impl.h"
2 #include <string.h>
3 #include <inttypes.h>
4 #include <errno.h>
5
6 #define MIN(a,b) ((a)<(b) ? (a) : (b))
7
8 ssize_t getdelim(char **restrict s, size_t *restrict n, int delim, FILE *restrict f)
9 {
10         char *tmp;
11         unsigned char *z;
12         size_t k;
13         size_t i=0;
14         int c;
15
16         FLOCK(f);
17
18         if (!n || !s) {
19                 f->flags |= F_ERR;
20                 FUNLOCK(f);
21                 errno = EINVAL;
22                 return -1;
23         }
24
25         if (!*s) *n=0;
26
27         for (;;) {
28                 z = memchr(f->rpos, delim, f->rend - f->rpos);
29                 k = z ? z - f->rpos + 1 : f->rend - f->rpos;
30                 if (i+k >= *n) {
31                         if (k >= SIZE_MAX/2-i) goto oom;
32                         *n = i+k+2;
33                         if (*n < SIZE_MAX/4) *n *= 2;
34                         tmp = realloc(*s, *n);
35                         if (!tmp) {
36                                 *n = i+k+2;
37                                 tmp = realloc(*s, *n);
38                                 if (!tmp) goto oom;
39                         }
40                         *s = tmp;
41                 }
42                 memcpy(*s+i, f->rpos, k);
43                 f->rpos += k;
44                 i += k;
45                 if (z) break;
46                 if ((c = getc_unlocked(f)) == EOF) {
47                         if (!i || !feof(f)) {
48                                 FUNLOCK(f);
49                                 return -1;
50                         }
51                         break;
52                 }
53                 if (((*s)[i++] = c) == delim) break;
54         }
55         (*s)[i] = 0;
56
57         FUNLOCK(f);
58
59         return i;
60 oom:
61         f->flags |= F_ERR;
62         FUNLOCK(f);
63         errno = ENOMEM;
64         return -1;
65 }
66
67 weak_alias(getdelim, __getdelim);