xref: /freebsd/contrib/bc/src/file.c (revision 031beb4e239bfce798af17f5fe8dba8bcaf13d99)
1 /*
2  * *****************************************************************************
3  *
4  * SPDX-License-Identifier: BSD-2-Clause
5  *
6  * Copyright (c) 2018-2023 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 	{
280 		int r;
281 
282 		// This mess is to silence a warning.
283 #if BC_CLANG
284 #pragma clang diagnostic ignored "-Wformat-nonliteral"
285 #endif // BC_CLANG
286 		r = vfprintf(f->f, fmt, args);
287 #if BC_CLANG
288 #pragma clang diagnostic warning "-Wformat-nonliteral"
289 #endif // BC_CLANG
290 
291 		// Just print and propagate the error.
292 		if (BC_ERR(r < 0))
293 		{
294 			bc_vm_fatalError(BC_ERR_FATAL_IO_ERR);
295 		}
296 	}
297 
298 #else // BC_ENABLE_LINE_LIB
299 
300 	{
301 		char* percent;
302 		const char* ptr = fmt;
303 		char buf[BC_FILE_ULL_LENGTH];
304 
305 		// This is a poor man's printf(). While I could look up algorithms to
306 		// make it as fast as possible, and should when I write the standard
307 		// library for a new language, for bc, outputting is not the bottleneck.
308 		// So we cheese it for now.
309 
310 		// Find each percent sign.
311 		while ((percent = strchr(ptr, '%')) != NULL)
312 		{
313 			char c;
314 
315 			// If the percent sign is not where we are, write what's inbetween
316 			// to the buffer.
317 			if (percent != ptr)
318 			{
319 				size_t len = (size_t) (percent - ptr);
320 				bc_file_write(f, bc_flush_none, ptr, len);
321 			}
322 
323 			c = percent[1];
324 
325 			// We only parse some format specifiers, the ones bc uses. If you
326 			// add more, you need to make sure to add them here.
327 			if (c == 'c')
328 			{
329 				uchar uc = (uchar) va_arg(args, int);
330 
331 				bc_file_putchar(f, bc_flush_none, uc);
332 			}
333 			else if (c == 's')
334 			{
335 				char* s = va_arg(args, char*);
336 
337 				bc_file_puts(f, bc_flush_none, s);
338 			}
339 #if BC_DEBUG
340 			// We only print signed integers in debug code.
341 			else if (c == 'd')
342 			{
343 				int d = va_arg(args, int);
344 
345 				// Take care of negative. Let's not worry about overflow.
346 				if (d < 0)
347 				{
348 					bc_file_putchar(f, bc_flush_none, '-');
349 					d = -d;
350 				}
351 
352 				// Either print 0 or translate and print.
353 				if (!d) bc_file_putchar(f, bc_flush_none, '0');
354 				else
355 				{
356 					bc_file_ultoa((unsigned long long) d, buf);
357 					bc_file_puts(f, bc_flush_none, buf);
358 				}
359 			}
360 #endif // BC_DEBUG
361 			else
362 			{
363 				unsigned long long ull;
364 
365 				// These are the ones that it expects from here. Fortunately,
366 				// all of these are unsigned types, so they can use the same
367 				// code, more or less.
368 				assert((c == 'l' || c == 'z') && percent[2] == 'u');
369 
370 				if (c == 'z') ull = (unsigned long long) va_arg(args, size_t);
371 				else ull = (unsigned long long) va_arg(args, unsigned long);
372 
373 				// Either print 0 or translate and print.
374 				if (!ull) bc_file_putchar(f, bc_flush_none, '0');
375 				else
376 				{
377 					bc_file_ultoa(ull, buf);
378 					bc_file_puts(f, bc_flush_none, buf);
379 				}
380 			}
381 
382 			// Increment to the next spot after the specifier.
383 			ptr = percent + 2 + (c == 'l' || c == 'z');
384 		}
385 
386 		// If we get here, there are no more percent signs, so we just output
387 		// whatever is left.
388 		if (ptr[0]) bc_file_puts(f, bc_flush_none, ptr);
389 	}
390 
391 #endif // BC_ENABLE_LINE_LIB
392 }
393 
394 void
395 bc_file_puts(BcFile* restrict f, BcFlushType type, const char* str)
396 {
397 #if BC_ENABLE_LINE_LIB
398 	// This is used because of flushing issues with using bc_file_write() when
399 	// bc is using a line library. It's also using printf() because puts()
400 	// writes a newline.
401 	bc_file_printf(f, "%s", str);
402 #else // BC_ENABLE_LINE_LIB
403 	bc_file_write(f, type, str, strlen(str));
404 #endif // BC_ENABLE_LINE_LIB
405 }
406 
407 void
408 bc_file_putchar(BcFile* restrict f, BcFlushType type, uchar c)
409 {
410 	sig_atomic_t lock;
411 
412 	BC_SIG_TRYLOCK(lock);
413 
414 #if BC_ENABLE_LINE_LIB
415 
416 	if (BC_ERR(fputc(c, f->f) == EOF))
417 	{
418 		// This is here to prevent a stack overflow from unbounded recursion.
419 		if (f->f == stderr) exit(BC_STATUS_ERROR_FATAL);
420 
421 		bc_vm_fatalError(BC_ERR_FATAL_IO_ERR);
422 	}
423 
424 #else // BC_ENABLE_LINE_LIB
425 
426 	if (f->len == f->cap) bc_file_flush(f, type);
427 
428 	assert(f->len < f->cap);
429 
430 	f->buf[f->len] = (char) c;
431 	f->len += 1;
432 
433 #endif // BC_ENABLE_LINE_LIB
434 
435 	BC_SIG_TRYUNLOCK(lock);
436 }
437 
438 #if BC_ENABLE_LINE_LIB
439 
440 void
441 bc_file_init(BcFile* f, FILE* file)
442 {
443 	BC_SIG_ASSERT_LOCKED;
444 	f->f = file;
445 }
446 
447 #else // BC_ENABLE_LINE_LIB
448 
449 void
450 bc_file_init(BcFile* f, int fd, char* buf, size_t cap)
451 {
452 	BC_SIG_ASSERT_LOCKED;
453 
454 	f->fd = fd;
455 	f->buf = buf;
456 	f->len = 0;
457 	f->cap = cap;
458 }
459 
460 #endif // BC_ENABLE_LINE_LIB
461 
462 void
463 bc_file_free(BcFile* f)
464 {
465 	BC_SIG_ASSERT_LOCKED;
466 	bc_file_flush(f, bc_flush_none);
467 }
468