2 * *****************************************************************************
4 * SPDX-License-Identifier: BSD-2-Clause
6 * Copyright (c) 2018-2020 Gavin D. Howard and contributors.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are met:
11 * * Redistributions of source code must retain the above copyright notice, this
12 * list of conditions and the following disclaimer.
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.
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.
30 * *****************************************************************************
32 * Code common to all of bc and dc.
48 #include <sys/types.h>
53 #define WIN32_LEAN_AND_MEAN
67 BC_NORETURN void bc_vm_jmp(const char* f) {
68 #else // BC_DEBUG_CODE
69 BC_NORETURN void bc_vm_jmp(void) {
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
84 assert(vm.jmp_bufs.len - (size_t) vm.sig_pop);
87 if (vm.sig_pop) bc_vec_pop(&vm.jmp_bufs);
90 siglongjmp(*((sigjmp_buf*) bc_vec_top(&vm.jmp_bufs)), 1);
93 static void bc_vm_sig(int sig) {
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;
101 if (BC_TTY && sig == SIGINT) {
105 if (write(STDOUT_FILENO, vm.sigmsg, vm.siglen) != (ssize_t) vm.siglen)
106 vm.status = BC_STATUS_ERROR_FATAL;
111 else vm.status = BC_STATUS_QUIT;
113 assert(vm.jmp_bufs.len);
115 if (!vm.sig_lock) BC_VM_JMP;
118 void bc_vm_info(const char* const help) {
120 BC_SIG_ASSERT_LOCKED;
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);
129 bc_file_putchar(&vm.fout, '\n');
130 bc_file_printf(&vm.fout, help, vm.name, vm.name);
133 bc_file_flush(&vm.fout);
136 void bc_vm_error(BcError e, size_t line, ...) {
140 uchar id = bc_err_ids[e];
141 const char* err_type = vm.err_ids[id];
144 assert(e < BC_ERROR_NELEMS);
148 if (!BC_S && e >= BC_ERROR_POSIX_START) {
150 // Make sure to not return an error.
152 err_type = vm.err_ids[BC_ERR_IDX_WARN];
158 BC_SIG_TRYLOCK(lock);
160 // Make sure all of stdout is written first.
161 s = bc_file_flushErr(&vm.fout);
163 if (BC_ERR(s == BC_STATUS_ERROR_FATAL)) {
164 vm.status = (sig_atomic_t) s;
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);
175 if (BC_NO_ERR(vm.file)) {
177 // This is the condition for parsing vs runtime.
178 // If line is not 0, it is parsing.
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);
186 BcInstPtr *ip = bc_vec_item_rev(&vm.prog.stack, 0);
187 BcFunc *f = bc_vec_item(&vm.prog.fns, ip->func);
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);
195 if (BC_IS_BC && ip->func != BC_PROG_MAIN &&
196 ip->func != BC_PROG_READ)
198 bc_file_puts(&vm.ferr, "()");
204 bc_file_puts(&vm.ferr, "\n\n");
206 s = bc_file_flushErr(&vm.ferr);
208 vm.status = s == BC_STATUS_ERROR_FATAL ?
209 (sig_atomic_t) s : (sig_atomic_t) (uchar) (id + 1);
211 if (BC_ERR(vm.status)) BC_VM_JMP;
213 BC_SIG_TRYUNLOCK(lock);
216 static void bc_vm_envArgs(const char* const env_args_name) {
218 char *env_args = getenv(env_args_name), *buf, *start;
221 BC_SIG_ASSERT_LOCKED;
223 if (env_args == NULL) return;
225 start = buf = vm.env_args_buffer = bc_vm_strdup(env_args);
229 bc_vec_init(&vm.env_args, sizeof(char*), NULL);
230 bc_vec_push(&vm.env_args, &env_args_name);
234 if (!isspace(*buf)) {
236 if (*buf == '"' || *buf == '\'') {
248 bc_vec_push(&vm.env_args, &buf);
250 while (*buf && ((!instr && !isspace(*buf)) ||
251 (instr && *buf != instr)))
258 if (instr) instr = '\0';
264 else if (instr) bc_vm_error(BC_ERROR_FATAL_OPTION, 0, start);
269 // Make sure to push a NULL pointer at the end.
271 bc_vec_push(&vm.env_args, &buf);
273 bc_args((int) vm.env_args.len - 1, bc_vec_item(&vm.env_args, 0));
276 static size_t bc_vm_envLen(const char *var) {
278 char *lenv = getenv(var);
279 size_t i, len = BC_NUM_PRINT_WIDTH;
282 if (lenv == NULL) return len;
286 for (num = 1, i = 0; num && i < len; ++i) num = isdigit(lenv[i]);
289 len = (size_t) atoi(lenv) - 1;
290 if (len < 2 || len >= UINT16_MAX) len = BC_NUM_PRINT_WIDTH;
292 else len = BC_NUM_PRINT_WIDTH;
297 void bc_vm_shutdown(void) {
299 BC_SIG_ASSERT_LOCKED;
302 if (vm.catalog != BC_VM_INVALID_CATALOG) catclose(vm.catalog);
303 #endif // BC_ENABLE_NLS
305 #if BC_ENABLE_HISTORY
306 // This must always run to ensure that the terminal is back to normal.
307 if (BC_TTY) bc_history_free(&vm.history);
308 #endif // BC_ENABLE_HISTORY
311 bc_vec_free(&vm.env_args);
312 free(vm.env_args_buffer);
313 bc_vec_free(&vm.files);
314 bc_vec_free(&vm.exprs);
316 bc_program_free(&vm.prog);
317 bc_parse_free(&vm.prs);
321 for (i = 0; i < vm.temps.len; ++i)
322 free(((BcNum*) bc_vec_item(&vm.temps, i))->num);
324 bc_vec_free(&vm.temps);
328 bc_file_free(&vm.fout);
329 bc_file_free(&vm.ferr);
332 inline size_t bc_vm_arraySize(size_t n, size_t size) {
333 size_t res = n * size;
334 if (BC_ERR(res >= SIZE_MAX || (n != 0 && res / n != size)))
335 bc_vm_err(BC_ERROR_FATAL_ALLOC_ERR);
339 inline size_t bc_vm_growSize(size_t a, size_t b) {
341 if (BC_ERR(res >= SIZE_MAX || res < a || res < b))
342 bc_vm_err(BC_ERROR_FATAL_ALLOC_ERR);
346 void* bc_vm_malloc(size_t n) {
350 BC_SIG_ASSERT_LOCKED;
354 if (BC_ERR(ptr == NULL)) bc_vm_err(BC_ERROR_FATAL_ALLOC_ERR);
359 void* bc_vm_realloc(void *ptr, size_t n) {
363 BC_SIG_ASSERT_LOCKED;
365 temp = realloc(ptr, n);
367 if (BC_ERR(temp == NULL)) bc_vm_err(BC_ERROR_FATAL_ALLOC_ERR);
372 char* bc_vm_strdup(const char *str) {
376 BC_SIG_ASSERT_LOCKED;
380 if (BC_ERR(!s)) bc_vm_err(BC_ERROR_FATAL_ALLOC_ERR);
385 void bc_vm_printf(const char *fmt, ...) {
392 bc_file_vprintf(&vm.fout, fmt, args);
400 void bc_vm_putchar(int c) {
401 bc_file_putchar(&vm.fout, (uchar) c);
402 vm.nchars = (c == '\n' ? 0 : vm.nchars + 1);
405 static void bc_vm_clean(void) {
407 BcVec *fns = &vm.prog.fns;
408 BcFunc *f = bc_vec_item(fns, BC_PROG_MAIN);
409 BcInstPtr *ip = bc_vec_item(&vm.prog.stack, 0);
410 bool good = ((vm.status && vm.status != BC_STATUS_QUIT) || vm.sig);
412 if (good) bc_program_reset(&vm.prog);
415 if (good && BC_IS_BC) good = !BC_PARSE_NO_EXEC(&vm.prs);
425 for (i = 0; good && i < vm.prog.results.len; ++i) {
426 BcResult *r = (BcResult*) bc_vec_item(&vm.prog.results, i);
427 good = BC_VM_SAFE_RESULT(r);
432 // If this condition is true, we can get rid of strings,
433 // constants, and code. This is an idea from busybox.
434 if (good && vm.prog.stack.len == 1 && ip->idx == f->code.len) {
438 bc_vec_npop(&f->labels, f->labels.len);
439 bc_vec_npop(&f->strs, f->strs.len);
440 bc_vec_npop(&f->consts, f->consts.len);
445 // Note to self: you cannot delete strings and functions. Deal with it.
446 if (BC_IS_DC) bc_vec_npop(vm.prog.consts, vm.prog.consts->len);
449 bc_vec_npop(&f->code, f->code.len);
455 static void bc_vm_process(const char *text, bool is_stdin) {
457 bc_parse_text(&vm.prs, text);
462 if (vm.prs.l.t == BC_LEX_KW_DEFINE) vm.parse(&vm.prs);
465 while (BC_PARSE_CAN_PARSE(vm.prs)) vm.parse(&vm.prs);
470 uint16_t *flags = BC_PARSE_TOP_FLAG_PTR(&vm.prs);
472 if (!is_stdin && vm.prs.flags.len == 1 &&
473 *flags == BC_PARSE_FLAG_IF_END)
475 bc_parse_noElse(&vm.prs);
478 if (BC_PARSE_NO_EXEC(&vm.prs)) return;
482 bc_program_exec(&vm.prog);
484 assert(BC_IS_DC || vm.prog.results.len == 0);
486 if (BC_I) bc_file_flush(&vm.fout);
488 } while (vm.prs.l.t != BC_LEX_EOF);
491 static void bc_vm_file(const char *file) {
497 bc_lex_file(&vm.prs.l, file);
501 bc_read_file(file, &data);
503 BC_SETJMP_LOCKED(err);
507 bc_vm_process(data, false);
510 if (BC_IS_BC && BC_ERR(BC_PARSE_NO_EXEC(&vm.prs)))
511 bc_parse_err(&vm.prs, BC_ERROR_PARSE_BLOCK);
520 // bc_program_reset(), called by bc_vm_clean(), resets the status.
521 // We want it to clear the sig_pop variable in case it was set.
522 if (vm.status == (sig_atomic_t) BC_STATUS_SUCCESS) BC_LONGJMP_STOP;
527 static void bc_vm_stdin(void) {
532 bool comment = false, hash = false;
534 bc_lex_file(&vm.prs.l, bc_program_stdin_name);
537 bc_vec_init(&buffer, sizeof(uchar), NULL);
538 bc_vec_init(&buf, sizeof(uchar), NULL);
539 bc_vec_pushByte(&buffer, '\0');
540 BC_SETJMP_LOCKED(err);
545 // This loop is complex because the vm tries not to send any lines that end
546 // with a backslash to the parser. The reason for that is because the parser
547 // treats a backslash+newline combo as whitespace, per the bc spec. In that
548 // case, and for strings and comments, the parser will expect more stuff.
549 while ((!(s = bc_read_line(&buf, ">>> ")) ||
550 (vm.eof = (s == BC_STATUS_EOF))) && buf.len > 1)
552 char c2, *str = buf.v;
553 size_t i, len = buf.len - 1;
555 for (i = 0; i < len; ++i) {
557 bool notend = len > i + 1;
558 uchar c = (uchar) str[i];
560 hash = (!comment && !string && ((hash && c != '\n') ||
561 (!hash && c == '#')));
563 if (!hash && !comment && (i - 1 > len || str[i - 1] != '\\')) {
564 if (BC_IS_BC) string ^= (c == '"');
565 else if (c == ']') string -= 1;
566 else if (c == '[') string += 1;
569 if (BC_IS_BC && !hash && !string && notend) {
573 if (c == '/' && !comment && c2 == '*') {
577 else if (c == '*' && comment && c2 == '/') {
584 bc_vec_concat(&buffer, buf.v);
586 if (string || comment) continue;
587 if (len >= 2 && str[len - 2] == '\\' && str[len - 1] == '\n') continue;
588 #if BC_ENABLE_HISTORY
589 if (vm.history.stdin_has_data) continue;
590 #endif // BC_ENABLE_HISTORY
592 bc_vm_process(buffer.v, true);
593 bc_vec_empty(&buffer);
599 if (!BC_STATUS_IS_ERROR(s)) {
601 bc_parse_err(&vm.prs, BC_ERROR_PARSE_COMMENT);
602 else if (BC_ERR(string))
603 bc_parse_err(&vm.prs, BC_ERROR_PARSE_STRING);
605 else if (BC_IS_BC && BC_ERR(BC_PARSE_NO_EXEC(&vm.prs)))
606 bc_parse_err(&vm.prs, BC_ERROR_PARSE_BLOCK);
615 vm.status = vm.status == BC_STATUS_ERROR_FATAL ||
616 vm.status == BC_STATUS_QUIT || !BC_I ?
617 vm.status : BC_STATUS_SUCCESS;
619 if (!vm.status && !vm.eof) {
620 bc_vec_empty(&buffer);
627 bc_vec_free(&buffer);
633 static void bc_vm_load(const char *name, const char *text) {
635 bc_lex_file(&vm.prs.l, name);
636 bc_parse_text(&vm.prs, text);
638 while (vm.prs.l.t != BC_LEX_EOF) vm.parse(&vm.prs);
642 static void bc_vm_defaultMsgs(void) {
646 vm.func_header = bc_err_func_header;
648 for (i = 0; i < BC_ERR_IDX_NELEMS + BC_ENABLED; ++i)
649 vm.err_ids[i] = bc_errs[i];
650 for (i = 0; i < BC_ERROR_NELEMS; ++i) vm.err_msgs[i] = bc_err_msgs[i];
653 static void bc_vm_gettext(void) {
657 int set = 1, msg = 1;
660 if (vm.locale == NULL) {
661 vm.catalog = BC_VM_INVALID_CATALOG;
666 vm.catalog = catopen(BC_MAINEXEC, NL_CAT_LOCALE);
668 if (vm.catalog == BC_VM_INVALID_CATALOG) {
673 vm.func_header = catgets(vm.catalog, set, msg, bc_err_func_header);
675 for (set += 1; msg <= BC_ERR_IDX_NELEMS + BC_ENABLED; ++msg)
676 vm.err_ids[msg - 1] = catgets(vm.catalog, set, msg, bc_errs[msg - 1]);
681 for (set = id + 3, msg = 1; i < BC_ERROR_NELEMS; ++i, ++msg) {
683 if (id != bc_err_ids[i]) {
689 vm.err_msgs[i] = catgets(vm.catalog, set, msg, bc_err_msgs[i]);
691 #else // BC_ENABLE_NLS
693 #endif // BC_ENABLE_NLS
696 static void bc_vm_exec(const char* env_exp_exit) {
699 bool has_file = false;
703 if (BC_IS_BC && (vm.flags & BC_FLAG_L)) {
705 bc_vm_load(bc_lib_name, bc_lib);
707 #if BC_ENABLE_EXTRA_MATH
708 if (!BC_IS_POSIX) bc_vm_load(bc_lib2_name, bc_lib2);
709 #endif // BC_ENABLE_EXTRA_MATH
715 size_t len = vm.exprs.len - 1;
719 bc_vec_init(&buf, sizeof(uchar), NULL);
722 BC_SETJMP_LOCKED(err);
727 bc_lex_file(&vm.prs.l, bc_program_exprs_name);
731 more = bc_read_buf(&buf, vm.exprs.v, &len);
732 bc_vec_pushByte(&buf, '\0');
733 bc_vm_process(buf.v, false);
735 bc_vec_npop(&buf, buf.len);
748 if (getenv(env_exp_exit) != NULL) return;
751 for (i = 0; i < vm.files.len; ++i) {
752 char *path = *((char**) bc_vec_item(&vm.files, i));
753 if (!strcmp(path, "")) continue;
758 if (BC_IS_BC || !has_file) bc_vm_stdin();
760 // These are all protected by ifndef NDEBUG because if these are needed, bc is
761 // goingi to exit anyway, and I see no reason to include this code in a release
762 // build when the OS is going to free all of the resources anyway.
773 void bc_vm_boot(int argc, char *argv[], const char *env_len,
774 const char* const env_args, const char* env_exp_exit)
776 int ttyin, ttyout, ttyerr;
779 BC_SIG_ASSERT_LOCKED;
781 ttyin = isatty(STDIN_FILENO);
782 ttyout = isatty(STDOUT_FILENO);
783 ttyerr = isatty(STDERR_FILENO);
785 vm.flags |= ttyin ? BC_FLAG_TTYIN : 0;
786 vm.flags |= (ttyin != 0 && ttyout != 0 && ttyerr != 0) ? BC_FLAG_TTY : 0;
787 vm.flags |= ttyin && ttyout ? BC_FLAG_I : 0;
789 sigemptyset(&sa.sa_mask);
790 sa.sa_handler = bc_vm_sig;
791 sa.sa_flags = SA_NODEFER;
793 sigaction(SIGTERM, &sa, NULL);
794 sigaction(SIGQUIT, &sa, NULL);
795 sigaction(SIGINT, &sa, NULL);
797 #if BC_ENABLE_HISTORY
798 if (BC_TTY) sigaction(SIGHUP, &sa, NULL);
799 #endif // BC_ENABLE_HISTORY
801 memcpy(vm.max_num, bc_num_bigdigMax,
802 bc_num_bigdigMax_size * sizeof(BcDig));
803 bc_num_setup(&vm.max, vm.max_num, BC_NUM_BIGDIG_LOG10);
804 vm.max.len = bc_num_bigdigMax_size;
810 bc_file_init(&vm.ferr, STDERR_FILENO, output_bufs + BC_VM_STDOUT_BUF_SIZE,
811 BC_VM_STDERR_BUF_SIZE);
812 bc_file_init(&vm.fout, STDOUT_FILENO, output_bufs, BC_VM_STDOUT_BUF_SIZE);
813 vm.buf = output_bufs + BC_VM_STDOUT_BUF_SIZE + BC_VM_STDERR_BUF_SIZE;
815 vm.line_len = (uint16_t) bc_vm_envLen(env_len);
817 bc_vec_clear(&vm.files);
818 bc_vec_clear(&vm.exprs);
820 bc_vec_init(&vm.temps, sizeof(BcNum), NULL);
822 bc_program_init(&vm.prog);
823 bc_parse_init(&vm.prs, &vm.prog, BC_PROG_MAIN);
825 #if BC_ENABLE_HISTORY
826 if (BC_TTY) bc_history_init(&vm.history);
827 #endif // BC_ENABLE_HISTORY
830 if (BC_IS_BC) vm.flags |= BC_FLAG_S * (getenv("POSIXLY_CORRECT") != NULL);
833 bc_vm_envArgs(env_args);
837 if (BC_IS_POSIX) vm.flags &= ~(BC_FLAG_G);
840 vm.maxes[BC_PROG_GLOBALS_IBASE] = BC_NUM_MAX_POSIX_IBASE;
841 vm.maxes[BC_PROG_GLOBALS_OBASE] = BC_MAX_OBASE;
842 vm.maxes[BC_PROG_GLOBALS_SCALE] = BC_MAX_SCALE;
844 #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND
845 vm.maxes[BC_PROG_MAX_RAND] = ((BcRand) 0) - 1;
846 #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND
849 if (BC_IS_BC && !BC_IS_POSIX)
850 vm.maxes[BC_PROG_GLOBALS_IBASE] = BC_NUM_MAX_IBASE;
853 if (BC_IS_BC && BC_I && !(vm.flags & BC_FLAG_Q)) bc_vm_info(NULL);
857 bc_vm_exec(env_exp_exit);