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
65 char output_bufs[BC_VM_BUF_SIZE];
69 BC_NORETURN void bc_vm_jmp(const char* f) {
70 #else // BC_DEBUG_CODE
71 BC_NORETURN void bc_vm_jmp(void) {
79 bc_file_puts(&vm.ferr, "Longjmp: ");
80 bc_file_puts(&vm.ferr, f);
81 bc_file_putchar(&vm.ferr, '\n');
82 bc_file_flush(&vm.ferr);
83 #endif // BC_DEBUG_CODE
86 assert(vm.jmp_bufs.len - (size_t) vm.sig_pop);
89 if (vm.jmp_bufs.len == 0) abort();
90 if (vm.sig_pop) bc_vec_pop(&vm.jmp_bufs);
93 siglongjmp(*((sigjmp_buf*) bc_vec_top(&vm.jmp_bufs)), 1);
96 #if !BC_ENABLE_LIBRARY
97 static void bc_vm_sig(int sig) {
99 // There is already a signal in flight.
100 if (vm.status == (sig_atomic_t) BC_STATUS_QUIT || vm.sig) {
101 if (!BC_TTY || sig != SIGINT) vm.status = BC_STATUS_QUIT;
105 if (BC_TTY && sig == SIGINT) {
109 if (write(STDOUT_FILENO, vm.sigmsg, vm.siglen) != (ssize_t) vm.siglen)
110 vm.status = BC_STATUS_ERROR_FATAL;
115 else vm.status = BC_STATUS_QUIT;
117 assert(vm.jmp_bufs.len);
119 if (!vm.sig_lock) BC_VM_JMP;
122 void bc_vm_info(const char* const help) {
124 BC_SIG_ASSERT_LOCKED;
126 bc_file_puts(&vm.fout, vm.name);
127 bc_file_putchar(&vm.fout, ' ');
128 bc_file_puts(&vm.fout, BC_VERSION);
129 bc_file_putchar(&vm.fout, '\n');
130 bc_file_puts(&vm.fout, bc_copyright);
133 bc_file_putchar(&vm.fout, '\n');
134 bc_file_printf(&vm.fout, help, vm.name, vm.name);
137 bc_file_flush(&vm.fout);
139 #endif // !BC_ENABLE_LIBRARY
141 #if BC_ENABLE_LIBRARY
142 void bc_vm_handleError(BcErr e) {
144 assert(e < BC_ERR_NELEMS);
149 if (e <= BC_ERR_MATH_DIVIDE_BY_ZERO) {
150 vm.err = (BclError) (e - BC_ERR_MATH_NEGATIVE +
151 BCL_ERROR_MATH_NEGATIVE);
153 else if (vm.abrt) abort();
154 else if (e == BC_ERR_FATAL_ALLOC_ERR) vm.err = BCL_ERROR_FATAL_ALLOC_ERR;
155 else vm.err = BCL_ERROR_FATAL_UNKNOWN_ERR;
159 #else // BC_ENABLE_LIBRARY
160 void bc_vm_handleError(BcErr e, size_t line, ...) {
164 uchar id = bc_err_ids[e];
165 const char* err_type = vm.err_ids[id];
168 assert(e < BC_ERR_NELEMS);
172 if (!BC_S && e >= BC_ERR_POSIX_START) {
174 // Make sure to not return an error.
176 err_type = vm.err_ids[BC_ERR_IDX_WARN];
182 BC_SIG_TRYLOCK(lock);
184 // Make sure all of stdout is written first.
185 s = bc_file_flushErr(&vm.fout);
187 if (BC_ERR(s == BC_STATUS_ERROR_FATAL)) {
188 vm.status = (sig_atomic_t) s;
192 va_start(args, line);
193 bc_file_putchar(&vm.ferr, '\n');
194 bc_file_puts(&vm.ferr, err_type);
195 bc_file_putchar(&vm.ferr, ' ');
196 bc_file_vprintf(&vm.ferr, vm.err_msgs[e], args);
199 if (BC_NO_ERR(vm.file)) {
201 // This is the condition for parsing vs runtime.
202 // If line is not 0, it is parsing.
204 bc_file_puts(&vm.ferr, "\n ");
205 bc_file_puts(&vm.ferr, vm.file);
206 bc_file_printf(&vm.ferr, bc_err_line, line);
210 BcInstPtr *ip = bc_vec_item_rev(&vm.prog.stack, 0);
211 BcFunc *f = bc_vec_item(&vm.prog.fns, ip->func);
213 bc_file_puts(&vm.ferr, "\n ");
214 bc_file_puts(&vm.ferr, vm.func_header);
215 bc_file_putchar(&vm.ferr, ' ');
216 bc_file_puts(&vm.ferr, f->name);
219 if (BC_IS_BC && ip->func != BC_PROG_MAIN &&
220 ip->func != BC_PROG_READ)
222 bc_file_puts(&vm.ferr, "()");
228 bc_file_puts(&vm.ferr, "\n\n");
230 s = bc_file_flushErr(&vm.ferr);
232 vm.status = s == BC_STATUS_ERROR_FATAL ?
233 (sig_atomic_t) s : (sig_atomic_t) (uchar) (id + 1);
235 if (BC_ERR(vm.status)) BC_VM_JMP;
237 BC_SIG_TRYUNLOCK(lock);
240 static void bc_vm_envArgs(const char* const env_args_name) {
242 char *env_args = getenv(env_args_name), *buf, *start;
245 BC_SIG_ASSERT_LOCKED;
247 if (env_args == NULL) return;
249 start = buf = vm.env_args_buffer = bc_vm_strdup(env_args);
253 bc_vec_init(&vm.env_args, sizeof(char*), NULL);
254 bc_vec_push(&vm.env_args, &env_args_name);
258 if (!isspace(*buf)) {
260 if (*buf == '"' || *buf == '\'') {
272 bc_vec_push(&vm.env_args, &buf);
274 while (*buf && ((!instr && !isspace(*buf)) ||
275 (instr && *buf != instr)))
282 if (instr) instr = '\0';
288 else if (instr) bc_vm_error(BC_ERR_FATAL_OPTION, 0, start);
293 // Make sure to push a NULL pointer at the end.
295 bc_vec_push(&vm.env_args, &buf);
297 bc_args((int) vm.env_args.len - 1, bc_vec_item(&vm.env_args, 0));
300 static size_t bc_vm_envLen(const char *var) {
302 char *lenv = getenv(var);
303 size_t i, len = BC_NUM_PRINT_WIDTH;
306 if (lenv == NULL) return len;
310 for (num = 1, i = 0; num && i < len; ++i) num = isdigit(lenv[i]);
313 len = (size_t) atoi(lenv) - 1;
314 if (len < 2 || len >= UINT16_MAX) len = BC_NUM_PRINT_WIDTH;
316 else len = BC_NUM_PRINT_WIDTH;
320 #endif // BC_ENABLE_LIBRARY
322 void bc_vm_shutdown(void) {
324 BC_SIG_ASSERT_LOCKED;
327 if (vm.catalog != BC_VM_INVALID_CATALOG) catclose(vm.catalog);
328 #endif // BC_ENABLE_NLS
330 #if BC_ENABLE_HISTORY
331 // This must always run to ensure that the terminal is back to normal.
332 if (BC_TTY) bc_history_free(&vm.history);
333 #endif // BC_ENABLE_HISTORY
336 #if !BC_ENABLE_LIBRARY
337 bc_vec_free(&vm.env_args);
338 free(vm.env_args_buffer);
339 bc_vec_free(&vm.files);
340 bc_vec_free(&vm.exprs);
342 bc_program_free(&vm.prog);
343 bc_parse_free(&vm.prs);
344 #endif // !BC_ENABLE_LIBRARY
347 bc_vec_free(&vm.temps);
350 #if !BC_ENABLE_LIBRARY
351 bc_file_free(&vm.fout);
352 bc_file_free(&vm.ferr);
353 #endif // !BC_ENABLE_LIBRARY
356 #if !defined(NDEBUG) || BC_ENABLE_LIBRARY
357 void bc_vm_freeTemps(void) {
361 for (i = 0; i < vm.temps.len; ++i) {
362 free(((BcNum*) bc_vec_item(&vm.temps, i))->num);
365 #endif // !defined(NDEBUG) || BC_ENABLE_LIBRARY
367 inline size_t bc_vm_arraySize(size_t n, size_t size) {
368 size_t res = n * size;
369 if (BC_ERR(res >= SIZE_MAX || (n != 0 && res / n != size)))
370 bc_vm_err(BC_ERR_FATAL_ALLOC_ERR);
374 inline size_t bc_vm_growSize(size_t a, size_t b) {
376 if (BC_ERR(res >= SIZE_MAX || res < a || res < b))
377 bc_vm_err(BC_ERR_FATAL_ALLOC_ERR);
381 void* bc_vm_malloc(size_t n) {
385 BC_SIG_ASSERT_LOCKED;
389 if (BC_ERR(ptr == NULL)) bc_vm_err(BC_ERR_FATAL_ALLOC_ERR);
394 void* bc_vm_realloc(void *ptr, size_t n) {
398 BC_SIG_ASSERT_LOCKED;
400 temp = realloc(ptr, n);
402 if (BC_ERR(temp == NULL)) bc_vm_err(BC_ERR_FATAL_ALLOC_ERR);
407 char* bc_vm_strdup(const char *str) {
411 BC_SIG_ASSERT_LOCKED;
415 if (BC_ERR(!s)) bc_vm_err(BC_ERR_FATAL_ALLOC_ERR);
420 #if !BC_ENABLE_LIBRARY
421 void bc_vm_printf(const char *fmt, ...) {
428 bc_file_vprintf(&vm.fout, fmt, args);
435 #endif // !BC_ENABLE_LIBRARY
437 void bc_vm_putchar(int c) {
438 #if BC_ENABLE_LIBRARY
439 bc_vec_pushByte(&vm.out, (uchar) c);
440 #else // BC_ENABLE_LIBRARY
441 bc_file_putchar(&vm.fout, (uchar) c);
442 vm.nchars = (c == '\n' ? 0 : vm.nchars + 1);
443 #endif // BC_ENABLE_LIBRARY
446 #if !BC_ENABLE_LIBRARY
447 static void bc_vm_clean(void) {
449 BcVec *fns = &vm.prog.fns;
450 BcFunc *f = bc_vec_item(fns, BC_PROG_MAIN);
451 BcInstPtr *ip = bc_vec_item(&vm.prog.stack, 0);
452 bool good = ((vm.status && vm.status != BC_STATUS_QUIT) || vm.sig);
454 if (good) bc_program_reset(&vm.prog);
457 if (good && BC_IS_BC) good = !BC_PARSE_NO_EXEC(&vm.prs);
467 for (i = 0; good && i < vm.prog.results.len; ++i) {
468 BcResult *r = (BcResult*) bc_vec_item(&vm.prog.results, i);
469 good = BC_VM_SAFE_RESULT(r);
474 // If this condition is true, we can get rid of strings,
475 // constants, and code. This is an idea from busybox.
476 if (good && vm.prog.stack.len == 1 && ip->idx == f->code.len) {
480 bc_vec_npop(&f->labels, f->labels.len);
481 bc_vec_npop(&f->strs, f->strs.len);
482 bc_vec_npop(&f->consts, f->consts.len);
487 // Note to self: you cannot delete strings and functions. Deal with it.
488 if (BC_IS_DC) bc_vec_npop(vm.prog.consts, vm.prog.consts->len);
491 bc_vec_npop(&f->code, f->code.len);
497 static void bc_vm_process(const char *text) {
499 bc_parse_text(&vm.prs, text);
504 if (vm.prs.l.t == BC_LEX_KW_DEFINE) vm.parse(&vm.prs);
507 while (BC_PARSE_CAN_PARSE(vm.prs)) vm.parse(&vm.prs);
509 if(BC_IS_DC || !BC_PARSE_NO_EXEC(&vm.prs)) bc_program_exec(&vm.prog);
511 assert(BC_IS_DC || vm.prog.results.len == 0);
513 if (BC_I) bc_file_flush(&vm.fout);
515 } while (vm.prs.l.t != BC_LEX_EOF);
519 static void bc_vm_endif(void) {
524 if (BC_NO_ERR(!BC_PARSE_NO_EXEC(&vm.prs))) return;
528 for (i = 0; good && i < vm.prs.flags.len; ++i) {
529 uint16_t flag = *((uint16_t*) bc_vec_item(&vm.prs.flags, i));
530 good = ((flag & BC_PARSE_FLAG_BRACE) != BC_PARSE_FLAG_BRACE);
534 while (BC_PARSE_IF_END(&vm.prs)) bc_vm_process("else {}");
536 else bc_parse_err(&vm.prs, BC_ERR_PARSE_BLOCK);
540 static void bc_vm_file(const char *file) {
546 bc_lex_file(&vm.prs.l, file);
550 bc_read_file(file, &data);
552 BC_SETJMP_LOCKED(err);
559 if (BC_IS_BC) bc_vm_endif();
568 // bc_program_reset(), called by bc_vm_clean(), resets the status.
569 // We want it to clear the sig_pop variable in case it was set.
570 if (vm.status == (sig_atomic_t) BC_STATUS_SUCCESS) BC_LONGJMP_STOP;
575 static void bc_vm_stdin(void) {
580 bool comment = false, hash = false;
582 bc_lex_file(&vm.prs.l, bc_program_stdin_name);
585 bc_vec_init(&buffer, sizeof(uchar), NULL);
586 bc_vec_init(&buf, sizeof(uchar), NULL);
587 bc_vec_pushByte(&buffer, '\0');
588 BC_SETJMP_LOCKED(err);
593 // This loop is complex because the vm tries not to send any lines that end
594 // with a backslash to the parser. The reason for that is because the parser
595 // treats a backslash+newline combo as whitespace, per the bc spec. In that
596 // case, and for strings and comments, the parser will expect more stuff.
597 while ((!(s = bc_read_line(&buf, ">>> ")) ||
598 (vm.eof = (s == BC_STATUS_EOF))) && buf.len > 1)
600 char c2, *str = buf.v;
601 size_t i, len = buf.len - 1;
603 for (i = 0; i < len; ++i) {
605 bool notend = len > i + 1;
606 uchar c = (uchar) str[i];
608 hash = (!comment && !string && ((hash && c != '\n') ||
609 (!hash && c == '#')));
611 if (!hash && !comment && (i - 1 > len || str[i - 1] != '\\')) {
612 if (BC_IS_BC) string ^= (c == '"');
613 else if (c == ']') string -= 1;
614 else if (c == '[') string += 1;
617 if (BC_IS_BC && !hash && !string && notend) {
621 if (c == '/' && !comment && c2 == '*') {
625 else if (c == '*' && comment && c2 == '/') {
632 bc_vec_concat(&buffer, buf.v);
634 if (string || comment) continue;
635 if (len >= 2 && str[len - 2] == '\\' && str[len - 1] == '\n') continue;
636 #if BC_ENABLE_HISTORY
637 if (vm.history.stdin_has_data) continue;
638 #endif // BC_ENABLE_HISTORY
640 bc_vm_process(buffer.v);
641 bc_vec_empty(&buffer);
647 if (!BC_STATUS_IS_ERROR(s)) {
649 bc_parse_err(&vm.prs, BC_ERR_PARSE_COMMENT);
650 else if (BC_ERR(string))
651 bc_parse_err(&vm.prs, BC_ERR_PARSE_STRING);
653 else if (BC_IS_BC) bc_vm_endif();
662 vm.status = vm.status == BC_STATUS_ERROR_FATAL ||
663 vm.status == BC_STATUS_QUIT || !BC_I ?
664 vm.status : BC_STATUS_SUCCESS;
666 if (!vm.status && !vm.eof) {
667 bc_vec_empty(&buffer);
674 bc_vec_free(&buffer);
680 static void bc_vm_load(const char *name, const char *text) {
682 bc_lex_file(&vm.prs.l, name);
683 bc_parse_text(&vm.prs, text);
685 while (vm.prs.l.t != BC_LEX_EOF) vm.parse(&vm.prs);
689 static void bc_vm_defaultMsgs(void) {
693 vm.func_header = bc_err_func_header;
695 for (i = 0; i < BC_ERR_IDX_NELEMS + BC_ENABLED; ++i)
696 vm.err_ids[i] = bc_errs[i];
697 for (i = 0; i < BC_ERR_NELEMS; ++i) vm.err_msgs[i] = bc_err_msgs[i];
700 static void bc_vm_gettext(void) {
704 int set = 1, msg = 1;
707 if (vm.locale == NULL) {
708 vm.catalog = BC_VM_INVALID_CATALOG;
713 vm.catalog = catopen(BC_MAINEXEC, NL_CAT_LOCALE);
715 if (vm.catalog == BC_VM_INVALID_CATALOG) {
720 vm.func_header = catgets(vm.catalog, set, msg, bc_err_func_header);
722 for (set += 1; msg <= BC_ERR_IDX_NELEMS + BC_ENABLED; ++msg)
723 vm.err_ids[msg - 1] = catgets(vm.catalog, set, msg, bc_errs[msg - 1]);
728 for (set = id + 3, msg = 1; i < BC_ERR_NELEMS; ++i, ++msg) {
730 if (id != bc_err_ids[i]) {
736 vm.err_msgs[i] = catgets(vm.catalog, set, msg, bc_err_msgs[i]);
738 #else // BC_ENABLE_NLS
740 #endif // BC_ENABLE_NLS
743 static void bc_vm_exec(void) {
746 bool has_file = false;
750 if (BC_IS_BC && (vm.flags & BC_FLAG_L)) {
752 bc_vm_load(bc_lib_name, bc_lib);
754 #if BC_ENABLE_EXTRA_MATH
755 if (!BC_IS_POSIX) bc_vm_load(bc_lib2_name, bc_lib2);
756 #endif // BC_ENABLE_EXTRA_MATH
762 size_t len = vm.exprs.len - 1;
766 bc_vec_init(&buf, sizeof(uchar), NULL);
769 BC_SETJMP_LOCKED(err);
774 bc_lex_file(&vm.prs.l, bc_program_exprs_name);
778 more = bc_read_buf(&buf, vm.exprs.v, &len);
779 bc_vec_pushByte(&buf, '\0');
780 bc_vm_process(buf.v);
782 bc_vec_npop(&buf, buf.len);
795 if (!vm.no_exit_exprs) return;
798 for (i = 0; i < vm.files.len; ++i) {
799 char *path = *((char**) bc_vec_item(&vm.files, i));
800 if (!strcmp(path, "")) continue;
805 if (BC_IS_BC || !has_file) bc_vm_stdin();
807 // These are all protected by ifndef NDEBUG because if these are needed, bc is
808 // goingi to exit anyway, and I see no reason to include this code in a release
809 // build when the OS is going to free all of the resources anyway.
820 void bc_vm_boot(int argc, char *argv[], const char *env_len,
821 const char* const env_args)
823 int ttyin, ttyout, ttyerr;
826 BC_SIG_ASSERT_LOCKED;
828 ttyin = isatty(STDIN_FILENO);
829 ttyout = isatty(STDOUT_FILENO);
830 ttyerr = isatty(STDERR_FILENO);
832 vm.flags |= ttyin ? BC_FLAG_TTYIN : 0;
833 vm.flags |= (ttyin != 0 && ttyout != 0 && ttyerr != 0) ? BC_FLAG_TTY : 0;
834 vm.flags |= ttyin && ttyout ? BC_FLAG_I : 0;
836 sigemptyset(&sa.sa_mask);
837 sa.sa_handler = bc_vm_sig;
838 sa.sa_flags = SA_NODEFER;
840 sigaction(SIGTERM, &sa, NULL);
841 sigaction(SIGQUIT, &sa, NULL);
842 sigaction(SIGINT, &sa, NULL);
844 #if BC_ENABLE_HISTORY
845 if (BC_TTY) sigaction(SIGHUP, &sa, NULL);
846 #endif // BC_ENABLE_HISTORY
854 bc_file_init(&vm.ferr, STDERR_FILENO, output_bufs + BC_VM_STDOUT_BUF_SIZE,
855 BC_VM_STDERR_BUF_SIZE);
856 bc_file_init(&vm.fout, STDOUT_FILENO, output_bufs, BC_VM_STDOUT_BUF_SIZE);
857 vm.buf = output_bufs + BC_VM_STDOUT_BUF_SIZE + BC_VM_STDERR_BUF_SIZE;
859 vm.line_len = (uint16_t) bc_vm_envLen(env_len);
861 bc_vec_clear(&vm.files);
862 bc_vec_clear(&vm.exprs);
864 bc_program_init(&vm.prog);
865 bc_parse_init(&vm.prs, &vm.prog, BC_PROG_MAIN);
867 #if BC_ENABLE_HISTORY
868 if (BC_TTY) bc_history_init(&vm.history);
869 #endif // BC_ENABLE_HISTORY
872 if (BC_IS_BC) vm.flags |= BC_FLAG_S * (getenv("POSIXLY_CORRECT") != NULL);
875 bc_vm_envArgs(env_args);
879 if (BC_IS_POSIX) vm.flags &= ~(BC_FLAG_G);
886 #endif // !BC_ENABLE_LIBRARY
888 void bc_vm_init(void) {
890 BC_SIG_ASSERT_LOCKED;
892 memcpy(vm.max_num, bc_num_bigdigMax,
893 bc_num_bigdigMax_size * sizeof(BcDig));
894 memcpy(vm.max2_num, bc_num_bigdigMax2,
895 bc_num_bigdigMax2_size * sizeof(BcDig));
896 bc_num_setup(&vm.max, vm.max_num, BC_NUM_BIGDIG_LOG10);
897 bc_num_setup(&vm.max2, vm.max2_num, BC_NUM_BIGDIG_LOG10);
898 vm.max.len = bc_num_bigdigMax_size;
899 vm.max2.len = bc_num_bigdigMax2_size;
901 bc_vec_init(&vm.temps, sizeof(BcNum), NULL);
903 vm.maxes[BC_PROG_GLOBALS_IBASE] = BC_NUM_MAX_POSIX_IBASE;
904 vm.maxes[BC_PROG_GLOBALS_OBASE] = BC_MAX_OBASE;
905 vm.maxes[BC_PROG_GLOBALS_SCALE] = BC_MAX_SCALE;
907 #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND
908 vm.maxes[BC_PROG_MAX_RAND] = ((BcRand) 0) - 1;
909 #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND
912 #if !BC_ENABLE_LIBRARY
913 if (BC_IS_BC && !BC_IS_POSIX)
914 #endif // !BC_ENABLE_LIBRARY
916 vm.maxes[BC_PROG_GLOBALS_IBASE] = BC_NUM_MAX_IBASE;