xref: /freebsd/contrib/bc/src/file.c (revision 7937bfbc0ca53fe7cdd0d54414f9296e273a518e)
1 /*
2  * *****************************************************************************
3  *
4  * SPDX-License-Identifier: BSD-2-Clause
5  *
6  * Copyright (c) 2018-2024 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 		// Make sure to handle non-fatal I/O properly.
204 		else if (!f->errors_fatal)
205 		{
206 			bc_vm_fatalError(BC_ERR_FATAL_IO_ERR);
207 		}
208 		// Blow up on fatal error. Okay, not blow up, just quit.
209 		else exit(BC_STATUS_ERROR_FATAL);
210 	}
211 
212 	BC_SIG_TRYUNLOCK(lock);
213 }
214 
215 #if !BC_ENABLE_LINE_LIB
216 
217 void
218 bc_file_write(BcFile* restrict f, BcFlushType type, const char* buf, size_t n)
219 {
220 	sig_atomic_t lock;
221 
222 	BC_SIG_TRYLOCK(lock);
223 
224 	// If we have enough to flush, do it.
225 	if (n > f->cap - f->len)
226 	{
227 		bc_file_flush(f, type);
228 		assert(!f->len);
229 	}
230 
231 	// If the output is large enough to flush by itself, just output it.
232 	// Otherwise, put it into the buffer.
233 	if (BC_UNLIKELY(n > f->cap - f->len))
234 	{
235 		BcStatus s = bc_file_output(f->fd, buf, n);
236 
237 		if (BC_ERR(s))
238 		{
239 			// For EOF, set it and jump.
240 			if (s == BC_STATUS_EOF)
241 			{
242 				vm->status = (sig_atomic_t) s;
243 				BC_SIG_TRYUNLOCK(lock);
244 				BC_JMP;
245 			}
246 			// Make sure to handle non-fatal I/O properly.
247 			else if (!f->errors_fatal)
248 			{
249 				bc_vm_fatalError(BC_ERR_FATAL_IO_ERR);
250 			}
251 			// Blow up on fatal error. Okay, not blow up, just quit.
252 			else exit(BC_STATUS_ERROR_FATAL);
253 		}
254 	}
255 	else
256 	{
257 		// NOLINTNEXTLINE
258 		memcpy(f->buf + f->len, buf, n);
259 		f->len += n;
260 	}
261 
262 	BC_SIG_TRYUNLOCK(lock);
263 }
264 
265 #endif // BC_ENABLE_LINE_LIB
266 
267 void
268 bc_file_printf(BcFile* restrict f, const char* fmt, ...)
269 {
270 	va_list args;
271 	sig_atomic_t lock;
272 
273 	BC_SIG_TRYLOCK(lock);
274 
275 	va_start(args, fmt);
276 	bc_file_vprintf(f, fmt, args);
277 	va_end(args);
278 
279 	BC_SIG_TRYUNLOCK(lock);
280 }
281 
282 void
283 bc_file_vprintf(BcFile* restrict f, const char* fmt, va_list args)
284 {
285 	BC_SIG_ASSERT_LOCKED;
286 
287 #if BC_ENABLE_LINE_LIB
288 
289 	{
290 		int r;
291 
292 		// This mess is to silence a warning.
293 #if BC_CLANG
294 #pragma clang diagnostic ignored "-Wformat-nonliteral"
295 #endif // BC_CLANG
296 		r = vfprintf(f->f, fmt, args);
297 #if BC_CLANG
298 #pragma clang diagnostic warning "-Wformat-nonliteral"
299 #endif // BC_CLANG
300 
301 		// Just print and propagate the error.
302 		if (BC_ERR(r < 0))
303 		{
304 			// Make sure to handle non-fatal I/O properly.
305 			if (!f->errors_fatal)
306 			{
307 				bc_vm_fatalError(BC_ERR_FATAL_IO_ERR);
308 			}
309 			else
310 			{
311 				exit(BC_STATUS_ERROR_FATAL);
312 			}
313 		}
314 	}
315 
316 #else // BC_ENABLE_LINE_LIB
317 
318 	{
319 		char* percent;
320 		const char* ptr = fmt;
321 		char buf[BC_FILE_ULL_LENGTH];
322 
323 		// This is a poor man's printf(). While I could look up algorithms to
324 		// make it as fast as possible, and should when I write the standard
325 		// library for a new language, for bc, outputting is not the bottleneck.
326 		// So we cheese it for now.
327 
328 		// Find each percent sign.
329 		while ((percent = strchr(ptr, '%')) != NULL)
330 		{
331 			char c;
332 
333 			// If the percent sign is not where we are, write what's inbetween
334 			// to the buffer.
335 			if (percent != ptr)
336 			{
337 				size_t len = (size_t) (percent - ptr);
338 				bc_file_write(f, bc_flush_none, ptr, len);
339 			}
340 
341 			c = percent[1];
342 
343 			// We only parse some format specifiers, the ones bc uses. If you
344 			// add more, you need to make sure to add them here.
345 			if (c == 'c')
346 			{
347 				uchar uc = (uchar) va_arg(args, int);
348 
349 				bc_file_putchar(f, bc_flush_none, uc);
350 			}
351 			else if (c == 's')
352 			{
353 				char* s = va_arg(args, char*);
354 
355 				bc_file_puts(f, bc_flush_none, s);
356 			}
357 #if BC_DEBUG
358 			// We only print signed integers in debug code.
359 			else if (c == 'd')
360 			{
361 				int d = va_arg(args, int);
362 
363 				// Take care of negative. Let's not worry about overflow.
364 				if (d < 0)
365 				{
366 					bc_file_putchar(f, bc_flush_none, '-');
367 					d = -d;
368 				}
369 
370 				// Either print 0 or translate and print.
371 				if (!d) bc_file_putchar(f, bc_flush_none, '0');
372 				else
373 				{
374 					bc_file_ultoa((unsigned long long) d, buf);
375 					bc_file_puts(f, bc_flush_none, buf);
376 				}
377 			}
378 #endif // BC_DEBUG
379 			else
380 			{
381 				unsigned long long ull;
382 
383 				// These are the ones that it expects from here. Fortunately,
384 				// all of these are unsigned types, so they can use the same
385 				// code, more or less.
386 				assert((c == 'l' || c == 'z') && percent[2] == 'u');
387 
388 				if (c == 'z') ull = (unsigned long long) va_arg(args, size_t);
389 				else ull = (unsigned long long) va_arg(args, unsigned long);
390 
391 				// Either print 0 or translate and print.
392 				if (!ull) bc_file_putchar(f, bc_flush_none, '0');
393 				else
394 				{
395 					bc_file_ultoa(ull, buf);
396 					bc_file_puts(f, bc_flush_none, buf);
397 				}
398 			}
399 
400 			// Increment to the next spot after the specifier.
401 			ptr = percent + 2 + (c == 'l' || c == 'z');
402 		}
403 
404 		// If we get here, there are no more percent signs, so we just output
405 		// whatever is left.
406 		if (ptr[0]) bc_file_puts(f, bc_flush_none, ptr);
407 	}
408 
409 #endif // BC_ENABLE_LINE_LIB
410 }
411 
412 void
413 bc_file_puts(BcFile* restrict f, BcFlushType type, const char* str)
414 {
415 #if BC_ENABLE_LINE_LIB
416 	// This is used because of flushing issues with using bc_file_write() when
417 	// bc is using a line library. It's also using printf() because puts()
418 	// writes a newline.
419 	bc_file_printf(f, "%s", str);
420 #else // BC_ENABLE_LINE_LIB
421 	bc_file_write(f, type, str, strlen(str));
422 #endif // BC_ENABLE_LINE_LIB
423 }
424 
425 void
426 bc_file_putchar(BcFile* restrict f, BcFlushType type, uchar c)
427 {
428 	sig_atomic_t lock;
429 
430 	BC_SIG_TRYLOCK(lock);
431 
432 #if BC_ENABLE_LINE_LIB
433 
434 	if (BC_ERR(fputc(c, f->f) == EOF))
435 	{
436 		// This is here to prevent a stack overflow from unbounded recursion.
437 		if (f->f == stderr) exit(BC_STATUS_ERROR_FATAL);
438 
439 		bc_err(BC_ERR_FATAL_IO_ERR);
440 	}
441 
442 #else // BC_ENABLE_LINE_LIB
443 
444 	if (f->len == f->cap) bc_file_flush(f, type);
445 
446 	assert(f->len < f->cap);
447 
448 	f->buf[f->len] = (char) c;
449 	f->len += 1;
450 
451 #endif // BC_ENABLE_LINE_LIB
452 
453 	BC_SIG_TRYUNLOCK(lock);
454 }
455 
456 #if BC_ENABLE_LINE_LIB
457 
458 void
459 bc_file_init(BcFile* f, FILE* file, bool errors_fatal)
460 {
461 	BC_SIG_ASSERT_LOCKED;
462 	f->f = file;
463 	f->errors_fatal = errors_fatal;
464 }
465 
466 #else // BC_ENABLE_LINE_LIB
467 
468 void
469 bc_file_init(BcFile* f, int fd, char* buf, size_t cap, bool errors_fatal)
470 {
471 	BC_SIG_ASSERT_LOCKED;
472 
473 	f->fd = fd;
474 	f->buf = buf;
475 	f->len = 0;
476 	f->cap = cap;
477 	f->errors_fatal = errors_fatal;
478 }
479 
480 #endif // BC_ENABLE_LINE_LIB
481 
482 void
483 bc_file_free(BcFile* f)
484 {
485 	BC_SIG_ASSERT_LOCKED;
486 	bc_file_flush(f, bc_flush_none);
487 }
488