1 #include "stdio_impl.h"
2 #include <wchar.h>
3 #include <errno.h>
4 #include <limits.h>
5 #include <string.h>
6 #include <stdlib.h>
7 #include <unsupported_api.h>
8 #include "libc.h"
9
10 struct cookie {
11 wchar_t **bufp;
12 size_t *sizep;
13 size_t pos;
14 wchar_t *buf;
15 size_t len;
16 size_t space;
17 mbstate_t mbs;
18 };
19
20 struct wms_FILE {
21 FILE f;
22 struct cookie c;
23 unsigned char buf[1];
24 };
25
wms_seek(FILE * f,off_t off,int whence)26 static off_t wms_seek(FILE *f, off_t off, int whence)
27 {
28 ssize_t base;
29 struct cookie *c = f->cookie;
30 if (whence>2U) {
31 fail:
32 errno = EINVAL;
33 return -1;
34 }
35 base = (size_t [3]){0, c->pos, c->len}[whence];
36 if (off < -base || off > SSIZE_MAX/4-base) goto fail;
37 memset(&c->mbs, 0, sizeof c->mbs);
38 return c->pos = base+off;
39 }
40
wms_write(FILE * f,const unsigned char * buf,size_t len)41 static size_t wms_write(FILE *f, const unsigned char *buf, size_t len)
42 {
43 struct cookie *c = f->cookie;
44 size_t len2;
45 wchar_t *newbuf;
46 if (len + c->pos >= c->space) {
47 len2 = 2*c->space+1 | c->pos+len+1;
48 if (len2 > SSIZE_MAX/4) return 0;
49 newbuf = realloc(c->buf, len2*4);
50 if (!newbuf) return 0;
51 *c->bufp = c->buf = newbuf;
52 memset(c->buf + c->space, 0, 4*(len2 - c->space));
53 c->space = len2;
54 }
55
56 len2 = mbsnrtowcs(c->buf+c->pos, (void *)&buf, len, c->space-c->pos, &c->mbs);
57 if (len2 == -1) return 0;
58 c->pos += len2;
59 if (c->pos >= c->len) c->len = c->pos;
60 *c->sizep = c->pos;
61 return len;
62 }
63
wms_close(FILE * f)64 static int wms_close(FILE *f)
65 {
66 return 0;
67 }
68
open_wmemstream(wchar_t ** bufp,size_t * sizep)69 FILE *open_wmemstream(wchar_t **bufp, size_t *sizep)
70 {
71 struct wms_FILE *f;
72 wchar_t *buf;
73
74 unsupported_api(__FUNCTION__);
75 if (!(f=malloc(sizeof *f))) return 0;
76 if (!(buf=malloc(sizeof *buf))) {
77 free(f);
78 return 0;
79 }
80 memset(&f->f, 0, sizeof f->f);
81 memset(&f->c, 0, sizeof f->c);
82 f->f.cookie = &f->c;
83
84 f->c.bufp = bufp;
85 f->c.sizep = sizep;
86 f->c.pos = f->c.len = f->c.space = *sizep = 0;
87 f->c.buf = *bufp = buf;
88 *buf = 0;
89
90 f->f.flags = F_NORD;
91 f->f.fd = -1;
92 f->f.buf = f->buf;
93 f->f.buf_size = 0;
94 f->f.lbf = EOF;
95 f->f.write = wms_write;
96 f->f.seek = wms_seek;
97 f->f.close = wms_close;
98
99 if (!libc.threaded) f->f.lock = -1;
100
101 fwide(&f->f, 1);
102
103 return __ofl_add(&f->f);
104 }
105