xref: /freebsd/contrib/bc/src/vm.c (revision b0ee263dbd3552d5b1776be0efc1c2d105f873b1)
1 /*
2  * *****************************************************************************
3  *
4  * Copyright (c) 2018-2020 Gavin D. Howard and contributors.
5  *
6  * All rights reserved.
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 <sys/types.h>
49 #include <unistd.h>
50 
51 #else // _WIN32
52 
53 #define WIN32_LEAN_AND_MEAN
54 #include <windows.h>
55 #include <io.h>
56 
57 #endif // _WIN32
58 
59 #include <status.h>
60 #include <vector.h>
61 #include <args.h>
62 #include <vm.h>
63 #include <read.h>
64 #include <bc.h>
65 
66 #if BC_DEBUG_CODE
67 BC_NORETURN void bc_vm_jmp(const char* f) {
68 #else // BC_DEBUG_CODE
69 BC_NORETURN void bc_vm_jmp(void) {
70 #endif
71 
72 	assert(vm.status != BC_STATUS_SUCCESS || vm.sig);
73 
74 	BC_SIG_MAYLOCK;
75 
76 #if BC_DEBUG_CODE
77 	bc_file_puts(&vm.ferr, "Longjmp: ");
78 	bc_file_puts(&vm.ferr, f);
79 	bc_file_putchar(&vm.ferr, '\n');
80 	bc_file_flush(&vm.ferr);
81 #endif // BC_DEBUG_CODE
82 
83 #ifndef NDEBUG
84 	assert(vm.jmp_bufs.len - (size_t) vm.sig_pop);
85 #endif // NDEBUG
86 
87 	if (vm.sig_pop) bc_vec_pop(&vm.jmp_bufs);
88 	else vm.sig_pop = 1;
89 
90 	siglongjmp(*((sigjmp_buf*) bc_vec_top(&vm.jmp_bufs)), 1);
91 }
92 
93 static void bc_vm_sig(int sig) {
94 
95 	// There is already a signal in flight.
96 	if (vm.status == (sig_atomic_t) BC_STATUS_QUIT || vm.sig) {
97 		if (!BC_TTY || sig != SIGINT) vm.status = BC_STATUS_QUIT;
98 		return;
99 	}
100 
101 	if (BC_TTY && sig == SIGINT) {
102 
103 		int err = errno;
104 
105 		if (write(STDOUT_FILENO, vm.sigmsg, vm.siglen) != (ssize_t) vm.siglen)
106 			vm.status = BC_STATUS_ERROR_FATAL;
107 		else vm.sig = 1;
108 
109 		errno = err;
110 	}
111 	else vm.status = BC_STATUS_QUIT;
112 
113 	assert(vm.jmp_bufs.len);
114 
115 	if (!vm.sig_lock) BC_VM_JMP;
116 }
117 
118 void bc_vm_info(const char* const help) {
119 
120 	BC_SIG_ASSERT_LOCKED;
121 
122 	bc_file_puts(&vm.fout, vm.name);
123 	bc_file_putchar(&vm.fout, ' ');
124 	bc_file_puts(&vm.fout, BC_VERSION);
125 	bc_file_putchar(&vm.fout, '\n');
126 	bc_file_puts(&vm.fout, bc_copyright);
127 
128 	if (help) {
129 		bc_file_putchar(&vm.fout, '\n');
130 		bc_file_printf(&vm.fout, help, vm.name, vm.name);
131 	}
132 
133 	bc_file_flush(&vm.fout);
134 }
135 
136 void bc_vm_error(BcError e, size_t line, ...) {
137 
138 	BcStatus s;
139 	va_list args;
140 	uchar id = bc_err_ids[e];
141 	const char* err_type = vm.err_ids[id];
142 	sig_atomic_t lock;
143 
144 	assert(e < BC_ERROR_NELEMS);
145 	assert(!vm.sig_pop);
146 
147 #if BC_ENABLED
148 	if (!BC_S && e >= BC_ERROR_POSIX_START) {
149 		if (BC_W) {
150 			// Make sure to not return an error.
151 			id = UCHAR_MAX;
152 			err_type = vm.err_ids[BC_ERR_IDX_WARN];
153 		}
154 		else return;
155 	}
156 #endif // BC_ENABLED
157 
158 	BC_SIG_TRYLOCK(lock);
159 
160 	// Make sure all of stdout is written first.
161 	s = bc_file_flushErr(&vm.fout);
162 
163 	if (BC_ERR(s == BC_STATUS_ERROR_FATAL)) {
164 		vm.status = (sig_atomic_t) s;
165 		BC_VM_JMP;
166 	}
167 
168 	va_start(args, line);
169 	bc_file_putchar(&vm.ferr, '\n');
170 	bc_file_puts(&vm.ferr, err_type);
171 	bc_file_putchar(&vm.ferr, ' ');
172 	bc_file_vprintf(&vm.ferr, vm.err_msgs[e], args);
173 	va_end(args);
174 
175 	if (BC_NO_ERR(vm.file)) {
176 
177 		// This is the condition for parsing vs runtime.
178 		// If line is not 0, it is parsing.
179 		if (line) {
180 			bc_file_puts(&vm.ferr, "\n    ");
181 			bc_file_puts(&vm.ferr, vm.file);
182 			bc_file_printf(&vm.ferr, bc_err_line, line);
183 		}
184 		else {
185 
186 			BcInstPtr *ip = bc_vec_item_rev(&vm.prog.stack, 0);
187 			BcFunc *f = bc_vec_item(&vm.prog.fns, ip->func);
188 
189 			bc_file_puts(&vm.ferr, "\n    ");
190 			bc_file_puts(&vm.ferr, vm.func_header);
191 			bc_file_putchar(&vm.ferr, ' ');
192 			bc_file_puts(&vm.ferr, f->name);
193 
194 			if (BC_IS_BC && ip->func != BC_PROG_MAIN &&
195 			    ip->func != BC_PROG_READ)
196 			{
197 				bc_file_puts(&vm.ferr, "()");
198 			}
199 		}
200 	}
201 
202 	bc_file_puts(&vm.ferr, "\n\n");
203 
204 	s = bc_file_flushErr(&vm.ferr);
205 
206 	vm.status = s == BC_STATUS_ERROR_FATAL ?
207 	    (sig_atomic_t) s : (sig_atomic_t) (uchar) (id + 1);
208 
209 	if (BC_ERR(vm.status)) BC_VM_JMP;
210 
211 	BC_SIG_TRYUNLOCK(lock);
212 }
213 
214 static void bc_vm_envArgs(const char* const env_args_name) {
215 
216 	char *env_args = getenv(env_args_name), *buf, *start;
217 	char instr = '\0';
218 
219 	BC_SIG_ASSERT_LOCKED;
220 
221 	if (env_args == NULL) return;
222 
223 	start = buf = vm.env_args_buffer = bc_vm_strdup(env_args);
224 
225 	assert(buf != NULL);
226 
227 	bc_vec_init(&vm.env_args, sizeof(char*), NULL);
228 	bc_vec_push(&vm.env_args, &env_args_name);
229 
230 	while (*buf) {
231 
232 		if (!isspace(*buf)) {
233 
234 			if (*buf == '"' || *buf == '\'') {
235 
236 				instr = *buf;
237 				buf += 1;
238 
239 				if (*buf == instr) {
240 					instr = '\0';
241 					buf += 1;
242 					continue;
243 				}
244 			}
245 
246 			bc_vec_push(&vm.env_args, &buf);
247 
248 			while (*buf && ((!instr && !isspace(*buf)) ||
249 			                (instr && *buf != instr)))
250 			{
251 				buf += 1;
252 			}
253 
254 			if (*buf) {
255 
256 				if (instr) instr = '\0';
257 
258 				*buf = '\0';
259 				buf += 1;
260 				start = buf;
261 			}
262 			else if (instr) bc_vm_error(BC_ERROR_FATAL_OPTION, 0, start);
263 		}
264 		else buf += 1;
265 	}
266 
267 	// Make sure to push a NULL pointer at the end.
268 	buf = NULL;
269 	bc_vec_push(&vm.env_args, &buf);
270 
271 	bc_args((int) vm.env_args.len - 1, bc_vec_item(&vm.env_args, 0));
272 }
273 
274 static size_t bc_vm_envLen(const char *var) {
275 
276 	char *lenv = getenv(var);
277 	size_t i, len = BC_NUM_PRINT_WIDTH;
278 	int num;
279 
280 	if (lenv == NULL) return len;
281 
282 	len = strlen(lenv);
283 
284 	for (num = 1, i = 0; num && i < len; ++i) num = isdigit(lenv[i]);
285 
286 	if (num) {
287 		len = (size_t) atoi(lenv) - 1;
288 		if (len < 2 || len >= UINT16_MAX) len = BC_NUM_PRINT_WIDTH;
289 	}
290 	else len = BC_NUM_PRINT_WIDTH;
291 
292 	return len;
293 }
294 
295 void bc_vm_shutdown(void) {
296 
297 	BC_SIG_ASSERT_LOCKED;
298 
299 #if BC_ENABLE_NLS
300 	if (vm.catalog != BC_VM_INVALID_CATALOG) catclose(vm.catalog);
301 #endif // BC_ENABLE_NLS
302 
303 #if BC_ENABLE_HISTORY
304 	// This must always run to ensure that the terminal is back to normal.
305 	if (BC_TTY) bc_history_free(&vm.history);
306 #endif // BC_ENABLE_HISTORY
307 
308 #ifndef NDEBUG
309 	bc_vec_free(&vm.env_args);
310 	free(vm.env_args_buffer);
311 	bc_vec_free(&vm.files);
312 	bc_vec_free(&vm.exprs);
313 
314 	bc_program_free(&vm.prog);
315 	bc_parse_free(&vm.prs);
316 
317 	{
318 		size_t i;
319 		for (i = 0; i < vm.temps.len; ++i)
320 			free(((BcNum*) bc_vec_item(&vm.temps, i))->num);
321 
322 		bc_vec_free(&vm.temps);
323 	}
324 #endif // NDEBUG
325 
326 	bc_file_free(&vm.fout);
327 	bc_file_free(&vm.ferr);
328 }
329 
330 size_t bc_vm_arraySize(size_t n, size_t size) {
331 	size_t res = n * size;
332 	if (BC_ERR(res >= SIZE_MAX || (n != 0 && res / n != size)))
333 		bc_vm_err(BC_ERROR_FATAL_ALLOC_ERR);
334 	return res;
335 }
336 
337 size_t bc_vm_growSize(size_t a, size_t b) {
338 	size_t res = a + b;
339 	if (BC_ERR(res >= SIZE_MAX || res < a || res < b))
340 		bc_vm_err(BC_ERROR_FATAL_ALLOC_ERR);
341 	return res;
342 }
343 
344 void* bc_vm_malloc(size_t n) {
345 
346 	void* ptr;
347 
348 	BC_SIG_ASSERT_LOCKED;
349 
350 	ptr = malloc(n);
351 
352 	if (BC_ERR(ptr == NULL)) bc_vm_err(BC_ERROR_FATAL_ALLOC_ERR);
353 
354 	return ptr;
355 }
356 
357 void* bc_vm_realloc(void *ptr, size_t n) {
358 
359 	void* temp;
360 
361 	BC_SIG_ASSERT_LOCKED;
362 
363 	temp = realloc(ptr, n);
364 
365 	if (BC_ERR(temp == NULL)) bc_vm_err(BC_ERROR_FATAL_ALLOC_ERR);
366 
367 	return temp;
368 }
369 
370 char* bc_vm_strdup(const char *str) {
371 
372 	char *s;
373 
374 	BC_SIG_ASSERT_LOCKED;
375 
376 	s = strdup(str);
377 
378 	if (BC_ERR(!s)) bc_vm_err(BC_ERROR_FATAL_ALLOC_ERR);
379 
380 	return s;
381 }
382 
383 void bc_vm_printf(const char *fmt, ...) {
384 
385 	va_list args;
386 
387 	BC_SIG_LOCK;
388 
389 	va_start(args, fmt);
390 	bc_file_vprintf(&vm.fout, fmt, args);
391 	va_end(args);
392 
393 	vm.nchars = 0;
394 
395 	BC_SIG_UNLOCK;
396 }
397 
398 void bc_vm_putchar(int c) {
399 	bc_file_putchar(&vm.fout, (uchar) c);
400 	vm.nchars = (c == '\n' ? 0 : vm.nchars + 1);
401 }
402 
403 static void bc_vm_clean(void) {
404 
405 	BcProgram *prog = &vm.prog;
406 	BcVec *fns = &prog->fns;
407 	BcFunc *f = bc_vec_item(fns, BC_PROG_MAIN);
408 	BcInstPtr *ip = bc_vec_item(&prog->stack, 0);
409 	bool good = (vm.status && vm.status != BC_STATUS_QUIT);
410 
411 	if (good) bc_program_reset(&vm.prog);
412 
413 #if BC_ENABLED
414 	if (good && BC_IS_BC) good = !BC_PARSE_NO_EXEC(&vm.prs);
415 #endif // BC_ENABLED
416 
417 #if DC_ENABLED
418 	if (!BC_IS_BC) {
419 
420 		size_t i;
421 
422 		for (i = 0; i < vm.prog.vars.len; ++i) {
423 			BcVec *arr = bc_vec_item(&vm.prog.vars, i);
424 			BcNum *n = bc_vec_top(arr);
425 			if (arr->len != 1 || BC_PROG_STR(n)) break;
426 		}
427 
428 		if (i == vm.prog.vars.len) {
429 
430 			for (i = 0; i < vm.prog.arrs.len; ++i) {
431 
432 				BcVec *arr = bc_vec_item(&vm.prog.arrs, i);
433 				size_t j;
434 
435 				assert(arr->len == 1);
436 
437 				arr = bc_vec_top(arr);
438 
439 				for (j = 0; j < arr->len; ++j) {
440 					BcNum *n = bc_vec_item(arr, j);
441 					if (BC_PROG_STR(n)) break;
442 				}
443 
444 				if (j != arr->len) break;
445 			}
446 
447 			good = (i == vm.prog.arrs.len);
448 		}
449 	}
450 #endif // DC_ENABLED
451 
452 	// If this condition is true, we can get rid of strings,
453 	// constants, and code. This is an idea from busybox.
454 	if (good && prog->stack.len == 1 && !prog->results.len &&
455 	    ip->idx == f->code.len)
456 	{
457 #if BC_ENABLED
458 		if (BC_IS_BC) {
459 			bc_vec_npop(&f->labels, f->labels.len);
460 			bc_vec_npop(&f->strs, f->strs.len);
461 		}
462 #endif // BC_ENABLED
463 		bc_vec_npop(&f->consts, f->consts.len);
464 		bc_vec_npop(&f->code, f->code.len);
465 		ip->idx = 0;
466 	}
467 }
468 
469 static void bc_vm_process(const char *text, bool is_stdin) {
470 
471 	bc_parse_text(&vm.prs, text);
472 
473 	do {
474 
475 #if BC_ENABLED
476 		if (vm.prs.l.t == BC_LEX_KW_DEFINE) vm.parse(&vm.prs);
477 #endif // BC_ENABLED
478 
479 		while (BC_PARSE_CAN_PARSE(vm.prs)) vm.parse(&vm.prs);
480 
481 #if BC_ENABLED
482 		if (BC_IS_BC) {
483 
484 			uint16_t *flags = BC_PARSE_TOP_FLAG_PTR(&vm.prs);
485 
486 			if (!is_stdin && vm.prs.flags.len == 1 &&
487 			    *flags == BC_PARSE_FLAG_IF_END)
488 			{
489 				bc_parse_noElse(&vm.prs);
490 			}
491 
492 			if (BC_PARSE_NO_EXEC(&vm.prs)) return;
493 		}
494 #endif // BC_ENABLED
495 
496 		bc_program_exec(&vm.prog);
497 		if (BC_I) bc_file_flush(&vm.fout);
498 
499 	} while (vm.prs.l.t != BC_LEX_EOF);
500 }
501 
502 static void bc_vm_file(const char *file) {
503 
504 	char *data = NULL;
505 
506 	assert(!vm.sig_pop);
507 
508 	bc_lex_file(&vm.prs.l, file);
509 
510 	BC_SIG_LOCK;
511 
512 	bc_read_file(file, &data);
513 
514 	BC_SETJMP_LOCKED(err);
515 
516 	BC_SIG_UNLOCK;
517 
518 	bc_vm_process(data, false);
519 
520 #if BC_ENABLED
521 	if (BC_IS_BC && BC_ERR(BC_PARSE_NO_EXEC(&vm.prs)))
522 		bc_parse_err(&vm.prs, BC_ERROR_PARSE_BLOCK);
523 #endif // BC_ENABLED
524 
525 err:
526 	BC_SIG_MAYLOCK;
527 
528 	free(data);
529 	bc_vm_clean();
530 
531 	// bc_program_reset(), called by bc_vm_clean(), resets the status.
532 	// We want it to clear the sig_pop variable in case it was set.
533 	if (vm.status == (sig_atomic_t) BC_STATUS_SUCCESS) BC_LONGJMP_STOP;
534 
535 	BC_LONGJMP_CONT;
536 }
537 
538 static void bc_vm_stdin(void) {
539 
540 	BcStatus s;
541 	BcVec buf, buffer;
542 	size_t string = 0;
543 	bool comment = false, hash = false;
544 
545 	bc_lex_file(&vm.prs.l, bc_program_stdin_name);
546 
547 	BC_SIG_LOCK;
548 	bc_vec_init(&buffer, sizeof(uchar), NULL);
549 	bc_vec_init(&buf, sizeof(uchar), NULL);
550 	bc_vec_pushByte(&buffer, '\0');
551 	BC_SETJMP_LOCKED(err);
552 	BC_SIG_UNLOCK;
553 
554 restart:
555 
556 	// This loop is complex because the vm tries not to send any lines that end
557 	// with a backslash to the parser. The reason for that is because the parser
558 	// treats a backslash+newline combo as whitespace, per the bc spec. In that
559 	// case, and for strings and comments, the parser will expect more stuff.
560 	while ((!(s = bc_read_line(&buf, ">>> ")) ||
561 	        (vm.eof = (s == BC_STATUS_EOF))) && buf.len > 1)
562 	{
563 		char c2, *str = buf.v;
564 		size_t i, len = buf.len - 1;
565 
566 		for (i = 0; i < len; ++i) {
567 
568 			bool notend = len > i + 1;
569 			uchar c = (uchar) str[i];
570 
571 			hash = (!comment && !string && ((hash && c != '\n') ||
572 			                                (!hash && c == '#')));
573 
574 			if (!hash && !comment && (i - 1 > len || str[i - 1] != '\\')) {
575 				if (BC_IS_BC) string ^= (c == '"');
576 				else if (c == ']') string -= 1;
577 				else if (c == '[') string += 1;
578 			}
579 
580 			if (BC_IS_BC && !hash && !string && notend) {
581 
582 				c2 = str[i + 1];
583 
584 				if (c == '/' && !comment && c2 == '*') {
585 					comment = true;
586 					i += 1;
587 				}
588 				else if (c == '*' && comment && c2 == '/') {
589 					comment = false;
590 					i += 1;
591 				}
592 			}
593 		}
594 
595 		bc_vec_concat(&buffer, buf.v);
596 
597 		if (string || comment) continue;
598 		if (len >= 2 && str[len - 2] == '\\' && str[len - 1] == '\n') continue;
599 #if BC_ENABLE_HISTORY
600 		if (vm.history.stdin_has_data) continue;
601 #endif // BC_ENABLE_HISTORY
602 
603 		bc_vm_process(buffer.v, true);
604 		bc_vec_empty(&buffer);
605 
606 		if (vm.eof) break;
607 	}
608 
609 	if (!BC_STATUS_IS_ERROR(s)) {
610 		if (BC_ERR(comment))
611 			bc_parse_err(&vm.prs, BC_ERROR_PARSE_COMMENT);
612 		else if (BC_ERR(string))
613 			bc_parse_err(&vm.prs, BC_ERROR_PARSE_STRING);
614 #if BC_ENABLED
615 		else if (BC_IS_BC && BC_ERR(BC_PARSE_NO_EXEC(&vm.prs)))
616 			bc_parse_err(&vm.prs, BC_ERROR_PARSE_BLOCK);
617 #endif // BC_ENABLED
618 	}
619 
620 err:
621 	BC_SIG_MAYLOCK;
622 
623 	bc_vm_clean();
624 
625 	vm.status = vm.status == BC_STATUS_ERROR_FATAL ||
626 	            vm.status == BC_STATUS_QUIT || !BC_I ?
627 	            vm.status : BC_STATUS_SUCCESS;
628 
629 	if (!vm.status && !vm.eof) {
630 		bc_vec_empty(&buffer);
631 		BC_LONGJMP_STOP;
632 		BC_SIG_UNLOCK;
633 		goto restart;
634 	}
635 
636 	bc_vec_free(&buf);
637 	bc_vec_free(&buffer);
638 
639 	BC_LONGJMP_CONT;
640 }
641 
642 #if BC_ENABLED
643 static void bc_vm_load(const char *name, const char *text) {
644 
645 	bc_lex_file(&vm.prs.l, name);
646 	bc_parse_text(&vm.prs, text);
647 
648 	while (vm.prs.l.t != BC_LEX_EOF) vm.parse(&vm.prs);
649 }
650 #endif // BC_ENABLED
651 
652 static void bc_vm_defaultMsgs(void) {
653 
654 	size_t i;
655 
656 	vm.func_header = bc_err_func_header;
657 
658 	for (i = 0; i < BC_ERR_IDX_NELEMS + BC_ENABLED; ++i)
659 		vm.err_ids[i] = bc_errs[i];
660 	for (i = 0; i < BC_ERROR_NELEMS; ++i) vm.err_msgs[i] = bc_err_msgs[i];
661 }
662 
663 static void bc_vm_gettext(void) {
664 
665 #if BC_ENABLE_NLS
666 	uchar id = 0;
667 	int set = 1, msg = 1;
668 	size_t i;
669 
670 	if (vm.locale == NULL) {
671 		vm.catalog = BC_VM_INVALID_CATALOG;
672 		bc_vm_defaultMsgs();
673 		return;
674 	}
675 
676 	vm.catalog = catopen(BC_MAINEXEC, NL_CAT_LOCALE);
677 
678 	if (vm.catalog == BC_VM_INVALID_CATALOG) {
679 		bc_vm_defaultMsgs();
680 		return;
681 	}
682 
683 	vm.func_header = catgets(vm.catalog, set, msg, bc_err_func_header);
684 
685 	for (set += 1; msg <= BC_ERR_IDX_NELEMS + BC_ENABLED; ++msg)
686 		vm.err_ids[msg - 1] = catgets(vm.catalog, set, msg, bc_errs[msg - 1]);
687 
688 	i = 0;
689 	id = bc_err_ids[i];
690 
691 	for (set = id + 3, msg = 1; i < BC_ERROR_NELEMS; ++i, ++msg) {
692 
693 		if (id != bc_err_ids[i]) {
694 			msg = 1;
695 			id = bc_err_ids[i];
696 			set = id + 3;
697 		}
698 
699 		vm.err_msgs[i] = catgets(vm.catalog, set, msg, bc_err_msgs[i]);
700 	}
701 #else // BC_ENABLE_NLS
702 	bc_vm_defaultMsgs();
703 #endif // BC_ENABLE_NLS
704 }
705 
706 static void bc_vm_exec(const char* env_exp_exit) {
707 
708 	size_t i;
709 	bool has_file = false;
710 
711 #if BC_ENABLED
712 	if (BC_IS_BC && (vm.flags & BC_FLAG_L)) {
713 
714 		bc_vm_load(bc_lib_name, bc_lib);
715 
716 #if BC_ENABLE_EXTRA_MATH
717 		if (!BC_IS_POSIX) bc_vm_load(bc_lib2_name, bc_lib2);
718 #endif // BC_ENABLE_EXTRA_MATH
719 	}
720 #endif // BC_ENABLED
721 
722 	if (vm.exprs.len) {
723 		bc_lex_file(&vm.prs.l, bc_program_exprs_name);
724 		bc_vm_process(vm.exprs.v, false);
725 		if (getenv(env_exp_exit) != NULL) return;
726 	}
727 
728 	for (i = 0; i < vm.files.len; ++i) {
729 		char *path = *((char**) bc_vec_item(&vm.files, i));
730 		if (!strcmp(path, "")) continue;
731 		has_file = true;
732 		bc_vm_file(path);
733 	}
734 
735 	if (BC_IS_BC || !has_file) bc_vm_stdin();
736 }
737 
738 void  bc_vm_boot(int argc, char *argv[], const char *env_len,
739                  const char* const env_args, const char* env_exp_exit)
740 {
741 	int ttyin, ttyout, ttyerr;
742 	struct sigaction sa;
743 
744 	BC_SIG_ASSERT_LOCKED;
745 
746 	ttyin = isatty(STDIN_FILENO);
747 	ttyout = isatty(STDOUT_FILENO);
748 	ttyerr = isatty(STDERR_FILENO);
749 
750 	vm.flags |= ttyin ? BC_FLAG_TTYIN : 0;
751 	vm.flags |= (ttyin != 0 && ttyout != 0 && ttyerr != 0) ? BC_FLAG_TTY : 0;
752 	vm.flags |= ttyin && ttyout ? BC_FLAG_I : 0;
753 
754 	sigemptyset(&sa.sa_mask);
755 	sa.sa_handler = bc_vm_sig;
756 	sa.sa_flags = SA_NODEFER;
757 
758 	sigaction(SIGTERM, &sa, NULL);
759 	sigaction(SIGQUIT, &sa, NULL);
760 	sigaction(SIGINT, &sa, NULL);
761 
762 #if BC_ENABLE_HISTORY
763 	if (BC_TTY) sigaction(SIGHUP, &sa, NULL);
764 #endif // BC_ENABLE_HISTORY
765 
766 	memcpy(vm.max_num, bc_num_bigdigMax,
767 	       bc_num_bigdigMax_size * sizeof(BcDig));
768 	bc_num_setup(&vm.max, vm.max_num, BC_NUM_BIGDIG_LOG10);
769 	vm.max.len = bc_num_bigdigMax_size;
770 
771 	vm.file = NULL;
772 
773 	bc_vm_gettext();
774 
775 	bc_file_init(&vm.ferr, STDERR_FILENO, output_bufs + BC_VM_STDOUT_BUF_SIZE,
776 	             BC_VM_STDERR_BUF_SIZE);
777 	bc_file_init(&vm.fout, STDOUT_FILENO, output_bufs, BC_VM_STDOUT_BUF_SIZE);
778 	vm.buf = output_bufs + BC_VM_STDOUT_BUF_SIZE + BC_VM_STDERR_BUF_SIZE;
779 
780 	vm.line_len = (uint16_t) bc_vm_envLen(env_len);
781 
782 	bc_vec_clear(&vm.files);
783 	bc_vec_clear(&vm.exprs);
784 
785 	bc_vec_init(&vm.temps, sizeof(BcNum), NULL);
786 
787 	bc_program_init(&vm.prog);
788 	bc_parse_init(&vm.prs, &vm.prog, BC_PROG_MAIN);
789 
790 #if BC_ENABLE_HISTORY
791 	if (BC_TTY) bc_history_init(&vm.history);
792 #endif // BC_ENABLE_HISTORY
793 
794 #if BC_ENABLED
795 	if (BC_IS_BC) vm.flags |= BC_FLAG_S * (getenv("POSIXLY_CORRECT") != NULL);
796 #endif // BC_ENABLED
797 
798 	bc_vm_envArgs(env_args);
799 	bc_args(argc, argv);
800 
801 	if (BC_IS_POSIX) vm.flags &= ~(BC_FLAG_G);
802 
803 	vm.maxes[BC_PROG_GLOBALS_IBASE] = BC_NUM_MAX_POSIX_IBASE;
804 	vm.maxes[BC_PROG_GLOBALS_OBASE] = BC_MAX_OBASE;
805 	vm.maxes[BC_PROG_GLOBALS_SCALE] = BC_MAX_SCALE;
806 
807 #if BC_ENABLE_EXTRA_MATH
808 	vm.maxes[BC_PROG_MAX_RAND] = ((BcRand) 0) - 1;
809 #endif // BC_ENABLE_EXTRA_MATH
810 
811 	if (BC_IS_BC && !BC_IS_POSIX)
812 		vm.maxes[BC_PROG_GLOBALS_IBASE] = BC_NUM_MAX_IBASE;
813 
814 	if (BC_IS_BC && BC_I && !(vm.flags & BC_FLAG_Q)) bc_vm_info(NULL);
815 
816 	BC_SIG_UNLOCK;
817 
818 	bc_vm_exec(env_exp_exit);
819 }
820