1 /*
2  * *****************************************************************************
3  *
4  * SPDX-License-Identifier: BSD-2-Clause
5  *
6  * Copyright (c) 2018-2021 Gavin D. Howard and contributors.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions are met:
10  *
11  * * Redistributions of source code must retain the above copyright notice, this
12  *   list of conditions and the following disclaimer.
13  *
14  * * Redistributions in binary form must reproduce the above copyright notice,
15  *   this list of conditions and the following disclaimer in the documentation
16  *   and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
22  * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28  * POSSIBILITY OF SUCH DAMAGE.
29  *
30  * *****************************************************************************
31  *
32  * Code for implementing buffered I/O on my own terms.
33  *
34  */
35 
36 #include <assert.h>
37 #include <errno.h>
38 #include <string.h>
39 
40 #ifndef _WIN32
41 #include <unistd.h>
42 #endif // _WIN32
43 
44 #include <file.h>
45 #include <vm.h>
46 
bc_file_ultoa(unsigned long long val,char buf[BC_FILE_ULL_LENGTH])47 static void bc_file_ultoa(unsigned long long val, char buf[BC_FILE_ULL_LENGTH])
48 {
49 	char buf2[BC_FILE_ULL_LENGTH];
50 	size_t i, len;
51 
52 	memset(buf2, 0, BC_FILE_ULL_LENGTH);
53 
54 	// The i = 1 is to ensure that there is a null byte at the end.
55 	for (i = 1; val; ++i) {
56 		unsigned long long mod = val % 10;
57 		buf2[i] = ((char) mod) + '0';
58 		val /= 10;
59 	}
60 
61 	len = i;
62 
63 	for (i = 0; i < len; ++i) buf[i] = buf2[len - i - 1];
64 }
65 
bc_file_output(int fd,const char * buf,size_t n)66 static BcStatus bc_file_output(int fd, const char *buf, size_t n) {
67 
68 	size_t bytes = 0;
69 	sig_atomic_t lock;
70 
71 	BC_SIG_TRYLOCK(lock);
72 
73 	while (bytes < n) {
74 
75 		ssize_t written = write(fd, buf + bytes, n - bytes);
76 
77 		if (BC_ERR(written == -1))
78 			return errno == EPIPE ? BC_STATUS_EOF : BC_STATUS_ERROR_FATAL;
79 
80 		bytes += (size_t) written;
81 	}
82 
83 	BC_SIG_TRYUNLOCK(lock);
84 
85 	return BC_STATUS_SUCCESS;
86 }
87 
bc_file_flushErr(BcFile * restrict f,BcFlushType type)88 BcStatus bc_file_flushErr(BcFile *restrict f, BcFlushType type)
89 {
90 	BcStatus s;
91 
92 	if (f->len) {
93 
94 #if BC_ENABLE_HISTORY
95 		if (BC_TTY) {
96 			if (f->buf[f->len - 1] != '\n' &&
97 			    (type == BC_FLUSH_SAVE_EXTRAS_CLEAR ||
98 			     type == BC_FLUSH_SAVE_EXTRAS_NO_CLEAR))
99 			{
100 				size_t i;
101 
102 				for (i = f->len - 2; i < f->len && f->buf[i] != '\n'; --i);
103 
104 				i += 1;
105 
106 				bc_vec_string(&vm.history.extras, f->len - i, f->buf + i);
107 			}
108 			else if (type >= BC_FLUSH_NO_EXTRAS_CLEAR) {
109 				bc_vec_popAll(&vm.history.extras);
110 			}
111 		}
112 #endif // BC_ENABLE_HISTORY
113 
114 		s = bc_file_output(f->fd, f->buf, f->len);
115 		f->len = 0;
116 	}
117 	else s = BC_STATUS_SUCCESS;
118 
119 	return s;
120 }
121 
bc_file_flush(BcFile * restrict f,BcFlushType type)122 void bc_file_flush(BcFile *restrict f, BcFlushType type) {
123 
124 	BcStatus s = bc_file_flushErr(f, type);
125 
126 	if (BC_ERR(s)) {
127 
128 		if (s == BC_STATUS_EOF) {
129 			vm.status = (sig_atomic_t) s;
130 			BC_VM_JMP;
131 		}
132 		else bc_vm_fatalError(BC_ERR_FATAL_IO_ERR);
133 	}
134 }
135 
bc_file_write(BcFile * restrict f,BcFlushType type,const char * buf,size_t n)136 void bc_file_write(BcFile *restrict f, BcFlushType type,
137                    const char *buf, size_t n)
138 {
139 	if (n > f->cap - f->len) {
140 		bc_file_flush(f, type);
141 		assert(!f->len);
142 	}
143 
144 	if (BC_UNLIKELY(n > f->cap - f->len)) bc_file_output(f->fd, buf, n);
145 	else {
146 		memcpy(f->buf + f->len, buf, n);
147 		f->len += n;
148 	}
149 }
150 
bc_file_printf(BcFile * restrict f,const char * fmt,...)151 void bc_file_printf(BcFile *restrict f, const char *fmt, ...)
152 {
153 	va_list args;
154 
155 	va_start(args, fmt);
156 	bc_file_vprintf(f, fmt, args);
157 	va_end(args);
158 }
159 
bc_file_vprintf(BcFile * restrict f,const char * fmt,va_list args)160 void bc_file_vprintf(BcFile *restrict f, const char *fmt, va_list args) {
161 
162 	char *percent;
163 	const char *ptr = fmt;
164 	char buf[BC_FILE_ULL_LENGTH];
165 
166 	while ((percent = strchr(ptr, '%')) != NULL) {
167 
168 		char c;
169 
170 		if (percent != ptr) {
171 			size_t len = (size_t) (percent - ptr);
172 			bc_file_write(f, bc_flush_none, ptr, len);
173 		}
174 
175 		c = percent[1];
176 
177 		if (c == 'c') {
178 
179 			uchar uc = (uchar) va_arg(args, int);
180 
181 			bc_file_putchar(f, bc_flush_none, uc);
182 		}
183 		else if (c == 's') {
184 
185 			char *s = va_arg(args, char*);
186 
187 			bc_file_puts(f, bc_flush_none, s);
188 		}
189 #if BC_DEBUG_CODE
190 		else if (c == 'd') {
191 
192 			int d = va_arg(args, int);
193 
194 			if (d < 0) {
195 				bc_file_putchar(f, bc_flush_none, '-');
196 				d = -d;
197 			}
198 
199 			if (!d) bc_file_putchar(f, bc_flush_none, '0');
200 			else {
201 				bc_file_ultoa((unsigned long long) d, buf);
202 				bc_file_puts(f, bc_flush_none, buf);
203 			}
204 		}
205 #endif // BC_DEBUG_CODE
206 		else {
207 
208 			unsigned long long ull;
209 
210 			assert((c == 'l' || c == 'z') && percent[2] == 'u');
211 
212 			if (c == 'z') ull = (unsigned long long) va_arg(args, size_t);
213 			else ull = (unsigned long long) va_arg(args, unsigned long);
214 
215 			if (!ull) bc_file_putchar(f, bc_flush_none, '0');
216 			else {
217 				bc_file_ultoa(ull, buf);
218 				bc_file_puts(f, bc_flush_none, buf);
219 			}
220 		}
221 
222 		ptr = percent + 2 + (c == 'l' || c == 'z');
223 	}
224 
225 	if (ptr[0]) bc_file_puts(f, bc_flush_none, ptr);
226 }
227 
bc_file_puts(BcFile * restrict f,BcFlushType type,const char * str)228 void bc_file_puts(BcFile *restrict f, BcFlushType type, const char *str) {
229 	bc_file_write(f, type, str, strlen(str));
230 }
231 
bc_file_putchar(BcFile * restrict f,BcFlushType type,uchar c)232 void bc_file_putchar(BcFile *restrict f, BcFlushType type, uchar c) {
233 	if (f->len == f->cap) bc_file_flush(f, type);
234 	assert(f->len < f->cap);
235 	f->buf[f->len] = (char) c;
236 	f->len += 1;
237 }
238 
bc_file_init(BcFile * f,int fd,char * buf,size_t cap)239 void bc_file_init(BcFile *f, int fd, char *buf, size_t cap) {
240 	BC_SIG_ASSERT_LOCKED;
241 	f->fd = fd;
242 	f->buf = buf;
243 	f->len = 0;
244 	f->cap = cap;
245 }
246 
bc_file_free(BcFile * f)247 void bc_file_free(BcFile *f) {
248 	BC_SIG_ASSERT_LOCKED;
249 	bc_file_flush(f, bc_flush_none);
250 }
251