xref: /aosp_15_r20/external/bc/src/vm.c (revision 5a6e848804d15c18a0125914844ee4eb0bda4fcf)
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 common to all of bc and dc.
33  *
34  */
35 
36 #include <assert.h>
37 #include <ctype.h>
38 #include <errno.h>
39 #include <stdarg.h>
40 #include <string.h>
41 
42 #include <signal.h>
43 
44 #include <setjmp.h>
45 
46 #ifndef _WIN32
47 
48 #include <unistd.h>
49 #include <sys/types.h>
50 #include <unistd.h>
51 
52 #else // _WIN32
53 
54 #define WIN32_LEAN_AND_MEAN
55 #include <windows.h>
56 #include <io.h>
57 
58 #endif // _WIN32
59 
60 #include <status.h>
61 #include <vector.h>
62 #include <args.h>
63 #include <vm.h>
64 #include <read.h>
65 #include <bc.h>
66 #if BC_ENABLE_LIBRARY
67 #include <library.h>
68 #endif // BC_ENABLE_LIBRARY
69 #if BC_ENABLE_OSSFUZZ
70 #include <ossfuzz.h>
71 #endif // BC_ENABLE_OSSFUZZ
72 
73 #if !BC_ENABLE_LIBRARY
74 
75 // The actual globals.
76 char output_bufs[BC_VM_BUF_SIZE];
77 BcVm vm_data;
78 BcVm* vm = &vm_data;
79 
80 #endif // !BC_ENABLE_LIBRARY
81 
82 #if BC_DEBUG_CODE
83 BC_NORETURN void
bc_vm_jmp(const char * f)84 bc_vm_jmp(const char* f)
85 {
86 #else // BC_DEBUG_CODE
87 BC_NORETURN void
88 bc_vm_jmp(void)
89 {
90 #endif
91 
92 #if BC_ENABLE_LIBRARY
93 	BcVm* vm = bcl_getspecific();
94 #endif // BC_ENABLE_LIBRARY
95 
96 	assert(BC_SIG_EXC(vm));
97 
98 	BC_SIG_MAYLOCK;
99 
100 #if BC_DEBUG_CODE
101 	bc_file_puts(&vm->ferr, bc_flush_none, "Longjmp: ");
102 	bc_file_puts(&vm->ferr, bc_flush_none, f);
103 	bc_file_putchar(&vm->ferr, bc_flush_none, '\n');
104 	bc_file_flush(&vm->ferr, bc_flush_none);
105 #endif // BC_DEBUG_CODE
106 
107 #if BC_DEBUG
108 	assert(vm->jmp_bufs.len - (size_t) vm->sig_pop);
109 #endif // BC_DEBUG
110 
111 	if (vm->jmp_bufs.len == 0) abort();
112 	if (vm->sig_pop) bc_vec_pop(&vm->jmp_bufs);
113 	else vm->sig_pop = 1;
114 
115 	siglongjmp(*((sigjmp_buf*) bc_vec_top(&vm->jmp_bufs)), 1);
116 }
117 
118 #if !BC_ENABLE_LIBRARY
119 
120 /**
121  * Handles signals. This is the signal handler.
122  * @param sig  The signal to handle.
123  */
124 static void
125 bc_vm_sig(int sig)
126 {
127 #if BC_ENABLE_EDITLINE
128 	// Editline needs this to resize the terminal. This also needs to come first
129 	// because a resize always needs to happen.
130 	if (sig == SIGWINCH)
131 	{
132 		if (BC_TTY)
133 		{
134 			el_resize(vm->history.el);
135 
136 			// If the signal was a SIGWINCH, clear it because we don't need to
137 			// print a stack trace in that case.
138 			if (vm->sig == SIGWINCH)
139 			{
140 				vm->sig = 0;
141 			}
142 		}
143 
144 		return;
145 	}
146 #endif // BC_ENABLE_EDITLINE
147 
148 	// There is already a signal in flight if this is true.
149 	if (vm->status == (sig_atomic_t) BC_STATUS_QUIT || vm->sig != 0)
150 	{
151 		if (!BC_I || sig != SIGINT) vm->status = BC_STATUS_QUIT;
152 		return;
153 	}
154 
155 	// We always want to set this because a stack trace can be printed if we do.
156 	vm->sig = sig;
157 
158 	// Only reset under these conditions; otherwise, quit.
159 	if (sig == SIGINT && BC_SIGINT && BC_I)
160 	{
161 		int err = errno;
162 
163 #if BC_ENABLE_EDITLINE
164 		// Editline needs this, for some unknown reason.
165 		if (write(STDOUT_FILENO, "^C", 2) != (ssize_t) 2)
166 		{
167 			vm->status = BC_STATUS_ERROR_FATAL;
168 		}
169 #endif // BC_ENABLE_EDITLINE
170 
171 		// Write the message.
172 		if (write(STDOUT_FILENO, vm->sigmsg, vm->siglen) !=
173 		    (ssize_t) vm->siglen)
174 		{
175 			vm->status = BC_STATUS_ERROR_FATAL;
176 		}
177 
178 		errno = err;
179 	}
180 	else
181 	{
182 #if BC_ENABLE_EDITLINE
183 		if (write(STDOUT_FILENO, "^C", 2) != (ssize_t) 2)
184 		{
185 			vm->status = BC_STATUS_ERROR_FATAL;
186 			return;
187 		}
188 #endif // BC_ENABLE_EDITLINE
189 
190 		vm->status = BC_STATUS_QUIT;
191 	}
192 
193 #if BC_ENABLE_LINE_LIB
194 	// Readline and Editline need this to actually handle sigints correctly.
195 	if (sig == SIGINT && bc_history_inlinelib)
196 	{
197 		bc_history_inlinelib = 0;
198 		siglongjmp(bc_history_jmpbuf, 1);
199 	}
200 #endif // BC_ENABLE_LINE_LIB
201 
202 	assert(vm->jmp_bufs.len);
203 
204 	// Only jump if signals are not locked. The jump will happen by whoever
205 	// unlocks signals.
206 	if (!vm->sig_lock) BC_JMP;
207 }
208 
209 /**
210  * Sets up signal handling.
211  */
212 static void
213 bc_vm_sigaction(void)
214 {
215 #ifndef _WIN32
216 
217 	struct sigaction sa;
218 
219 	sigemptyset(&sa.sa_mask);
220 	sa.sa_flags = BC_ENABLE_EDITLINE ? 0 : SA_NODEFER;
221 
222 	// This mess is to silence a warning on Clang with regards to glibc's
223 	// sigaction handler, which activates the warning here.
224 #if BC_CLANG
225 #pragma clang diagnostic push
226 #pragma clang diagnostic ignored "-Wdisabled-macro-expansion"
227 #endif // BC_CLANG
228 	sa.sa_handler = bc_vm_sig;
229 #if BC_CLANG
230 #pragma clang diagnostic pop
231 #endif // BC_CLANG
232 
233 	sigaction(SIGTERM, &sa, NULL);
234 	sigaction(SIGQUIT, &sa, NULL);
235 	sigaction(SIGINT, &sa, NULL);
236 
237 #if BC_ENABLE_EDITLINE
238 	// Editline needs this to resize the terminal.
239 	if (BC_TTY) sigaction(SIGWINCH, &sa, NULL);
240 #endif // BC_ENABLE_EDITLINE
241 
242 #if BC_ENABLE_HISTORY
243 	if (BC_TTY) sigaction(SIGHUP, &sa, NULL);
244 #endif // BC_ENABLE_HISTORY
245 
246 #else // _WIN32
247 
248 	signal(SIGTERM, bc_vm_sig);
249 	signal(SIGINT, bc_vm_sig);
250 
251 #endif // _WIN32
252 }
253 
254 void
255 bc_vm_info(const char* const help)
256 {
257 	BC_SIG_ASSERT_LOCKED;
258 
259 	// Print the banner.
260 	bc_file_printf(&vm->fout, "%s %s\n%s", vm->name, BC_VERSION, bc_copyright);
261 
262 	// Print the help.
263 	if (help != NULL)
264 	{
265 		bc_file_putchar(&vm->fout, bc_flush_none, '\n');
266 
267 #if BC_ENABLED
268 		if (BC_IS_BC)
269 		{
270 			const char* const banner = BC_DEFAULT_BANNER ? "to" : "to not";
271 			const char* const sigint = BC_DEFAULT_SIGINT_RESET ? "to reset" :
272 			                                                     "to exit";
273 			const char* const tty = BC_DEFAULT_TTY_MODE ? "enabled" :
274 			                                              "disabled";
275 			const char* const prompt = BC_DEFAULT_PROMPT ? "enabled" :
276 			                                               "disabled";
277 			const char* const expr = BC_DEFAULT_EXPR_EXIT ? "to exit" :
278 			                                                "to not exit";
279 			const char* const clamp = BC_DEFAULT_DIGIT_CLAMP ? "to clamp" :
280 			                                                   "to not clamp";
281 
282 			bc_file_printf(&vm->fout, help, vm->name, vm->name, BC_VERSION,
283 			               BC_BUILD_TYPE, banner, sigint, tty, prompt, expr,
284 			               clamp);
285 		}
286 #endif // BC_ENABLED
287 
288 #if DC_ENABLED
289 		if (BC_IS_DC)
290 		{
291 			const char* const sigint = DC_DEFAULT_SIGINT_RESET ? "to reset" :
292 			                                                     "to exit";
293 			const char* const tty = DC_DEFAULT_TTY_MODE ? "enabled" :
294 			                                              "disabled";
295 			const char* const prompt = DC_DEFAULT_PROMPT ? "enabled" :
296 			                                               "disabled";
297 			const char* const expr = DC_DEFAULT_EXPR_EXIT ? "to exit" :
298 			                                                "to not exit";
299 			const char* const clamp = DC_DEFAULT_DIGIT_CLAMP ? "to clamp" :
300 			                                                   "to not clamp";
301 
302 			bc_file_printf(&vm->fout, help, vm->name, vm->name, BC_VERSION,
303 			               BC_BUILD_TYPE, sigint, tty, prompt, expr, clamp);
304 		}
305 #endif // DC_ENABLED
306 	}
307 
308 	// Flush.
309 	bc_file_flush(&vm->fout, bc_flush_none);
310 }
311 #endif // !BC_ENABLE_LIBRARY
312 
313 #if !BC_ENABLE_LIBRARY && !BC_ENABLE_MEMCHECK
314 BC_NORETURN
315 #endif // !BC_ENABLE_LIBRARY && !BC_ENABLE_MEMCHECK
316 void
317 bc_vm_fatalError(BcErr e)
318 {
319 	bc_err(e);
320 #if !BC_ENABLE_LIBRARY && !BC_ENABLE_MEMCHECK
321 	BC_UNREACHABLE
322 #if !BC_CLANG
323 	abort();
324 #endif // !BC_CLANG
325 #endif // !BC_ENABLE_LIBRARY && !BC_ENABLE_MEMCHECK
326 }
327 
328 #if BC_ENABLE_LIBRARY
329 BC_NORETURN void
330 bc_vm_handleError(BcErr e)
331 {
332 #if BC_ENABLE_LIBRARY
333 	BcVm* vm = bcl_getspecific();
334 #endif // BC_ENABLE_LIBRARY
335 
336 	assert(e < BC_ERR_NELEMS);
337 	assert(!vm->sig_pop);
338 
339 	BC_SIG_LOCK;
340 
341 	// If we have a normal error...
342 	if (e <= BC_ERR_MATH_DIVIDE_BY_ZERO)
343 	{
344 		// Set the error.
345 		vm->err = (BclError) (e - BC_ERR_MATH_NEGATIVE +
346 		                      BCL_ERROR_MATH_NEGATIVE);
347 	}
348 	// Abort if we should.
349 	else if (vm->abrt) abort();
350 	else if (e == BC_ERR_FATAL_ALLOC_ERR) vm->err = BCL_ERROR_FATAL_ALLOC_ERR;
351 	else vm->err = BCL_ERROR_FATAL_UNKNOWN_ERR;
352 
353 	BC_JMP;
354 }
355 #else // BC_ENABLE_LIBRARY
356 #if BC_DEBUG
357 void
358 bc_vm_handleError(BcErr e, const char* file, int fline, size_t line, ...)
359 #else // BC_DEBUG
360 void
361 bc_vm_handleError(BcErr e, size_t line, ...)
362 #endif // BC_DEBUG
363 {
364 	BcStatus s;
365 	BcStatus fout_s;
366 	va_list args;
367 	uchar id = bc_err_ids[e];
368 	const char* err_type = vm->err_ids[id];
369 	sig_atomic_t lock;
370 
371 	assert(e < BC_ERR_NELEMS);
372 	assert(!vm->sig_pop);
373 
374 #if BC_ENABLED
375 	// Figure out if the POSIX error should be an error, a warning, or nothing.
376 	if (!BC_S && e >= BC_ERR_POSIX_START)
377 	{
378 		if (BC_W)
379 		{
380 			// Make sure to not return an error.
381 			id = UCHAR_MAX;
382 			err_type = vm->err_ids[BC_ERR_IDX_WARN];
383 		}
384 		else return;
385 	}
386 #endif // BC_ENABLED
387 
388 	BC_SIG_TRYLOCK(lock);
389 
390 	// Make sure all of stdout is written first.
391 	fout_s = bc_file_flushErr(&vm->fout, bc_flush_err);
392 
393 	// XXX: Keep the status for later.
394 
395 	// Print the error message.
396 	va_start(args, line);
397 	bc_file_putchar(&vm->ferr, bc_flush_none, '\n');
398 	bc_file_puts(&vm->ferr, bc_flush_none, err_type);
399 	bc_file_putchar(&vm->ferr, bc_flush_none, ' ');
400 	bc_file_vprintf(&vm->ferr, vm->err_msgs[e], args);
401 	va_end(args);
402 
403 	// Print the extra information if we have it.
404 	if (BC_NO_ERR(vm->file != NULL))
405 	{
406 		// This is the condition for parsing vs runtime.
407 		// If line is not 0, it is parsing.
408 		if (line)
409 		{
410 			bc_file_puts(&vm->ferr, bc_flush_none, "\n    ");
411 			bc_file_puts(&vm->ferr, bc_flush_none, vm->file);
412 			bc_file_printf(&vm->ferr, ":%zu\n", line);
413 		}
414 		else
415 		{
416 			// Print a stack trace.
417 			bc_file_putchar(&vm->ferr, bc_flush_none, '\n');
418 			bc_program_printStackTrace(&vm->prog);
419 		}
420 	}
421 	else
422 	{
423 		bc_file_putchar(&vm->ferr, bc_flush_none, '\n');
424 	}
425 
426 #if BC_DEBUG
427 	bc_file_printf(&vm->ferr, "\n    %s:%d\n", file, fline);
428 #endif // BC_DEBUG
429 
430 	bc_file_puts(&vm->ferr, bc_flush_none, "\n");
431 
432 	// If flushing to stdout failed, try to print *that* error, as long as that
433 	// was not the error already.
434 	if (fout_s == BC_STATUS_ERROR_FATAL && e != BC_ERR_FATAL_IO_ERR)
435 	{
436 		bc_file_putchar(&vm->ferr, bc_flush_none, '\n');
437 		bc_file_puts(&vm->ferr, bc_flush_none,
438 		             vm->err_ids[bc_err_ids[BC_ERR_FATAL_IO_ERR]]);
439 		bc_file_putchar(&vm->ferr, bc_flush_none, ' ');
440 		bc_file_puts(&vm->ferr, bc_flush_none,
441 		             vm->err_msgs[BC_ERR_FATAL_IO_ERR]);
442 	}
443 
444 	s = bc_file_flushErr(&vm->ferr, bc_flush_err);
445 
446 #if !BC_ENABLE_MEMCHECK
447 
448 	// Because this function is called by a BC_NORETURN function when fatal
449 	// errors happen, we need to make sure to exit on fatal errors. This will
450 	// be faster anyway. This function *cannot jump when a fatal error occurs!*
451 	if (BC_ERR(id == BC_ERR_IDX_FATAL || fout_s == BC_STATUS_ERROR_FATAL ||
452 	           s == BC_STATUS_ERROR_FATAL))
453 	{
454 		exit((int) BC_STATUS_ERROR_FATAL);
455 	}
456 
457 #else // !BC_ENABLE_MEMCHECK
458 	if (BC_ERR(fout_s == BC_STATUS_ERROR_FATAL))
459 	{
460 		vm->status = (sig_atomic_t) fout_s;
461 	}
462 	else if (BC_ERR(s == BC_STATUS_ERROR_FATAL))
463 	{
464 		vm->status = (sig_atomic_t) s;
465 	}
466 	else
467 #endif // !BC_ENABLE_MEMCHECK
468 	{
469 		vm->status = (sig_atomic_t) (uchar) (id + 1);
470 	}
471 
472 	// Only jump if there is an error.
473 	if (BC_ERR(vm->status)) BC_JMP;
474 
475 	BC_SIG_TRYUNLOCK(lock);
476 }
477 
478 char*
479 bc_vm_getenv(const char* var)
480 {
481 	char* ret;
482 
483 #ifndef _WIN32
484 	ret = getenv(var);
485 #else // _WIN32
486 	_dupenv_s(&ret, NULL, var);
487 #endif // _WIN32
488 
489 	return ret;
490 }
491 
492 void
493 bc_vm_getenvFree(char* val)
494 {
495 	BC_UNUSED(val);
496 #ifdef _WIN32
497 	free(val);
498 #endif // _WIN32
499 }
500 
501 /**
502  * Sets a flag from an environment variable and the default.
503  * @param var   The environment variable.
504  * @param def   The default.
505  * @param flag  The flag to set.
506  */
507 static void
508 bc_vm_setenvFlag(const char* const var, int def, uint16_t flag)
509 {
510 	// Get the value.
511 	char* val = bc_vm_getenv(var);
512 
513 	// If there is no value...
514 	if (val == NULL)
515 	{
516 		// Set the default.
517 		if (def) vm->flags |= flag;
518 		else vm->flags &= ~(flag);
519 	}
520 	// Parse the value.
521 	else if (strtoul(val, NULL, 0)) vm->flags |= flag;
522 	else vm->flags &= ~(flag);
523 
524 	bc_vm_getenvFree(val);
525 }
526 
527 /**
528  * Parses the arguments in {B,D]C_ENV_ARGS.
529  * @param env_args_name  The environment variable to use.
530  * @param scale          A pointer to return the scale that the arguments set,
531  *                       if any.
532  * @param ibase          A pointer to return the ibase that the arguments set,
533  *                       if any.
534  * @param obase          A pointer to return the obase that the arguments set,
535  *                       if any.
536  */
537 static void
538 bc_vm_envArgs(const char* const env_args_name, BcBigDig* scale, BcBigDig* ibase,
539               BcBigDig* obase)
540 {
541 	char *env_args = bc_vm_getenv(env_args_name), *buf, *start;
542 	char instr = '\0';
543 
544 	BC_SIG_ASSERT_LOCKED;
545 
546 	if (env_args == NULL) return;
547 
548 		// Windows already allocates, so we don't need to.
549 #ifndef _WIN32
550 	start = buf = vm->env_args_buffer = bc_vm_strdup(env_args);
551 #else // _WIN32
552 	start = buf = vm->env_args_buffer = env_args;
553 #endif // _WIN32
554 
555 	assert(buf != NULL);
556 
557 	// Create two buffers for parsing. These need to stay throughout the entire
558 	// execution of bc, unfortunately, because of filenames that might be in
559 	// there.
560 	bc_vec_init(&vm->env_args, sizeof(char*), BC_DTOR_NONE);
561 	bc_vec_push(&vm->env_args, &env_args_name);
562 
563 	// While we haven't reached the end of the args...
564 	while (*buf)
565 	{
566 		// If we don't have whitespace...
567 		if (!isspace(*buf))
568 		{
569 			// If we have the start of a string...
570 			if (*buf == '"' || *buf == '\'')
571 			{
572 				// Set stuff appropriately.
573 				instr = *buf;
574 				buf += 1;
575 
576 				// Check for the empty string.
577 				if (*buf == instr)
578 				{
579 					instr = '\0';
580 					buf += 1;
581 					continue;
582 				}
583 			}
584 
585 			// Push the pointer to the args buffer.
586 			bc_vec_push(&vm->env_args, &buf);
587 
588 			// Parse the string.
589 			while (*buf &&
590 			       ((!instr && !isspace(*buf)) || (instr && *buf != instr)))
591 			{
592 				buf += 1;
593 			}
594 
595 			// If we did find the end of the string...
596 			if (*buf)
597 			{
598 				if (instr) instr = '\0';
599 
600 				// Reset stuff.
601 				*buf = '\0';
602 				buf += 1;
603 				start = buf;
604 			}
605 			else if (instr) bc_error(BC_ERR_FATAL_OPTION, 0, start);
606 		}
607 		// If we have whitespace, eat it.
608 		else buf += 1;
609 	}
610 
611 	// Make sure to push a NULL pointer at the end.
612 	buf = NULL;
613 	bc_vec_push(&vm->env_args, &buf);
614 
615 	// Parse the arguments.
616 	bc_args((int) vm->env_args.len - 1, bc_vec_item(&vm->env_args, 0), false,
617 	        scale, ibase, obase);
618 }
619 
620 /**
621  * Gets the {B,D}C_LINE_LENGTH.
622  * @param var  The environment variable to pull it from.
623  * @return     The line length.
624  */
625 static size_t
626 bc_vm_envLen(const char* var)
627 {
628 	char* lenv = bc_vm_getenv(var);
629 	size_t i, len = BC_NUM_PRINT_WIDTH;
630 	int num;
631 
632 	// Return the default with none.
633 	if (lenv == NULL) return len;
634 
635 	len = strlen(lenv);
636 
637 	// Figure out if it's a number.
638 	for (num = 1, i = 0; num && i < len; ++i)
639 	{
640 		num = isdigit(lenv[i]);
641 	}
642 
643 	// If it is a number...
644 	if (num)
645 	{
646 		// Parse it and clamp it if needed.
647 		len = (size_t) strtol(lenv, NULL, 10);
648 		if (len != 0)
649 		{
650 			len -= 1;
651 			if (len < 2 || len >= UINT16_MAX) len = BC_NUM_PRINT_WIDTH;
652 		}
653 	}
654 	// Set the default.
655 	else len = BC_NUM_PRINT_WIDTH;
656 
657 	bc_vm_getenvFree(lenv);
658 
659 	return len;
660 }
661 #endif // BC_ENABLE_LIBRARY
662 
663 void
664 bc_vm_shutdown(void)
665 {
666 	BC_SIG_ASSERT_LOCKED;
667 
668 #if BC_ENABLE_NLS
669 	if (vm->catalog != BC_VM_INVALID_CATALOG) catclose(vm->catalog);
670 #endif // BC_ENABLE_NLS
671 
672 #if !BC_ENABLE_LIBRARY
673 #if BC_ENABLE_HISTORY
674 	// This must always run to ensure that the terminal is back to normal, i.e.,
675 	// has raw mode disabled. But we should only do it if we did not have a bad
676 	// terminal because history was not initialized if it is a bad terminal.
677 	if (BC_TTY && !vm->history.badTerm) bc_history_free(&vm->history);
678 #endif // BC_ENABLE_HISTORY
679 #endif // !BC_ENABLE_LIBRARY
680 
681 #if BC_DEBUG || BC_ENABLE_MEMCHECK
682 #if !BC_ENABLE_LIBRARY
683 	bc_vec_free(&vm->env_args);
684 	free(vm->env_args_buffer);
685 	bc_vec_free(&vm->files);
686 	bc_vec_free(&vm->exprs);
687 
688 	if (BC_PARSE_IS_INITED(&vm->read_prs, &vm->prog))
689 	{
690 		bc_vec_free(&vm->read_buf);
691 		bc_parse_free(&vm->read_prs);
692 	}
693 
694 	bc_parse_free(&vm->prs);
695 	bc_program_free(&vm->prog);
696 
697 	bc_slabvec_free(&vm->slabs);
698 #endif // !BC_ENABLE_LIBRARY
699 
700 	bc_vm_freeTemps();
701 #endif // BC_DEBUG || BC_ENABLE_MEMCHECK
702 
703 #if !BC_ENABLE_LIBRARY
704 	// We always want to flush.
705 	bc_file_free(&vm->fout);
706 	bc_file_free(&vm->ferr);
707 #endif // !BC_ENABLE_LIBRARY
708 }
709 
710 void
711 bc_vm_addTemp(BcDig* num)
712 {
713 #if BC_ENABLE_LIBRARY
714 	BcVm* vm = bcl_getspecific();
715 #endif // BC_ENABLE_LIBRARY
716 
717 	BC_SIG_ASSERT_LOCKED;
718 
719 	// If we don't have room, just free.
720 	if (vm->temps_len == BC_VM_MAX_TEMPS) free(num);
721 	else
722 	{
723 		// Add to the buffer and length.
724 		vm->temps_buf[vm->temps_len] = num;
725 		vm->temps_len += 1;
726 	}
727 }
728 
729 BcDig*
730 bc_vm_takeTemp(void)
731 {
732 #if BC_ENABLE_LIBRARY
733 	BcVm* vm = bcl_getspecific();
734 #endif // BC_ENABLE_LIBRARY
735 
736 	BC_SIG_ASSERT_LOCKED;
737 
738 	if (!vm->temps_len) return NULL;
739 
740 	vm->temps_len -= 1;
741 
742 	return vm->temps_buf[vm->temps_len];
743 }
744 
745 BcDig*
746 bc_vm_getTemp(void)
747 {
748 #if BC_ENABLE_LIBRARY
749 	BcVm* vm = bcl_getspecific();
750 #endif // BC_ENABLE_LIBRARY
751 
752 	BC_SIG_ASSERT_LOCKED;
753 
754 	if (!vm->temps_len) return NULL;
755 
756 	return vm->temps_buf[vm->temps_len - 1];
757 }
758 
759 void
760 bc_vm_freeTemps(void)
761 {
762 	size_t i;
763 #if BC_ENABLE_LIBRARY
764 	BcVm* vm = bcl_getspecific();
765 #endif // BC_ENABLE_LIBRARY
766 
767 	BC_SIG_ASSERT_LOCKED;
768 
769 	if (!vm->temps_len) return;
770 
771 	// Free them all...
772 	for (i = 0; i < vm->temps_len; ++i)
773 	{
774 		free(vm->temps_buf[i]);
775 	}
776 
777 	vm->temps_len = 0;
778 }
779 
780 #if !BC_ENABLE_LIBRARY
781 
782 size_t
783 bc_vm_numDigits(size_t val)
784 {
785 	size_t digits = 0;
786 
787 	do
788 	{
789 		digits += 1;
790 		val /= 10;
791 	}
792 	while (val != 0);
793 
794 	return digits;
795 }
796 
797 #endif // !BC_ENABLE_LIBRARY
798 
799 inline size_t
800 bc_vm_arraySize(size_t n, size_t size)
801 {
802 	size_t res = n * size;
803 
804 	if (BC_ERR(BC_VM_MUL_OVERFLOW(n, size, res)))
805 	{
806 		bc_vm_fatalError(BC_ERR_FATAL_ALLOC_ERR);
807 	}
808 
809 	return res;
810 }
811 
812 inline size_t
813 bc_vm_growSize(size_t a, size_t b)
814 {
815 	size_t res = a + b;
816 
817 	if (BC_ERR(res >= SIZE_MAX || res < a))
818 	{
819 		bc_vm_fatalError(BC_ERR_FATAL_ALLOC_ERR);
820 	}
821 
822 	return res;
823 }
824 
825 void*
826 bc_vm_malloc(size_t n)
827 {
828 	void* ptr;
829 
830 	BC_SIG_ASSERT_LOCKED;
831 
832 	ptr = malloc(n);
833 
834 	if (BC_ERR(ptr == NULL))
835 	{
836 		bc_vm_freeTemps();
837 
838 		ptr = malloc(n);
839 
840 		if (BC_ERR(ptr == NULL)) bc_vm_fatalError(BC_ERR_FATAL_ALLOC_ERR);
841 	}
842 
843 	return ptr;
844 }
845 
846 void*
847 bc_vm_realloc(void* ptr, size_t n)
848 {
849 	void* temp;
850 
851 	BC_SIG_ASSERT_LOCKED;
852 
853 	temp = realloc(ptr, n);
854 
855 	if (BC_ERR(temp == NULL))
856 	{
857 		bc_vm_freeTemps();
858 
859 		temp = realloc(ptr, n);
860 
861 		if (BC_ERR(temp == NULL)) bc_vm_fatalError(BC_ERR_FATAL_ALLOC_ERR);
862 	}
863 
864 	return temp;
865 }
866 
867 char*
868 bc_vm_strdup(const char* str)
869 {
870 	char* s;
871 
872 	BC_SIG_ASSERT_LOCKED;
873 
874 	s = strdup(str);
875 
876 	if (BC_ERR(s == NULL))
877 	{
878 		bc_vm_freeTemps();
879 
880 		s = strdup(str);
881 
882 		if (BC_ERR(s == NULL)) bc_vm_fatalError(BC_ERR_FATAL_ALLOC_ERR);
883 	}
884 
885 	return s;
886 }
887 
888 #if !BC_ENABLE_LIBRARY
889 void
890 bc_vm_printf(const char* fmt, ...)
891 {
892 	va_list args;
893 #if BC_ENABLE_LIBRARY
894 	BcVm* vm = bcl_getspecific();
895 #else // BC_ENABLE_LIBRARY
896 	sig_atomic_t lock;
897 #endif // BC_ENABLE_LIBRARY
898 
899 	BC_SIG_TRYLOCK(lock);
900 
901 	va_start(args, fmt);
902 	bc_file_vprintf(&vm->fout, fmt, args);
903 	va_end(args);
904 
905 	vm->nchars = 0;
906 
907 	BC_SIG_TRYUNLOCK(lock);
908 }
909 #endif // !BC_ENABLE_LIBRARY
910 
911 void
912 bc_vm_putchar(int c, BcFlushType type)
913 {
914 #if BC_ENABLE_LIBRARY
915 	BcVm* vm = bcl_getspecific();
916 	bc_vec_pushByte(&vm->out, (uchar) c);
917 #else // BC_ENABLE_LIBRARY
918 	bc_file_putchar(&vm->fout, type, (uchar) c);
919 	vm->nchars = (c == '\n' ? 0 : vm->nchars + 1);
920 #endif // BC_ENABLE_LIBRARY
921 }
922 
923 #if !BC_ENABLE_LIBRARY
924 
925 #ifdef __OpenBSD__
926 
927 /**
928  * Aborts with a message. This should never be called because I have carefully
929  * made sure that the calls to pledge() and unveil() are correct, but it's here
930  * just in case.
931  * @param msg  The message to print.
932  */
933 BC_NORETURN static void
934 bc_abortm(const char* msg)
935 {
936 	bc_file_puts(&vm->ferr, bc_flush_none, msg);
937 	bc_file_puts(&vm->ferr, bc_flush_none, "; this is a bug");
938 	bc_file_flush(&vm->ferr, bc_flush_none);
939 	abort();
940 }
941 
942 void
943 bc_pledge(const char* promises, const char* execpromises)
944 {
945 	int r = pledge(promises, execpromises);
946 	if (r) bc_abortm("pledge() failed");
947 }
948 
949 #if BC_ENABLE_EXTRA_MATH
950 
951 /**
952  * A convenience and portability function for OpenBSD's unveil().
953  * @param path         The path.
954  * @param permissions  The permissions for the path.
955  */
956 static void
957 bc_unveil(const char* path, const char* permissions)
958 {
959 	int r = unveil(path, permissions);
960 	if (r) bc_abortm("unveil() failed");
961 }
962 
963 #endif // BC_ENABLE_EXTRA_MATH
964 
965 #else // __OpenBSD__
966 
967 void
968 bc_pledge(const char* promises, const char* execpromises)
969 {
970 	BC_UNUSED(promises);
971 	BC_UNUSED(execpromises);
972 }
973 
974 #if BC_ENABLE_EXTRA_MATH
975 static void
976 bc_unveil(const char* path, const char* permissions)
977 {
978 	BC_UNUSED(path);
979 	BC_UNUSED(permissions);
980 }
981 #endif // BC_ENABLE_EXTRA_MATH
982 
983 #endif // __OpenBSD__
984 
985 /**
986  * Cleans unneeded variables, arrays, functions, strings, and constants when
987  * done executing a line of stdin. This is to prevent memory usage growing
988  * without bound. This is an idea from busybox.
989  */
990 static void
991 bc_vm_clean(void)
992 {
993 	BcVec* fns = &vm->prog.fns;
994 	BcFunc* f = bc_vec_item(fns, BC_PROG_MAIN);
995 	BcInstPtr* ip = bc_vec_item(&vm->prog.stack, 0);
996 	bool good = ((vm->status && vm->status != BC_STATUS_QUIT) || vm->sig != 0);
997 
998 	BC_SIG_ASSERT_LOCKED;
999 
1000 	// If all is good, go ahead and reset.
1001 	if (good) bc_program_reset(&vm->prog);
1002 
1003 #if BC_ENABLED
1004 	// bc has this extra condition. If it not satisfied, it is in the middle of
1005 	// a parse.
1006 	if (good && BC_IS_BC) good = !BC_PARSE_NO_EXEC(&vm->prs);
1007 #endif // BC_ENABLED
1008 
1009 #if DC_ENABLED
1010 	// For dc, it is safe only when all of the results on the results stack are
1011 	// safe, which means that they are temporaries or other things that don't
1012 	// need strings or constants.
1013 	if (BC_IS_DC)
1014 	{
1015 		size_t i;
1016 
1017 		good = true;
1018 
1019 		for (i = 0; good && i < vm->prog.results.len; ++i)
1020 		{
1021 			BcResult* r = (BcResult*) bc_vec_item(&vm->prog.results, i);
1022 			good = BC_VM_SAFE_RESULT(r);
1023 		}
1024 	}
1025 #endif // DC_ENABLED
1026 
1027 	// If this condition is true, we can get rid of strings,
1028 	// constants, and code.
1029 	if (good && vm->prog.stack.len == 1 && ip->idx == f->code.len)
1030 	{
1031 		// XXX: Nothing can be popped in dc. Deal with it.
1032 
1033 #if BC_ENABLED
1034 		if (BC_IS_BC)
1035 		{
1036 			// XXX: you cannot delete strings, functions, or constants in bc.
1037 			// Deal with it.
1038 			bc_vec_popAll(&f->labels);
1039 		}
1040 #endif // BC_ENABLED
1041 
1042 		bc_vec_popAll(&f->code);
1043 
1044 		ip->idx = 0;
1045 	}
1046 }
1047 
1048 /**
1049  * Process a bunch of text.
1050  * @param text  The text to process.
1051  * @param mode  The mode to process in.
1052  */
1053 static void
1054 bc_vm_process(const char* text, BcMode mode)
1055 {
1056 	// Set up the parser.
1057 	bc_parse_text(&vm->prs, text, mode);
1058 
1059 	while (vm->prs.l.t != BC_LEX_EOF)
1060 	{
1061 		// Parsing requires a signal lock. We also don't parse everything; we
1062 		// want to execute as soon as possible for *everything*.
1063 		BC_SIG_LOCK;
1064 		vm->parse(&vm->prs);
1065 		BC_SIG_UNLOCK;
1066 
1067 		// Execute if possible.
1068 		if (BC_IS_DC || !BC_PARSE_NO_EXEC(&vm->prs)) bc_program_exec(&vm->prog);
1069 
1070 		assert(BC_IS_DC || vm->prog.results.len == 0);
1071 
1072 		// Flush in interactive mode.
1073 		if (BC_I) bc_file_flush(&vm->fout, bc_flush_save);
1074 	}
1075 }
1076 
1077 #if BC_ENABLED
1078 
1079 /**
1080  * Ends a series of if statements. This is to ensure that full parses happen
1081  * when a file finishes or stdin has no more data. Without this, bc thinks that
1082  * it cannot parse any further. But if we reach the end of a file or stdin has
1083  * no more data, we know we can add an empty else clause.
1084  */
1085 static void
1086 bc_vm_endif(void)
1087 {
1088 	bc_parse_endif(&vm->prs);
1089 	bc_program_exec(&vm->prog);
1090 }
1091 
1092 #endif // BC_ENABLED
1093 
1094 /**
1095  * Processes a file.
1096  * @param file  The filename.
1097  */
1098 static void
1099 bc_vm_file(const char* file)
1100 {
1101 	char* data = NULL;
1102 #if BC_ENABLE_LIBRARY
1103 	BcVm* vm = bcl_getspecific();
1104 #endif // BC_ENABLE_LIBRARY
1105 
1106 	assert(!vm->sig_pop);
1107 
1108 	vm->mode = BC_MODE_FILE;
1109 
1110 	// Set up the lexer.
1111 	bc_lex_file(&vm->prs.l, file);
1112 
1113 	BC_SIG_LOCK;
1114 
1115 	// Read the file.
1116 	data = bc_read_file(file);
1117 
1118 	assert(data != NULL);
1119 
1120 	BC_SETJMP_LOCKED(vm, err);
1121 
1122 	BC_SIG_UNLOCK;
1123 
1124 	// Process it.
1125 	bc_vm_process(data, BC_MODE_FILE);
1126 
1127 #if BC_ENABLED
1128 	// Make sure to end any open if statements.
1129 	if (BC_IS_BC) bc_vm_endif();
1130 #endif // BC_ENABLED
1131 
1132 err:
1133 
1134 	BC_SIG_MAYLOCK;
1135 
1136 	// Cleanup.
1137 	free(data);
1138 	bc_vm_clean();
1139 
1140 	// bc_program_reset(), called by bc_vm_clean(), resets the status.
1141 	// We want it to clear the sig_pop variable in case it was set.
1142 	if (vm->status == (sig_atomic_t) BC_STATUS_SUCCESS) BC_LONGJMP_STOP;
1143 
1144 	BC_LONGJMP_CONT(vm);
1145 }
1146 
1147 #if !BC_ENABLE_OSSFUZZ
1148 
1149 bool
1150 bc_vm_readLine(bool clear)
1151 {
1152 	BcStatus s;
1153 	bool good;
1154 
1155 	BC_SIG_ASSERT_NOT_LOCKED;
1156 
1157 	// Clear the buffer if desired.
1158 	if (clear) bc_vec_empty(&vm->buffer);
1159 
1160 	// Empty the line buffer.
1161 	bc_vec_empty(&vm->line_buf);
1162 
1163 	if (vm->eof) return false;
1164 
1165 	do
1166 	{
1167 		// bc_read_line() must always return either BC_STATUS_SUCCESS or
1168 		// BC_STATUS_EOF. Everything else, it and whatever it calls, must jump
1169 		// out instead.
1170 		s = bc_read_line(&vm->line_buf, ">>> ");
1171 		vm->eof = (s == BC_STATUS_EOF);
1172 	}
1173 	while (s == BC_STATUS_SUCCESS && !vm->eof && vm->line_buf.len < 1);
1174 
1175 	good = (vm->line_buf.len > 1);
1176 
1177 	// Concat if we found something.
1178 	if (good) bc_vec_concat(&vm->buffer, vm->line_buf.v);
1179 
1180 	return good;
1181 }
1182 
1183 /**
1184  * Processes text from stdin.
1185  */
1186 static void
1187 bc_vm_stdin(void)
1188 {
1189 	bool clear;
1190 
1191 #if BC_ENABLE_LIBRARY
1192 	BcVm* vm = bcl_getspecific();
1193 #endif // BC_ENABLE_LIBRARY
1194 
1195 	clear = true;
1196 	vm->mode = BC_MODE_STDIN;
1197 
1198 	// Set up the lexer.
1199 	bc_lex_file(&vm->prs.l, bc_program_stdin_name);
1200 
1201 	// These are global so that the lexers can access them, but they are
1202 	// allocated and freed in this function because they should only be used for
1203 	// stdin and expressions (they are used in bc_vm_exprs() as well). So they
1204 	// are tied to this function, really. Well, this and bc_vm_readLine(). These
1205 	// are the reasons that we have vm->is_stdin to tell the lexers if we are
1206 	// reading from stdin. Well, both lexers care. And the reason they care is
1207 	// so that if a comment or a string goes across multiple lines, the lexer
1208 	// can request more data from stdin until the comment or string is ended.
1209 	BC_SIG_LOCK;
1210 	bc_vec_init(&vm->buffer, sizeof(uchar), BC_DTOR_NONE);
1211 	bc_vec_init(&vm->line_buf, sizeof(uchar), BC_DTOR_NONE);
1212 	BC_SETJMP_LOCKED(vm, err);
1213 	BC_SIG_UNLOCK;
1214 
1215 // This label exists because errors can cause jumps to end up at the err label
1216 // below. If that happens, and the error should be cleared and execution
1217 // continue, then we need to jump back.
1218 restart:
1219 
1220 	// While we still read data from stdin.
1221 	while (bc_vm_readLine(clear))
1222 	{
1223 		size_t len = vm->buffer.len - 1;
1224 		const char* str = vm->buffer.v;
1225 
1226 		// We don't want to clear the buffer when the line ends with a backslash
1227 		// because a backslash newline is special in bc.
1228 		clear = (len < 2 || str[len - 2] != '\\' || str[len - 1] != '\n');
1229 		if (!clear) continue;
1230 
1231 		// Process the data.
1232 		bc_vm_process(vm->buffer.v, BC_MODE_STDIN);
1233 
1234 		if (vm->eof) break;
1235 		else
1236 		{
1237 			BC_SIG_LOCK;
1238 			bc_vm_clean();
1239 			BC_SIG_UNLOCK;
1240 		}
1241 	}
1242 
1243 #if BC_ENABLED
1244 	// End the if statements.
1245 	if (BC_IS_BC) bc_vm_endif();
1246 #endif // BC_ENABLED
1247 
1248 err:
1249 
1250 	BC_SIG_MAYLOCK;
1251 
1252 	// Cleanup.
1253 	bc_vm_clean();
1254 
1255 #if !BC_ENABLE_MEMCHECK
1256 	assert(vm->status != BC_STATUS_ERROR_FATAL);
1257 
1258 	vm->status = vm->status == BC_STATUS_QUIT || !BC_I ? vm->status :
1259 	                                                     BC_STATUS_SUCCESS;
1260 #else // !BC_ENABLE_MEMCHECK
1261 	vm->status = vm->status == BC_STATUS_ERROR_FATAL ||
1262 	                     vm->status == BC_STATUS_QUIT || !BC_I ?
1263 	                 vm->status :
1264 	                 BC_STATUS_SUCCESS;
1265 #endif // !BC_ENABLE_MEMCHECK
1266 
1267 	if (!vm->status && !vm->eof)
1268 	{
1269 		bc_vec_empty(&vm->buffer);
1270 		BC_LONGJMP_STOP;
1271 		BC_SIG_UNLOCK;
1272 		goto restart;
1273 	}
1274 
1275 #if BC_DEBUG
1276 	// Since these are tied to this function, free them here. We only free in
1277 	// debug mode because stdin is always the last thing read.
1278 	bc_vec_free(&vm->line_buf);
1279 	bc_vec_free(&vm->buffer);
1280 #endif // BC_DEBUG
1281 
1282 	BC_LONGJMP_CONT(vm);
1283 }
1284 
1285 #endif // BC_ENABLE_OSSFUZZ
1286 
1287 bool
1288 bc_vm_readBuf(bool clear)
1289 {
1290 	size_t len = vm->exprs.len - 1;
1291 	bool more;
1292 
1293 	BC_SIG_ASSERT_NOT_LOCKED;
1294 
1295 	// Clear the buffer if desired.
1296 	if (clear) bc_vec_empty(&vm->buffer);
1297 
1298 	// We want to pop the nul byte off because that's what bc_read_buf()
1299 	// expects.
1300 	bc_vec_pop(&vm->buffer);
1301 
1302 	// Read one line of expressions.
1303 	more = bc_read_buf(&vm->buffer, vm->exprs.v, &len);
1304 	bc_vec_pushByte(&vm->buffer, '\0');
1305 
1306 	return more;
1307 }
1308 
1309 static void
1310 bc_vm_exprs(void)
1311 {
1312 	bool clear;
1313 
1314 #if BC_ENABLE_LIBRARY
1315 	BcVm* vm = bcl_getspecific();
1316 #endif // BC_ENABLE_LIBRARY
1317 
1318 	clear = true;
1319 	vm->mode = BC_MODE_EXPRS;
1320 
1321 	// Prepare the lexer.
1322 	bc_lex_file(&vm->prs.l, bc_program_exprs_name);
1323 
1324 	// We initialize this so that the lexer can access it in the case that it
1325 	// needs more data for expressions, such as for a multiline string or
1326 	// comment. See the comment on the allocation of vm->buffer above in
1327 	// bc_vm_stdin() for more information.
1328 	BC_SIG_LOCK;
1329 	bc_vec_init(&vm->buffer, sizeof(uchar), BC_DTOR_NONE);
1330 	BC_SETJMP_LOCKED(vm, err);
1331 	BC_SIG_UNLOCK;
1332 
1333 	while (bc_vm_readBuf(clear))
1334 	{
1335 		size_t len = vm->buffer.len - 1;
1336 		const char* str = vm->buffer.v;
1337 
1338 		// We don't want to clear the buffer when the line ends with a backslash
1339 		// because a backslash newline is special in bc.
1340 		clear = (len < 2 || str[len - 2] != '\\' || str[len - 1] != '\n');
1341 		if (!clear) continue;
1342 
1343 		// Process the data.
1344 		bc_vm_process(vm->buffer.v, BC_MODE_EXPRS);
1345 	}
1346 
1347 	// If we were not supposed to clear, then we should process everything. This
1348 	// makes sure that errors get reported.
1349 	if (!clear) bc_vm_process(vm->buffer.v, BC_MODE_EXPRS);
1350 
1351 err:
1352 
1353 	BC_SIG_MAYLOCK;
1354 
1355 	// Cleanup.
1356 	bc_vm_clean();
1357 
1358 	// bc_program_reset(), called by bc_vm_clean(), resets the status.
1359 	// We want it to clear the sig_pop variable in case it was set.
1360 	if (vm->status == (sig_atomic_t) BC_STATUS_SUCCESS) BC_LONGJMP_STOP;
1361 
1362 	// Since this is tied to this function, free it here. We always free it here
1363 	// because bc_vm_stdin() may or may not use it later.
1364 	bc_vec_free(&vm->buffer);
1365 
1366 	BC_LONGJMP_CONT(vm);
1367 }
1368 
1369 #if BC_ENABLED
1370 
1371 /**
1372  * Loads a math library.
1373  * @param name  The name of the library.
1374  * @param text  The text of the source code.
1375  */
1376 static void
1377 bc_vm_load(const char* name, const char* text)
1378 {
1379 	bc_lex_file(&vm->prs.l, name);
1380 	bc_parse_text(&vm->prs, text, BC_MODE_FILE);
1381 
1382 	BC_SIG_LOCK;
1383 
1384 	while (vm->prs.l.t != BC_LEX_EOF)
1385 	{
1386 		vm->parse(&vm->prs);
1387 	}
1388 
1389 	BC_SIG_UNLOCK;
1390 }
1391 
1392 #endif // BC_ENABLED
1393 
1394 /**
1395  * Loads the default error messages.
1396  */
1397 static void
1398 bc_vm_defaultMsgs(void)
1399 {
1400 	size_t i;
1401 
1402 	// Load the error categories.
1403 	for (i = 0; i < BC_ERR_IDX_NELEMS + BC_ENABLED; ++i)
1404 	{
1405 		vm->err_ids[i] = bc_errs[i];
1406 	}
1407 
1408 	// Load the error messages.
1409 	for (i = 0; i < BC_ERR_NELEMS; ++i)
1410 	{
1411 		vm->err_msgs[i] = bc_err_msgs[i];
1412 	}
1413 }
1414 
1415 /**
1416  * Loads the error messages for the locale. If NLS is disabled, this just loads
1417  * the default messages.
1418  */
1419 static void
1420 bc_vm_gettext(void)
1421 {
1422 #if BC_ENABLE_NLS
1423 	uchar id = 0;
1424 	int set, msg = 1;
1425 	size_t i;
1426 
1427 	// If no locale, load the defaults.
1428 	if (vm->locale == NULL)
1429 	{
1430 		vm->catalog = BC_VM_INVALID_CATALOG;
1431 		bc_vm_defaultMsgs();
1432 		return;
1433 	}
1434 
1435 	vm->catalog = catopen(BC_MAINEXEC, NL_CAT_LOCALE);
1436 
1437 	// If no catalog, load the defaults.
1438 	if (vm->catalog == BC_VM_INVALID_CATALOG)
1439 	{
1440 		bc_vm_defaultMsgs();
1441 		return;
1442 	}
1443 
1444 	// Load the error categories.
1445 	for (set = 1; msg <= BC_ERR_IDX_NELEMS + BC_ENABLED; ++msg)
1446 	{
1447 		vm->err_ids[msg - 1] = catgets(vm->catalog, set, msg, bc_errs[msg - 1]);
1448 	}
1449 
1450 	i = 0;
1451 	id = bc_err_ids[i];
1452 
1453 	// Load the error messages. In order to understand this loop, you must know
1454 	// the order of messages and categories in the enum and in the locale files.
1455 	for (set = id + 2, msg = 1; i < BC_ERR_NELEMS; ++i, ++msg)
1456 	{
1457 		if (id != bc_err_ids[i])
1458 		{
1459 			msg = 1;
1460 			id = bc_err_ids[i];
1461 			set = id + 2;
1462 		}
1463 
1464 		vm->err_msgs[i] = catgets(vm->catalog, set, msg, bc_err_msgs[i]);
1465 	}
1466 #else // BC_ENABLE_NLS
1467 	bc_vm_defaultMsgs();
1468 #endif // BC_ENABLE_NLS
1469 }
1470 
1471 /**
1472  * Starts execution. Really, this is a function of historical accident; it could
1473  * probably be combined with bc_vm_boot(), but I don't care enough. Really, this
1474  * function starts when execution of bc or dc source code starts.
1475  */
1476 static void
1477 bc_vm_exec(void)
1478 {
1479 	size_t i;
1480 #if DC_ENABLED
1481 	bool has_file = false;
1482 #endif // DC_ENABLED
1483 
1484 #if BC_ENABLED
1485 	// Load the math libraries.
1486 	if (BC_IS_BC && (vm->flags & BC_FLAG_L))
1487 	{
1488 		// Can't allow redefinitions in the builtin library.
1489 		vm->no_redefine = true;
1490 
1491 		bc_vm_load(bc_lib_name, bc_lib);
1492 
1493 #if BC_ENABLE_EXTRA_MATH
1494 		if (!BC_IS_POSIX) bc_vm_load(bc_lib2_name, bc_lib2);
1495 #endif // BC_ENABLE_EXTRA_MATH
1496 
1497 		// Make sure to clear this.
1498 		vm->no_redefine = false;
1499 
1500 		// Execute to ensure that all is hunky dory. Without this, scale can be
1501 		// set improperly.
1502 		bc_program_exec(&vm->prog);
1503 	}
1504 #endif // BC_ENABLED
1505 
1506 	assert(!BC_ENABLE_OSSFUZZ || BC_EXPR_EXIT == 0);
1507 
1508 	// If there are expressions to execute...
1509 	if (vm->exprs.len)
1510 	{
1511 		// Process the expressions.
1512 		bc_vm_exprs();
1513 
1514 		// Sometimes, executing expressions means we need to quit.
1515 		if (vm->status != BC_STATUS_SUCCESS ||
1516 		    (!vm->no_exprs && vm->exit_exprs && BC_EXPR_EXIT))
1517 		{
1518 			return;
1519 		}
1520 	}
1521 
1522 	// Process files.
1523 	for (i = 0; i < vm->files.len; ++i)
1524 	{
1525 		char* path = *((char**) bc_vec_item(&vm->files, i));
1526 		if (!strcmp(path, "")) continue;
1527 #if DC_ENABLED
1528 		has_file = true;
1529 #endif // DC_ENABLED
1530 		bc_vm_file(path);
1531 
1532 		if (vm->status != BC_STATUS_SUCCESS) return;
1533 	}
1534 
1535 #if BC_ENABLE_EXTRA_MATH
1536 	// These are needed for the pseudo-random number generator.
1537 	bc_unveil("/dev/urandom", "r");
1538 	bc_unveil("/dev/random", "r");
1539 	bc_unveil(NULL, NULL);
1540 #endif // BC_ENABLE_EXTRA_MATH
1541 
1542 #if BC_ENABLE_HISTORY
1543 
1544 	// We need to keep tty if history is enabled, and we need to keep rpath for
1545 	// the times when we read from /dev/urandom.
1546 	if (BC_TTY && !vm->history.badTerm) bc_pledge(bc_pledge_end_history, NULL);
1547 	else
1548 #endif // BC_ENABLE_HISTORY
1549 	{
1550 		bc_pledge(bc_pledge_end, NULL);
1551 	}
1552 
1553 #if BC_ENABLE_AFL
1554 	// This is the thing that makes fuzzing with AFL++ so fast. If you move this
1555 	// back, you won't cause any problems, but fuzzing will slow down. If you
1556 	// move this forward, you won't fuzz anything because you will be skipping
1557 	// the reading from stdin.
1558 	__AFL_INIT();
1559 #endif // BC_ENABLE_AFL
1560 
1561 #if BC_ENABLE_OSSFUZZ
1562 
1563 	if (BC_VM_RUN_STDIN(has_file))
1564 	{
1565 		// XXX: Yes, this is a hack to run the fuzzer for OSS-Fuzz, but it
1566 		// works.
1567 		bc_vm_load("<stdin>", (const char*) bc_fuzzer_data);
1568 	}
1569 
1570 #else // BC_ENABLE_OSSFUZZ
1571 
1572 	// Execute from stdin. bc always does.
1573 	if (BC_VM_RUN_STDIN(has_file)) bc_vm_stdin();
1574 
1575 #endif // BC_ENABLE_OSSFUZZ
1576 }
1577 
1578 BcStatus
1579 bc_vm_boot(int argc, const char* argv[])
1580 {
1581 	int ttyin, ttyout, ttyerr;
1582 	bool tty;
1583 	const char* const env_len = BC_VM_LINE_LENGTH_STR;
1584 	const char* const env_args = BC_VM_ENV_ARGS_STR;
1585 	const char* const env_exit = BC_VM_EXPR_EXIT_STR;
1586 	const char* const env_clamp = BC_VM_DIGIT_CLAMP_STR;
1587 	int env_exit_def = BC_VM_EXPR_EXIT_DEF;
1588 	int env_clamp_def = BC_VM_DIGIT_CLAMP_DEF;
1589 	BcBigDig scale = BC_NUM_BIGDIG_MAX;
1590 	BcBigDig env_scale = BC_NUM_BIGDIG_MAX;
1591 	BcBigDig ibase = BC_NUM_BIGDIG_MAX;
1592 	BcBigDig env_ibase = BC_NUM_BIGDIG_MAX;
1593 	BcBigDig obase = BC_NUM_BIGDIG_MAX;
1594 	BcBigDig env_obase = BC_NUM_BIGDIG_MAX;
1595 
1596 	// We need to know which of stdin, stdout, and stderr are tty's.
1597 	ttyin = isatty(STDIN_FILENO);
1598 	ttyout = isatty(STDOUT_FILENO);
1599 	ttyerr = isatty(STDERR_FILENO);
1600 	tty = (ttyin != 0 && ttyout != 0 && ttyerr != 0);
1601 
1602 	vm->flags |= ttyin ? BC_FLAG_TTYIN : 0;
1603 	vm->flags |= tty ? BC_FLAG_TTY : 0;
1604 	vm->flags |= ttyin && ttyout ? BC_FLAG_I : 0;
1605 
1606 	// Set up signals.
1607 	bc_vm_sigaction();
1608 
1609 	// Initialize some vm stuff. This is separate to make things easier for the
1610 	// library.
1611 	bc_vm_init();
1612 
1613 	// Explicitly set this in case NULL isn't all zeroes.
1614 	vm->file = NULL;
1615 
1616 	// Set the error messages.
1617 	bc_vm_gettext();
1618 
1619 #if BC_ENABLE_LINE_LIB
1620 
1621 	// Initialize the output file buffers.
1622 	bc_file_init(&vm->ferr, stderr, true);
1623 	bc_file_init(&vm->fout, stdout, false);
1624 
1625 	// Set the input buffer.
1626 	vm->buf = output_bufs;
1627 
1628 #else // BC_ENABLE_LINE_LIB
1629 
1630 	// Initialize the output file buffers. They each take portions of the global
1631 	// buffer. stdout gets more because it will probably have more data.
1632 	bc_file_init(&vm->ferr, STDERR_FILENO, output_bufs + BC_VM_STDOUT_BUF_SIZE,
1633 	             BC_VM_STDERR_BUF_SIZE, true);
1634 	bc_file_init(&vm->fout, STDOUT_FILENO, output_bufs, BC_VM_STDOUT_BUF_SIZE,
1635 	             false);
1636 
1637 	// Set the input buffer to the rest of the global buffer.
1638 	vm->buf = output_bufs + BC_VM_STDOUT_BUF_SIZE + BC_VM_STDERR_BUF_SIZE;
1639 #endif // BC_ENABLE_LINE_LIB
1640 
1641 	// Set the line length by environment variable.
1642 	vm->line_len = (uint16_t) bc_vm_envLen(env_len);
1643 
1644 	bc_vm_setenvFlag(env_exit, env_exit_def, BC_FLAG_EXPR_EXIT);
1645 	bc_vm_setenvFlag(env_clamp, env_clamp_def, BC_FLAG_DIGIT_CLAMP);
1646 
1647 	// Clear the files and expressions vectors, just in case. This marks them as
1648 	// *not* allocated.
1649 	bc_vec_clear(&vm->files);
1650 	bc_vec_clear(&vm->exprs);
1651 
1652 #if !BC_ENABLE_LIBRARY
1653 
1654 	// Initialize the slab vector.
1655 	bc_slabvec_init(&vm->slabs);
1656 
1657 #endif // !BC_ENABLE_LIBRARY
1658 
1659 	// Initialize the program and main parser. These have to be in this order
1660 	// because the program has to be initialized first, since a pointer to it is
1661 	// passed to the parser.
1662 	bc_program_init(&vm->prog);
1663 	bc_parse_init(&vm->prs, &vm->prog, BC_PROG_MAIN);
1664 
1665 	// Set defaults.
1666 	vm->flags |= BC_TTY ? BC_FLAG_P | BC_FLAG_R : 0;
1667 	vm->flags |= BC_I ? BC_FLAG_Q : 0;
1668 
1669 #if BC_ENABLED
1670 	if (BC_IS_BC)
1671 	{
1672 		// bc checks this environment variable to see if it should run in
1673 		// standard mode.
1674 		char* var = bc_vm_getenv("POSIXLY_CORRECT");
1675 
1676 		vm->flags |= BC_FLAG_S * (var != NULL);
1677 		bc_vm_getenvFree(var);
1678 
1679 		// Set whether we print the banner or not.
1680 		if (BC_I) bc_vm_setenvFlag("BC_BANNER", BC_DEFAULT_BANNER, BC_FLAG_Q);
1681 	}
1682 #endif // BC_ENABLED
1683 
1684 	// Are we in TTY mode?
1685 	if (BC_TTY)
1686 	{
1687 		const char* const env_tty = BC_VM_TTY_MODE_STR;
1688 		int env_tty_def = BC_VM_TTY_MODE_DEF;
1689 		const char* const env_prompt = BC_VM_PROMPT_STR;
1690 		int env_prompt_def = BC_VM_PROMPT_DEF;
1691 
1692 		// Set flags for TTY mode and prompt.
1693 		bc_vm_setenvFlag(env_tty, env_tty_def, BC_FLAG_TTY);
1694 		bc_vm_setenvFlag(env_prompt, tty ? env_prompt_def : 0, BC_FLAG_P);
1695 
1696 #if BC_ENABLE_HISTORY
1697 		// If TTY mode is used, activate history.
1698 		if (BC_TTY) bc_history_init(&vm->history);
1699 #endif // BC_ENABLE_HISTORY
1700 	}
1701 
1702 	// Process environment and command-line arguments.
1703 	bc_vm_envArgs(env_args, &env_scale, &env_ibase, &env_obase);
1704 	bc_args(argc, argv, true, &scale, &ibase, &obase);
1705 
1706 	// This section is here because we don't want the math library to stomp on
1707 	// the user's given value for scale. And we don't want ibase affecting how
1708 	// the scale is interpreted. Also, it's sectioned off just for this comment.
1709 	{
1710 		BC_SIG_UNLOCK;
1711 
1712 		scale = scale == BC_NUM_BIGDIG_MAX ? env_scale : scale;
1713 #if BC_ENABLED
1714 		// Assign the library value only if it is used and no value was set.
1715 		scale = scale == BC_NUM_BIGDIG_MAX && BC_L ? 20 : scale;
1716 #endif // BC_ENABLED
1717 		obase = obase == BC_NUM_BIGDIG_MAX ? env_obase : obase;
1718 		ibase = ibase == BC_NUM_BIGDIG_MAX ? env_ibase : ibase;
1719 
1720 		if (scale != BC_NUM_BIGDIG_MAX)
1721 		{
1722 			bc_program_assignBuiltin(&vm->prog, true, false, scale);
1723 		}
1724 
1725 		if (obase != BC_NUM_BIGDIG_MAX)
1726 		{
1727 			bc_program_assignBuiltin(&vm->prog, false, true, obase);
1728 		}
1729 
1730 		// This is last to avoid it affecting the value of the others.
1731 		if (ibase != BC_NUM_BIGDIG_MAX)
1732 		{
1733 			bc_program_assignBuiltin(&vm->prog, false, false, ibase);
1734 		}
1735 
1736 		BC_SIG_LOCK;
1737 	}
1738 
1739 	// If we are in interactive mode...
1740 	if (BC_I)
1741 	{
1742 		const char* const env_sigint = BC_VM_SIGINT_RESET_STR;
1743 		int env_sigint_def = BC_VM_SIGINT_RESET_DEF;
1744 
1745 		// Set whether we reset on SIGINT or not.
1746 		bc_vm_setenvFlag(env_sigint, env_sigint_def, BC_FLAG_SIGINT);
1747 	}
1748 
1749 #if BC_ENABLED
1750 	// Disable global stacks in POSIX mode.
1751 	if (BC_IS_POSIX) vm->flags &= ~(BC_FLAG_G);
1752 
1753 	// Print the banner if allowed. We have to be in bc, in interactive mode,
1754 	// and not be quieted by command-line option or environment variable.
1755 	if (BC_IS_BC && BC_I && (vm->flags & BC_FLAG_Q))
1756 	{
1757 		bc_vm_info(NULL);
1758 		bc_file_putchar(&vm->fout, bc_flush_none, '\n');
1759 		bc_file_flush(&vm->fout, bc_flush_none);
1760 	}
1761 #endif // BC_ENABLED
1762 
1763 	BC_SIG_UNLOCK;
1764 
1765 	// Start executing.
1766 	bc_vm_exec();
1767 
1768 	BC_SIG_LOCK;
1769 
1770 	// Exit.
1771 	return (BcStatus) vm->status;
1772 }
1773 #endif // !BC_ENABLE_LIBRARY
1774 
1775 void
1776 bc_vm_init(void)
1777 {
1778 #if BC_ENABLE_LIBRARY
1779 	BcVm* vm = bcl_getspecific();
1780 #endif // BC_ENABLE_LIBRARY
1781 
1782 	BC_SIG_ASSERT_LOCKED;
1783 
1784 #if !BC_ENABLE_LIBRARY
1785 	// Set up the constant zero.
1786 	bc_num_setup(&vm->zero, vm->zero_num, BC_VM_ONE_CAP);
1787 #endif // !BC_ENABLE_LIBRARY
1788 
1789 	// Set up more constant BcNum's.
1790 	bc_num_setup(&vm->one, vm->one_num, BC_VM_ONE_CAP);
1791 	bc_num_one(&vm->one);
1792 
1793 	// Set up more constant BcNum's.
1794 	// NOLINTNEXTLINE
1795 	memcpy(vm->max_num, bc_num_bigdigMax,
1796 	       bc_num_bigdigMax_size * sizeof(BcDig));
1797 	// NOLINTNEXTLINE
1798 	memcpy(vm->max2_num, bc_num_bigdigMax2,
1799 	       bc_num_bigdigMax2_size * sizeof(BcDig));
1800 	bc_num_setup(&vm->max, vm->max_num, BC_NUM_BIGDIG_LOG10);
1801 	bc_num_setup(&vm->max2, vm->max2_num, BC_NUM_BIGDIG_LOG10);
1802 	vm->max.len = bc_num_bigdigMax_size;
1803 	vm->max2.len = bc_num_bigdigMax2_size;
1804 
1805 	// Set up the maxes for the globals.
1806 	vm->maxes[BC_PROG_GLOBALS_IBASE] = BC_NUM_MAX_POSIX_IBASE;
1807 	vm->maxes[BC_PROG_GLOBALS_OBASE] = BC_MAX_OBASE;
1808 	vm->maxes[BC_PROG_GLOBALS_SCALE] = BC_MAX_SCALE;
1809 
1810 #if BC_ENABLE_EXTRA_MATH
1811 	vm->maxes[BC_PROG_MAX_RAND] = ((BcRand) 0) - 1;
1812 #endif // BC_ENABLE_EXTRA_MATH
1813 
1814 #if BC_ENABLED
1815 #if !BC_ENABLE_LIBRARY
1816 	// bc has a higher max ibase when it's not in POSIX mode.
1817 	if (BC_IS_BC && !BC_IS_POSIX)
1818 #endif // !BC_ENABLE_LIBRARY
1819 	{
1820 		vm->maxes[BC_PROG_GLOBALS_IBASE] = BC_NUM_MAX_IBASE;
1821 	}
1822 #endif // BC_ENABLED
1823 }
1824 
1825 #if BC_ENABLE_LIBRARY
1826 void
1827 bc_vm_atexit(void)
1828 {
1829 #if BC_DEBUG
1830 #if BC_ENABLE_LIBRARY
1831 	BcVm* vm = bcl_getspecific();
1832 #endif // BC_ENABLE_LIBRARY
1833 #endif // BC_DEBUG
1834 
1835 	bc_vm_shutdown();
1836 
1837 #if BC_DEBUG
1838 	bc_vec_free(&vm->jmp_bufs);
1839 #endif // BC_DEBUG
1840 }
1841 #else // BC_ENABLE_LIBRARY
1842 BcStatus
1843 bc_vm_atexit(BcStatus status)
1844 {
1845 	// Set the status correctly.
1846 	BcStatus s = BC_STATUS_IS_ERROR(status) ? status : BC_STATUS_SUCCESS;
1847 
1848 	bc_vm_shutdown();
1849 
1850 #if BC_DEBUG
1851 	bc_vec_free(&vm->jmp_bufs);
1852 #endif // BC_DEBUG
1853 
1854 	return s;
1855 }
1856 #endif // BC_ENABLE_LIBRARY
1857