xref: /freebsd/contrib/bc/src/file.c (revision 38a52bd3b5cac3da6f7f6eef3dd050e6aa08ebb3)
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 
47 #if !BC_ENABLE_LINE_LIB
48 
49 /**
50  * Translates an integer into a string.
51  * @param val  The value to translate.
52  * @param buf  The return parameter.
53  */
54 static void
55 bc_file_ultoa(unsigned long long val, char buf[BC_FILE_ULL_LENGTH])
56 {
57 	char buf2[BC_FILE_ULL_LENGTH];
58 	size_t i, len;
59 
60 	// We need to make sure the entire thing is zeroed.
61 	// NOLINTNEXTLINE
62 	memset(buf2, 0, BC_FILE_ULL_LENGTH);
63 
64 	// The i = 1 is to ensure that there is a null byte at the end.
65 	for (i = 1; val; ++i)
66 	{
67 		unsigned long long mod = val % 10;
68 
69 		buf2[i] = ((char) mod) + '0';
70 		val /= 10;
71 	}
72 
73 	len = i;
74 
75 	// Since buf2 is reversed, reverse it into buf.
76 	for (i = 0; i < len; ++i)
77 	{
78 		buf[i] = buf2[len - i - 1];
79 	}
80 }
81 
82 /**
83  * Output to the file directly.
84  * @param fd   The file descriptor.
85  * @param buf  The buffer of data to output.
86  * @param n    The number of bytes to output.
87  * @return     A status indicating error or success. We could have a fatal I/O
88  *             error or EOF.
89  */
90 static BcStatus
91 bc_file_output(int fd, const char* buf, size_t n)
92 {
93 	size_t bytes = 0;
94 	sig_atomic_t lock;
95 
96 	BC_SIG_TRYLOCK(lock);
97 
98 	// While the number of bytes written is less than intended...
99 	while (bytes < n)
100 	{
101 		// Write.
102 		ssize_t written = write(fd, buf + bytes, n - bytes);
103 
104 		// Check for error and return, if any.
105 		if (BC_ERR(written == -1))
106 		{
107 			BC_SIG_TRYUNLOCK(lock);
108 
109 			return errno == EPIPE ? BC_STATUS_EOF : BC_STATUS_ERROR_FATAL;
110 		}
111 
112 		bytes += (size_t) written;
113 	}
114 
115 	BC_SIG_TRYUNLOCK(lock);
116 
117 	return BC_STATUS_SUCCESS;
118 }
119 
120 #endif // !BC_ENABLE_LINE_LIB
121 
122 BcStatus
123 bc_file_flushErr(BcFile* restrict f, BcFlushType type)
124 {
125 	BcStatus s;
126 
127 	BC_SIG_ASSERT_LOCKED;
128 
129 #if BC_ENABLE_LINE_LIB
130 
131 	// Just flush and propagate the error.
132 	if (fflush(f->f) == EOF) s = BC_STATUS_ERROR_FATAL;
133 	else s = BC_STATUS_SUCCESS;
134 
135 #else // BC_ENABLE_LINE_LIB
136 
137 	// If there is stuff to output...
138 	if (f->len)
139 	{
140 #if BC_ENABLE_HISTORY
141 
142 		// If history is enabled...
143 		if (BC_TTY)
144 		{
145 			// If we have been told to save the extras, and there *are*
146 			// extras...
147 			if (f->buf[f->len - 1] != '\n' &&
148 			    (type == BC_FLUSH_SAVE_EXTRAS_CLEAR ||
149 			     type == BC_FLUSH_SAVE_EXTRAS_NO_CLEAR))
150 			{
151 				size_t i;
152 
153 				// Look for the last newline.
154 				for (i = f->len - 2; i < f->len && f->buf[i] != '\n'; --i)
155 				{
156 					continue;
157 				}
158 
159 				i += 1;
160 
161 				// Save the extras.
162 				bc_vec_string(&vm.history.extras, f->len - i, f->buf + i);
163 			}
164 			// Else clear the extras if told to.
165 			else if (type >= BC_FLUSH_NO_EXTRAS_CLEAR)
166 			{
167 				bc_vec_popAll(&vm.history.extras);
168 			}
169 		}
170 #endif // BC_ENABLE_HISTORY
171 
172 		// Actually output.
173 		s = bc_file_output(f->fd, f->buf, f->len);
174 		f->len = 0;
175 	}
176 	else s = BC_STATUS_SUCCESS;
177 
178 #endif // BC_ENABLE_LINE_LIB
179 
180 	return s;
181 }
182 
183 void
184 bc_file_flush(BcFile* restrict f, BcFlushType type)
185 {
186 	BcStatus s;
187 	sig_atomic_t lock;
188 
189 	BC_SIG_TRYLOCK(lock);
190 
191 	s = bc_file_flushErr(f, type);
192 
193 	// If we have an error...
194 	if (BC_ERR(s))
195 	{
196 		// For EOF, set it and jump.
197 		if (s == BC_STATUS_EOF)
198 		{
199 			vm.status = (sig_atomic_t) s;
200 			BC_SIG_TRYUNLOCK(lock);
201 			BC_JMP;
202 		}
203 		// Blow up on fatal error. Okay, not blow up, just quit.
204 		else bc_vm_fatalError(BC_ERR_FATAL_IO_ERR);
205 	}
206 
207 	BC_SIG_TRYUNLOCK(lock);
208 }
209 
210 #if !BC_ENABLE_LINE_LIB
211 
212 void
213 bc_file_write(BcFile* restrict f, BcFlushType type, const char* buf, size_t n)
214 {
215 	sig_atomic_t lock;
216 
217 	BC_SIG_TRYLOCK(lock);
218 
219 	// If we have enough to flush, do it.
220 	if (n > f->cap - f->len)
221 	{
222 		bc_file_flush(f, type);
223 		assert(!f->len);
224 	}
225 
226 	// If the output is large enough to flush by itself, just output it.
227 	// Otherwise, put it into the buffer.
228 	if (BC_UNLIKELY(n > f->cap - f->len))
229 	{
230 		BcStatus s = bc_file_output(f->fd, buf, n);
231 
232 		if (BC_ERR(s))
233 		{
234 			// For EOF, set it and jump.
235 			if (s == BC_STATUS_EOF)
236 			{
237 				vm.status = (sig_atomic_t) s;
238 				BC_SIG_TRYUNLOCK(lock);
239 				BC_JMP;
240 			}
241 			// Blow up on fatal error. Okay, not blow up, just quit.
242 			else bc_vm_fatalError(BC_ERR_FATAL_IO_ERR);
243 		}
244 	}
245 	else
246 	{
247 		// NOLINTNEXTLINE
248 		memcpy(f->buf + f->len, buf, n);
249 		f->len += n;
250 	}
251 
252 	BC_SIG_TRYUNLOCK(lock);
253 }
254 
255 #endif // BC_ENABLE_LINE_LIB
256 
257 void
258 bc_file_printf(BcFile* restrict f, const char* fmt, ...)
259 {
260 	va_list args;
261 	sig_atomic_t lock;
262 
263 	BC_SIG_TRYLOCK(lock);
264 
265 	va_start(args, fmt);
266 	bc_file_vprintf(f, fmt, args);
267 	va_end(args);
268 
269 	BC_SIG_TRYUNLOCK(lock);
270 }
271 
272 void
273 bc_file_vprintf(BcFile* restrict f, const char* fmt, va_list args)
274 {
275 	BC_SIG_ASSERT_LOCKED;
276 
277 #if BC_ENABLE_LINE_LIB
278 
279 	// Just print and propagate the error.
280 	if (BC_ERR(vfprintf(f->f, fmt, args) < 0))
281 	{
282 		bc_vm_fatalError(BC_ERR_FATAL_IO_ERR);
283 	}
284 
285 #else // BC_ENABLE_LINE_LIB
286 
287 	char* percent;
288 	const char* ptr = fmt;
289 	char buf[BC_FILE_ULL_LENGTH];
290 
291 	// This is a poor man's printf(). While I could look up algorithms to make
292 	// it as fast as possible, and should when I write the standard library for
293 	// a new language, for bc, outputting is not the bottleneck. So we cheese it
294 	// for now.
295 
296 	// Find each percent sign.
297 	while ((percent = strchr(ptr, '%')) != NULL)
298 	{
299 		char c;
300 
301 		// If the percent sign is not where we are, write what's inbetween to
302 		// the buffer.
303 		if (percent != ptr)
304 		{
305 			size_t len = (size_t) (percent - ptr);
306 			bc_file_write(f, bc_flush_none, ptr, len);
307 		}
308 
309 		c = percent[1];
310 
311 		// We only parse some format specifiers, the ones bc uses. If you add
312 		// more, you need to make sure to add them here.
313 		if (c == 'c')
314 		{
315 			uchar uc = (uchar) va_arg(args, int);
316 
317 			bc_file_putchar(f, bc_flush_none, uc);
318 		}
319 		else if (c == 's')
320 		{
321 			char* s = va_arg(args, char*);
322 
323 			bc_file_puts(f, bc_flush_none, s);
324 		}
325 #if BC_DEBUG_CODE
326 		// We only print signed integers in debug code.
327 		else if (c == 'd')
328 		{
329 			int d = va_arg(args, int);
330 
331 			// Take care of negative. Let's not worry about overflow.
332 			if (d < 0)
333 			{
334 				bc_file_putchar(f, bc_flush_none, '-');
335 				d = -d;
336 			}
337 
338 			// Either print 0 or translate and print.
339 			if (!d) bc_file_putchar(f, bc_flush_none, '0');
340 			else
341 			{
342 				bc_file_ultoa((unsigned long long) d, buf);
343 				bc_file_puts(f, bc_flush_none, buf);
344 			}
345 		}
346 #endif // BC_DEBUG_CODE
347 		else
348 		{
349 			unsigned long long ull;
350 
351 			// These are the ones that it expects from here. Fortunately, all of
352 			// these are unsigned types, so they can use the same code, more or
353 			// less.
354 			assert((c == 'l' || c == 'z') && percent[2] == 'u');
355 
356 			if (c == 'z') ull = (unsigned long long) va_arg(args, size_t);
357 			else ull = (unsigned long long) va_arg(args, unsigned long);
358 
359 			// Either print 0 or translate and print.
360 			if (!ull) bc_file_putchar(f, bc_flush_none, '0');
361 			else
362 			{
363 				bc_file_ultoa(ull, buf);
364 				bc_file_puts(f, bc_flush_none, buf);
365 			}
366 		}
367 
368 		// Increment to the next spot after the specifier.
369 		ptr = percent + 2 + (c == 'l' || c == 'z');
370 	}
371 
372 	// If we get here, there are no more percent signs, so we just output
373 	// whatever is left.
374 	if (ptr[0]) bc_file_puts(f, bc_flush_none, ptr);
375 
376 #endif // BC_ENABLE_LINE_LIB
377 }
378 
379 void
380 bc_file_puts(BcFile* restrict f, BcFlushType type, const char* str)
381 {
382 #if BC_ENABLE_LINE_LIB
383 	// This is used because of flushing issues with using bc_file_write() when
384 	// bc is using a line library. It's also using printf() because puts()
385 	// writes a newline.
386 	bc_file_printf(f, "%s", str);
387 #else // BC_ENABLE_LINE_LIB
388 	bc_file_write(f, type, str, strlen(str));
389 #endif // BC_ENABLE_LINE_LIB
390 }
391 
392 void
393 bc_file_putchar(BcFile* restrict f, BcFlushType type, uchar c)
394 {
395 	sig_atomic_t lock;
396 
397 	BC_SIG_TRYLOCK(lock);
398 
399 #if BC_ENABLE_LINE_LIB
400 
401 	if (BC_ERR(fputc(c, f->f) == EOF))
402 	{
403 		// This is here to prevent a stack overflow from unbounded recursion.
404 		if (f->f == stderr) exit(BC_STATUS_ERROR_FATAL);
405 
406 		bc_vm_fatalError(BC_ERR_FATAL_IO_ERR);
407 	}
408 
409 #else // BC_ENABLE_LINE_LIB
410 
411 	if (f->len == f->cap) bc_file_flush(f, type);
412 
413 	assert(f->len < f->cap);
414 
415 	f->buf[f->len] = (char) c;
416 	f->len += 1;
417 
418 #endif // BC_ENABLE_LINE_LIB
419 
420 	BC_SIG_TRYUNLOCK(lock);
421 }
422 
423 #if BC_ENABLE_LINE_LIB
424 
425 void
426 bc_file_init(BcFile* f, FILE* file)
427 {
428 	BC_SIG_ASSERT_LOCKED;
429 	f->f = file;
430 }
431 
432 #else // BC_ENABLE_LINE_LIB
433 
434 void
435 bc_file_init(BcFile* f, int fd, char* buf, size_t cap)
436 {
437 	BC_SIG_ASSERT_LOCKED;
438 
439 	f->fd = fd;
440 	f->buf = buf;
441 	f->len = 0;
442 	f->cap = cap;
443 }
444 
445 #endif // BC_ENABLE_LINE_LIB
446 
447 void
448 bc_file_free(BcFile* f)
449 {
450 	BC_SIG_ASSERT_LOCKED;
451 	bc_file_flush(f, bc_flush_none);
452 }
453