2 * *****************************************************************************
4 * SPDX-License-Identifier: BSD-2-Clause
6 * Copyright (c) 2018-2021 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.
49 #include <sys/types.h>
54 #define WIN32_LEAN_AND_MEAN
67 // The actual globals.
68 static BcDig* temps_buf[BC_VM_MAX_TEMPS];
69 char output_bufs[BC_VM_BUF_SIZE];
73 BC_NORETURN void bc_vm_jmp(const char* f) {
74 #else // BC_DEBUG_CODE
75 BC_NORETURN void bc_vm_jmp(void) {
83 bc_file_puts(&vm.ferr, bc_flush_none, "Longjmp: ");
84 bc_file_puts(&vm.ferr, bc_flush_none, f);
85 bc_file_putchar(&vm.ferr, bc_flush_none, '\n');
86 bc_file_flush(&vm.ferr, bc_flush_none);
87 #endif // BC_DEBUG_CODE
90 assert(vm.jmp_bufs.len - (size_t) vm.sig_pop);
93 if (vm.jmp_bufs.len == 0) abort();
94 if (vm.sig_pop) bc_vec_pop(&vm.jmp_bufs);
97 siglongjmp(*((sigjmp_buf*) bc_vec_top(&vm.jmp_bufs)), 1);
100 #if !BC_ENABLE_LIBRARY
103 * Handles signals. This is the signal handler.
104 * @param sig The signal to handle.
106 static void bc_vm_sig(int sig) {
108 // There is already a signal in flight.
109 if (vm.status == (sig_atomic_t) BC_STATUS_QUIT || vm.sig) {
110 if (!BC_I || sig != SIGINT) vm.status = BC_STATUS_QUIT;
114 // Only reset under these conditions; otherwise, quit.
115 if (sig == SIGINT && BC_SIGINT && BC_I) {
119 // Write the message.
120 if (write(STDOUT_FILENO, vm.sigmsg, vm.siglen) != (ssize_t) vm.siglen)
121 vm.status = BC_STATUS_ERROR_FATAL;
126 else vm.status = BC_STATUS_QUIT;
128 assert(vm.jmp_bufs.len);
130 // Only jump if signals are not locked. The jump will happen by whoever
132 if (!vm.sig_lock) BC_JMP;
136 * Sets up signal handling.
138 static void bc_vm_sigaction(void) {
143 sigemptyset(&sa.sa_mask);
144 sa.sa_handler = bc_vm_sig;
145 sa.sa_flags = SA_NODEFER;
147 sigaction(SIGTERM, &sa, NULL);
148 sigaction(SIGQUIT, &sa, NULL);
149 sigaction(SIGINT, &sa, NULL);
151 #if BC_ENABLE_HISTORY
152 if (BC_TTY) sigaction(SIGHUP, &sa, NULL);
153 #endif // BC_ENABLE_HISTORY
157 signal(SIGTERM, bc_vm_sig);
158 signal(SIGINT, bc_vm_sig);
163 void bc_vm_info(const char* const help) {
165 BC_SIG_ASSERT_LOCKED;
168 bc_file_puts(&vm.fout, bc_flush_none, vm.name);
169 bc_file_putchar(&vm.fout, bc_flush_none, ' ');
170 bc_file_puts(&vm.fout, bc_flush_none, BC_VERSION);
171 bc_file_putchar(&vm.fout, bc_flush_none, '\n');
172 bc_file_puts(&vm.fout, bc_flush_none, bc_copyright);
177 bc_file_putchar(&vm.fout, bc_flush_none, '\n');
182 const char* const banner = BC_DEFAULT_BANNER ? "to" : "to not";
183 const char* const sigint = BC_DEFAULT_SIGINT_RESET ? "to reset" :
185 const char* const tty = BC_DEFAULT_TTY_MODE ? "enabled" :
187 const char* const prompt = BC_DEFAULT_PROMPT ? "enabled" :
190 bc_file_printf(&vm.fout, help, vm.name, vm.name, BC_VERSION,
191 BC_BUILD_TYPE, banner, sigint, tty, prompt);
198 const char* const sigint = DC_DEFAULT_SIGINT_RESET ? "to reset" :
200 const char* const tty = DC_DEFAULT_TTY_MODE ? "enabled" :
202 const char* const prompt = DC_DEFAULT_PROMPT ? "enabled" :
205 bc_file_printf(&vm.fout, help, vm.name, vm.name, BC_VERSION,
206 BC_BUILD_TYPE, sigint, tty, prompt);
212 bc_file_flush(&vm.fout, bc_flush_none);
214 #endif // !BC_ENABLE_LIBRARY
216 #if !BC_ENABLE_LIBRARY && !BC_ENABLE_MEMCHECK
218 #endif // !BC_ENABLE_LIBRARY && !BC_ENABLE_MEMCHECK
219 void bc_vm_fatalError(BcErr e) {
221 #if !BC_ENABLE_LIBRARY && !BC_ENABLE_MEMCHECK
224 #endif // !BC_ENABLE_LIBRARY && !BC_ENABLE_MEMCHECK
227 #if BC_ENABLE_LIBRARY
228 void bc_vm_handleError(BcErr e) {
230 assert(e < BC_ERR_NELEMS);
235 // If we have a normal error...
236 if (e <= BC_ERR_MATH_DIVIDE_BY_ZERO) {
239 vm.err = (BclError) (e - BC_ERR_MATH_NEGATIVE +
240 BCL_ERROR_MATH_NEGATIVE);
242 // Abort if we should.
243 else if (vm.abrt) abort();
244 else if (e == BC_ERR_FATAL_ALLOC_ERR) vm.err = BCL_ERROR_FATAL_ALLOC_ERR;
245 else vm.err = BCL_ERROR_FATAL_UNKNOWN_ERR;
249 #else // BC_ENABLE_LIBRARY
250 void bc_vm_handleError(BcErr e, size_t line, ...) {
254 uchar id = bc_err_ids[e];
255 const char* err_type = vm.err_ids[id];
258 assert(e < BC_ERR_NELEMS);
262 // Figure out if the POSIX error should be an error, a warning, or nothing.
263 if (!BC_S && e >= BC_ERR_POSIX_START) {
265 // Make sure to not return an error.
267 err_type = vm.err_ids[BC_ERR_IDX_WARN];
273 BC_SIG_TRYLOCK(lock);
275 // Make sure all of stdout is written first.
276 s = bc_file_flushErr(&vm.fout, bc_flush_err);
278 // Just jump out if the flush failed; there's nothing we can do.
279 if (BC_ERR(s == BC_STATUS_ERROR_FATAL)) {
280 vm.status = (sig_atomic_t) s;
284 // Print the error message.
285 va_start(args, line);
286 bc_file_putchar(&vm.ferr, bc_flush_none, '\n');
287 bc_file_puts(&vm.ferr, bc_flush_none, err_type);
288 bc_file_putchar(&vm.ferr, bc_flush_none, ' ');
289 bc_file_vprintf(&vm.ferr, vm.err_msgs[e], args);
292 // Print the extra information if we have it.
293 if (BC_NO_ERR(vm.file != NULL)) {
295 // This is the condition for parsing vs runtime.
296 // If line is not 0, it is parsing.
298 bc_file_puts(&vm.ferr, bc_flush_none, "\n ");
299 bc_file_puts(&vm.ferr, bc_flush_none, vm.file);
300 bc_file_printf(&vm.ferr, bc_err_line, line);
304 BcInstPtr *ip = bc_vec_item_rev(&vm.prog.stack, 0);
305 BcFunc *f = bc_vec_item(&vm.prog.fns, ip->func);
307 bc_file_puts(&vm.ferr, bc_flush_none, "\n ");
308 bc_file_puts(&vm.ferr, bc_flush_none, vm.func_header);
309 bc_file_putchar(&vm.ferr, bc_flush_none, ' ');
310 bc_file_puts(&vm.ferr, bc_flush_none, f->name);
313 if (BC_IS_BC && ip->func != BC_PROG_MAIN &&
314 ip->func != BC_PROG_READ)
316 bc_file_puts(&vm.ferr, bc_flush_none, "()");
322 bc_file_puts(&vm.ferr, bc_flush_none, "\n\n");
324 s = bc_file_flushErr(&vm.ferr, bc_flush_err);
326 #if !BC_ENABLE_MEMCHECK
327 // Because this function is called by a BC_NORETURN function when fatal
328 // errors happen, we need to make sure to exit on fatal errors. This will
329 // be faster anyway. This function *cannot jump when a fatal error occurs!*
330 if (BC_ERR(id == BC_ERR_IDX_FATAL || s == BC_STATUS_ERROR_FATAL))
331 exit(bc_vm_atexit((int) BC_STATUS_ERROR_FATAL));
332 #else // !BC_ENABLE_MEMCHECK
333 if (BC_ERR(s == BC_STATUS_ERROR_FATAL)) vm.status = (sig_atomic_t) s;
335 #endif // !BC_ENABLE_MEMCHECK
337 vm.status = (sig_atomic_t) (uchar) (id + 1);
340 // Only jump if there is an error.
341 if (BC_ERR(vm.status)) BC_JMP;
343 BC_SIG_TRYUNLOCK(lock);
346 char* bc_vm_getenv(const char* var) {
353 _dupenv_s(&ret, NULL, var);
359 void bc_vm_getenvFree(char* val) {
367 * Sets a flag from an environment variable and the default.
368 * @param var The environment variable.
369 * @param def The default.
370 * @param flag The flag to set.
372 static void bc_vm_setenvFlag(const char* const var, int def, uint16_t flag) {
375 char* val = bc_vm_getenv(var);
377 // If there is no value...
381 if (def) vm.flags |= flag;
382 else vm.flags &= ~(flag);
385 else if (strtoul(val, NULL, 0)) vm.flags |= flag;
386 else vm.flags &= ~(flag);
388 bc_vm_getenvFree(val);
392 * Parses the arguments in {B,D]C_ENV_ARGS.
393 * @param env_args_name The environment variable to use.
395 static void bc_vm_envArgs(const char* const env_args_name) {
397 char *env_args = bc_vm_getenv(env_args_name), *buf, *start;
400 BC_SIG_ASSERT_LOCKED;
402 if (env_args == NULL) return;
404 // Windows already allocates, so we don't need to.
406 start = buf = vm.env_args_buffer = bc_vm_strdup(env_args);
408 start = buf = vm.env_args_buffer = env_args;
413 // Create two buffers for parsing. These need to stay throughout the entire
414 // execution of bc, unfortunately, because of filenames that might be in
416 bc_vec_init(&vm.env_args, sizeof(char*), BC_DTOR_NONE);
417 bc_vec_push(&vm.env_args, &env_args_name);
419 // While we haven't reached the end of the args...
422 // If we don't have whitespace...
423 if (!isspace(*buf)) {
425 // If we have the start of a string...
426 if (*buf == '"' || *buf == '\'') {
428 // Set stuff appropriately.
432 // Check for the empty string.
440 // Push the pointer to the args buffer.
441 bc_vec_push(&vm.env_args, &buf);
444 while (*buf && ((!instr && !isspace(*buf)) ||
445 (instr && *buf != instr)))
450 // If we did find the end of the string...
453 if (instr) instr = '\0';
460 else if (instr) bc_error(BC_ERR_FATAL_OPTION, 0, start);
462 // If we have whitespace, eat it.
466 // Make sure to push a NULL pointer at the end.
468 bc_vec_push(&vm.env_args, &buf);
470 // Parse the arguments.
471 bc_args((int) vm.env_args.len - 1, bc_vec_item(&vm.env_args, 0), false);
475 * Gets the {B,D}C_LINE_LENGTH.
476 * @param var The environment variable to pull it from.
477 * @return The line length.
479 static size_t bc_vm_envLen(const char *var) {
481 char *lenv = bc_vm_getenv(var);
482 size_t i, len = BC_NUM_PRINT_WIDTH;
485 // Return the default with none.
486 if (lenv == NULL) return len;
490 // Figure out if it's a number.
491 for (num = 1, i = 0; num && i < len; ++i) num = isdigit(lenv[i]);
493 // If it is a number...
496 // Parse it and clamp it if needed.
497 len = (size_t) atoi(lenv) - 1;
498 if (len == 1 || len >= UINT16_MAX) len = BC_NUM_PRINT_WIDTH;
501 else len = BC_NUM_PRINT_WIDTH;
503 bc_vm_getenvFree(lenv);
507 #endif // BC_ENABLE_LIBRARY
509 void bc_vm_shutdown(void) {
511 BC_SIG_ASSERT_LOCKED;
514 if (vm.catalog != BC_VM_INVALID_CATALOG) catclose(vm.catalog);
515 #endif // BC_ENABLE_NLS
517 #if BC_ENABLE_HISTORY
518 // This must always run to ensure that the terminal is back to normal, i.e.,
519 // has raw mode disabled.
520 if (BC_TTY) bc_history_free(&vm.history);
521 #endif // BC_ENABLE_HISTORY
524 #if !BC_ENABLE_LIBRARY
525 bc_vec_free(&vm.env_args);
526 free(vm.env_args_buffer);
527 bc_vec_free(&vm.files);
528 bc_vec_free(&vm.exprs);
530 if (BC_PARSE_IS_INITED(&vm.read_prs, &vm.prog)) {
531 bc_vec_free(&vm.read_buf);
532 bc_parse_free(&vm.read_prs);
535 bc_parse_free(&vm.prs);
536 bc_program_free(&vm.prog);
538 bc_slabvec_free(&vm.other_slabs);
539 bc_slabvec_free(&vm.main_slabs);
540 bc_slabvec_free(&vm.main_const_slab);
541 #endif // !BC_ENABLE_LIBRARY
546 #if !BC_ENABLE_LIBRARY
547 // We always want to flush.
548 bc_file_free(&vm.fout);
549 bc_file_free(&vm.ferr);
550 #endif // !BC_ENABLE_LIBRARY
553 void bc_vm_addTemp(BcDig *num) {
555 // If we don't have room, just free.
556 if (vm.temps_len == BC_VM_MAX_TEMPS) free(num);
559 // Add to the buffer and length.
560 temps_buf[vm.temps_len] = num;
565 BcDig* bc_vm_takeTemp(void) {
566 if (!vm.temps_len) return NULL;
568 return temps_buf[vm.temps_len];
571 void bc_vm_freeTemps(void) {
575 BC_SIG_ASSERT_LOCKED;
577 if (!vm.temps_len) return;
580 for (i = 0; i < vm.temps_len; ++i) free(temps_buf[i]);
585 inline size_t bc_vm_arraySize(size_t n, size_t size) {
586 size_t res = n * size;
587 if (BC_ERR(BC_VM_MUL_OVERFLOW(n, size, res)))
588 bc_vm_fatalError(BC_ERR_FATAL_ALLOC_ERR);
592 inline size_t bc_vm_growSize(size_t a, size_t b) {
594 if (BC_ERR(res >= SIZE_MAX || res < a))
595 bc_vm_fatalError(BC_ERR_FATAL_ALLOC_ERR);
599 void* bc_vm_malloc(size_t n) {
603 BC_SIG_ASSERT_LOCKED;
607 if (BC_ERR(ptr == NULL)) {
613 if (BC_ERR(ptr == NULL)) bc_vm_fatalError(BC_ERR_FATAL_ALLOC_ERR);
619 void* bc_vm_realloc(void *ptr, size_t n) {
623 BC_SIG_ASSERT_LOCKED;
625 temp = realloc(ptr, n);
627 if (BC_ERR(temp == NULL)) {
631 temp = realloc(ptr, n);
633 if (BC_ERR(temp == NULL)) bc_vm_fatalError(BC_ERR_FATAL_ALLOC_ERR);
639 char* bc_vm_strdup(const char *str) {
643 BC_SIG_ASSERT_LOCKED;
647 if (BC_ERR(s == NULL)) {
653 if (BC_ERR(s == NULL)) bc_vm_fatalError(BC_ERR_FATAL_ALLOC_ERR);
659 #if !BC_ENABLE_LIBRARY
660 void bc_vm_printf(const char *fmt, ...) {
667 bc_file_vprintf(&vm.fout, fmt, args);
674 #endif // !BC_ENABLE_LIBRARY
676 void bc_vm_putchar(int c, BcFlushType type) {
677 #if BC_ENABLE_LIBRARY
678 bc_vec_pushByte(&vm.out, (uchar) c);
679 #else // BC_ENABLE_LIBRARY
680 bc_file_putchar(&vm.fout, type, (uchar) c);
681 vm.nchars = (c == '\n' ? 0 : vm.nchars + 1);
682 #endif // BC_ENABLE_LIBRARY
685 #if !BC_ENABLE_LIBRARY
690 * Aborts with a message. This should never be called because I have carefully
691 * made sure that the calls to pledge() and unveil() are correct, but it's here
693 * @param msg The message to print.
695 BC_NORETURN static void bc_abortm(const char* msg) {
696 bc_file_puts(&vm.ferr, bc_flush_none, msg);
697 bc_file_puts(&vm.ferr, bc_flush_none, "; this is a bug");
698 bc_file_flush(&vm.ferr, bc_flush_none);
702 void bc_pledge(const char *promises, const char* execpromises) {
703 int r = pledge(promises, execpromises);
704 if (r) bc_abortm("pledge() failed");
707 #if BC_ENABLE_EXTRA_MATH
710 * A convenience and portability function for OpenBSD's unveil().
711 * @param path The path.
712 * @param permissions The permissions for the path.
714 static void bc_unveil(const char *path, const char *permissions) {
715 int r = unveil(path, permissions);
716 if (r) bc_abortm("unveil() failed");
718 #endif // BC_ENABLE_EXTRA_MATH
722 void bc_pledge(const char *promises, const char *execpromises) {
724 BC_UNUSED(execpromises);
727 #if BC_ENABLE_EXTRA_MATH
728 static void bc_unveil(const char *path, const char *permissions) {
730 BC_UNUSED(permissions);
732 #endif // BC_ENABLE_EXTRA_MATH
734 #endif // __OpenBSD__
737 * Cleans unneeded variables, arrays, functions, strings, and constants when
738 * done executing a line of stdin. This is to prevent memory usage growing
739 * without bound. This is an idea from busybox.
741 static void bc_vm_clean(void) {
743 BcVec *fns = &vm.prog.fns;
744 BcFunc *f = bc_vec_item(fns, BC_PROG_MAIN);
745 BcInstPtr *ip = bc_vec_item(&vm.prog.stack, 0);
746 bool good = ((vm.status && vm.status != BC_STATUS_QUIT) || vm.sig);
748 // If all is good, go ahead and reset.
749 if (good) bc_program_reset(&vm.prog);
752 // bc has this extra condition. If it not satisfied, it is in the middle of
754 if (good && BC_IS_BC) good = !BC_PARSE_NO_EXEC(&vm.prs);
758 // For dc, it is safe only when all of the results on the results stack are
759 // safe, which means that they are temporaries or other things that don't
760 // need strings or constants.
767 for (i = 0; good && i < vm.prog.results.len; ++i) {
768 BcResult *r = (BcResult*) bc_vec_item(&vm.prog.results, i);
769 good = BC_VM_SAFE_RESULT(r);
774 // If this condition is true, we can get rid of strings,
775 // constants, and code.
776 if (good && vm.prog.stack.len == 1 && ip->idx == f->code.len) {
781 bc_vec_popAll(&f->labels);
782 bc_vec_popAll(&f->strs);
783 bc_vec_popAll(&f->consts);
785 // I can't clear out the other_slabs because it has functions,
786 // consts, strings, vars, and arrays. It has strings from *other*
787 // functions, specifically.
788 bc_slabvec_clear(&vm.main_const_slab);
789 bc_slabvec_clear(&vm.main_slabs);
794 // Note to self: you cannot delete strings and functions. Deal with it.
796 bc_vec_popAll(vm.prog.consts);
797 bc_slabvec_clear(&vm.main_const_slab);
801 bc_vec_popAll(&f->code);
808 * Process a bunch of text.
809 * @param text The text to process.
810 * @param is_stdin True if the text came from stdin, false otherwise.
812 static void bc_vm_process(const char *text, bool is_stdin) {
814 // Set up the parser.
815 bc_parse_text(&vm.prs, text, is_stdin);
820 // If the first token is the keyword define, then we need to do this
821 // specially because bc thinks it may not be able to parse.
822 if (vm.prs.l.t == BC_LEX_KW_DEFINE) vm.parse(&vm.prs);
826 while (BC_PARSE_CAN_PARSE(vm.prs)) vm.parse(&vm.prs);
828 // Execute if possible.
829 if(BC_IS_DC || !BC_PARSE_NO_EXEC(&vm.prs)) bc_program_exec(&vm.prog);
831 assert(BC_IS_DC || vm.prog.results.len == 0);
833 // Flush in interactive mode.
834 if (BC_I) bc_file_flush(&vm.fout, bc_flush_save);
836 } while (vm.prs.l.t != BC_LEX_EOF);
842 * Ends an if statement that ends a file. This is to ensure that full parses
843 * happen when a file finishes. Without this, bc thinks that it cannot parse
844 * any further. But if we reach the end of a file, we know we can add an empty
847 static void bc_vm_endif(void) {
852 // Not a problem if this is true.
853 if (BC_NO_ERR(!BC_PARSE_NO_EXEC(&vm.prs))) return;
857 // Find an instance of a body that needs closing, i.e., a statement that did
858 // not have a right brace when it should have.
859 for (i = 0; good && i < vm.prs.flags.len; ++i) {
860 uint16_t flag = *((uint16_t*) bc_vec_item(&vm.prs.flags, i));
861 good = ((flag & BC_PARSE_FLAG_BRACE) != BC_PARSE_FLAG_BRACE);
864 // If we did not find such an instance...
867 // We set this to restore it later. We don't want the parser thinking
868 // that we are on stdin for this one because it will want more.
869 bool is_stdin = vm.is_stdin;
873 // Cheat and keep parsing empty else clauses until all of them are
875 while (BC_PARSE_IF_END(&vm.prs)) bc_vm_process("else {}", false);
877 vm.is_stdin = is_stdin;
879 // If we reach here, a block was not properly closed, and we should error.
880 else bc_parse_err(&vm.prs, BC_ERR_PARSE_BLOCK);
886 * @param file The filename.
888 static void bc_vm_file(const char *file) {
895 bc_lex_file(&vm.prs.l, file);
900 data = bc_read_file(file);
902 assert(data != NULL);
904 BC_SETJMP_LOCKED(err);
909 bc_vm_process(data, false);
912 // Make sure to end any open if statements.
913 if (BC_IS_BC) bc_vm_endif();
923 // bc_program_reset(), called by bc_vm_clean(), resets the status.
924 // We want it to clear the sig_pop variable in case it was set.
925 if (vm.status == (sig_atomic_t) BC_STATUS_SUCCESS) BC_LONGJMP_STOP;
930 bool bc_vm_readLine(bool clear) {
935 // Clear the buffer if desired.
936 if (clear) bc_vec_empty(&vm.buffer);
938 // Empty the line buffer.
939 bc_vec_empty(&vm.line_buf);
941 if (vm.eof) return false;
944 // bc_read_line() must always return either BC_STATUS_SUCCESS or
945 // BC_STATUS_EOF. Everything else, it and whatever it calls, must jump
947 s = bc_read_line(&vm.line_buf, ">>> ");
948 vm.eof = (s == BC_STATUS_EOF);
949 } while (!(s) && !vm.eof && vm.line_buf.len < 1);
951 good = (vm.line_buf.len > 1);
953 // Concat if we found something.
954 if (good) bc_vec_concat(&vm.buffer, vm.line_buf.v);
960 * Processes text from stdin.
962 static void bc_vm_stdin(void) {
969 bc_lex_file(&vm.prs.l, bc_program_stdin_name);
971 // These are global so that the dc lexer can access them, but they are tied
972 // to this function, really. Well, this and bc_vm_readLine(). These are the
973 // reason that we have vm.is_stdin to tell the dc lexer if we are reading
974 // from stdin. Well, both lexers care. And the reason they care is so that
975 // if a comment or a string goes across multiple lines, the lexer can
976 // request more data from stdin until the comment or string is ended.
978 bc_vec_init(&vm.buffer, sizeof(uchar), BC_DTOR_NONE);
979 bc_vec_init(&vm.line_buf, sizeof(uchar), BC_DTOR_NONE);
980 BC_SETJMP_LOCKED(err);
983 // This label exists because errors can cause jumps to end up at the err label
984 // below. If that happens, and the error should be cleared and execution
985 // continue, then we need to jump back.
988 // While we still read data from stdin.
989 while (bc_vm_readLine(clear)) {
991 size_t len = vm.buffer.len - 1;
992 const char *str = vm.buffer.v;
994 // We don't want to clear the buffer when the line ends with a backslash
995 // because a backslash newline is special in bc.
996 clear = (len < 2 || str[len - 2] != '\\' || str[len - 1] != '\n');
997 if (!clear) continue;
1000 bc_vm_process(vm.buffer.v, true);
1007 // End the if statements.
1008 if (BC_IS_BC) bc_vm_endif();
1009 #endif // BC_ENABLED
1017 #if !BC_ENABLE_MEMCHECK
1018 assert(vm.status != BC_STATUS_ERROR_FATAL);
1020 vm.status = vm.status == BC_STATUS_QUIT || !BC_I ?
1021 vm.status : BC_STATUS_SUCCESS;
1022 #else // !BC_ENABLE_MEMCHECK
1023 vm.status = vm.status == BC_STATUS_ERROR_FATAL ||
1024 vm.status == BC_STATUS_QUIT || !BC_I ?
1025 vm.status : BC_STATUS_SUCCESS;
1026 #endif // !BC_ENABLE_MEMCHECK
1028 if (!vm.status && !vm.eof) {
1029 bc_vec_empty(&vm.buffer);
1036 // Since these are tied to this function, free them here.
1037 bc_vec_free(&vm.line_buf);
1038 bc_vec_free(&vm.buffer);
1047 * Loads a math library.
1048 * @param name The name of the library.
1049 * @param text The text of the source code.
1051 static void bc_vm_load(const char *name, const char *text) {
1053 bc_lex_file(&vm.prs.l, name);
1054 bc_parse_text(&vm.prs, text, false);
1056 while (vm.prs.l.t != BC_LEX_EOF) vm.parse(&vm.prs);
1059 #endif // BC_ENABLED
1062 * Loads the default error messages.
1064 static void bc_vm_defaultMsgs(void) {
1068 vm.func_header = bc_err_func_header;
1070 // Load the error categories.
1071 for (i = 0; i < BC_ERR_IDX_NELEMS + BC_ENABLED; ++i)
1072 vm.err_ids[i] = bc_errs[i];
1074 // Load the error messages.
1075 for (i = 0; i < BC_ERR_NELEMS; ++i) vm.err_msgs[i] = bc_err_msgs[i];
1079 * Loads the error messages for the locale. If NLS is disabled, this just loads
1080 * the default messages.
1082 static void bc_vm_gettext(void) {
1086 int set = 1, msg = 1;
1089 // If no locale, load the defaults.
1090 if (vm.locale == NULL) {
1091 vm.catalog = BC_VM_INVALID_CATALOG;
1092 bc_vm_defaultMsgs();
1096 vm.catalog = catopen(BC_MAINEXEC, NL_CAT_LOCALE);
1098 // If no catalog, load the defaults.
1099 if (vm.catalog == BC_VM_INVALID_CATALOG) {
1100 bc_vm_defaultMsgs();
1104 // Load the function header.
1105 vm.func_header = catgets(vm.catalog, set, msg, bc_err_func_header);
1107 // Load the error categories.
1108 for (set += 1; msg <= BC_ERR_IDX_NELEMS + BC_ENABLED; ++msg)
1109 vm.err_ids[msg - 1] = catgets(vm.catalog, set, msg, bc_errs[msg - 1]);
1114 // Load the error messages. In order to understand this loop, you must know
1115 // the order of messages and categories in the enum and in the locale files.
1116 for (set = id + 3, msg = 1; i < BC_ERR_NELEMS; ++i, ++msg) {
1118 if (id != bc_err_ids[i]) {
1124 vm.err_msgs[i] = catgets(vm.catalog, set, msg, bc_err_msgs[i]);
1126 #else // BC_ENABLE_NLS
1127 bc_vm_defaultMsgs();
1128 #endif // BC_ENABLE_NLS
1132 * Starts execution. Really, this is a function of historical accident; it could
1133 * probably be combined with bc_vm_boot(), but I don't care enough. Really, this
1134 * function starts when execution of bc or dc source code starts.
1136 static void bc_vm_exec(void) {
1139 bool has_file = false;
1143 // Load the math libraries.
1144 if (BC_IS_BC && (vm.flags & BC_FLAG_L)) {
1146 // Can't allow redefinitions in the builtin library.
1147 vm.no_redefine = true;
1149 bc_vm_load(bc_lib_name, bc_lib);
1151 #if BC_ENABLE_EXTRA_MATH
1152 if (!BC_IS_POSIX) bc_vm_load(bc_lib2_name, bc_lib2);
1153 #endif // BC_ENABLE_EXTRA_MATH
1155 // Make sure to clear this.
1156 vm.no_redefine = false;
1158 // Execute to ensure that all is hunky dory. Without this, scale can be
1160 bc_program_exec(&vm.prog);
1162 #endif // BC_ENABLED
1164 // If there are expressions to execute...
1167 size_t len = vm.exprs.len - 1;
1172 // Create this as a buffer for reading into.
1173 bc_vec_init(&buf, sizeof(uchar), BC_DTOR_NONE);
1176 BC_SETJMP_LOCKED(err);
1181 // Prepare the lexer.
1182 bc_lex_file(&vm.prs.l, bc_program_exprs_name);
1184 // Process the expressions one at a time.
1187 more = bc_read_buf(&buf, vm.exprs.v, &len);
1188 bc_vec_pushByte(&buf, '\0');
1189 bc_vm_process(buf.v, false);
1191 bc_vec_popAll(&buf);
1205 // Sometimes, executing expressions means we need to quit.
1206 if (!vm.no_exprs && vm.exit_exprs) return;
1210 for (i = 0; i < vm.files.len; ++i) {
1211 char *path = *((char**) bc_vec_item(&vm.files, i));
1212 if (!strcmp(path, "")) continue;
1217 #if BC_ENABLE_EXTRA_MATH
1218 // These are needed for the pseudo-random number generator.
1219 bc_unveil("/dev/urandom", "r");
1220 bc_unveil("/dev/random", "r");
1221 bc_unveil(NULL, NULL);
1222 #endif // BC_ENABLE_EXTRA_MATH
1224 #if BC_ENABLE_HISTORY
1226 // We need to keep tty if history is enabled, and we need to keep rpath for
1227 // the times when we read from /dev/urandom.
1228 if (BC_TTY && !vm.history.badTerm) {
1229 bc_pledge(bc_pledge_end_history, NULL);
1232 #endif // BC_ENABLE_HISTORY
1234 bc_pledge(bc_pledge_end, NULL);
1238 // This is the thing that makes fuzzing with AFL++ so fast. If you move this
1239 // back, you won't cause any problems, but fuzzing will slow down. If you
1240 // move this forward, you won't fuzz anything because you will be skipping
1241 // the reading from stdin.
1243 #endif // BC_ENABLE_AFL
1245 // Execute from stdin. bc always does.
1246 if (BC_IS_BC || !has_file) bc_vm_stdin();
1248 // These are all protected by ifndef NDEBUG because if these are needed, bc is
1249 // going to exit anyway, and I see no reason to include this code in a release
1250 // build when the OS is going to free all of the resources anyway.
1261 void bc_vm_boot(int argc, char *argv[]) {
1263 int ttyin, ttyout, ttyerr;
1265 const char* const env_len = BC_IS_BC ? "BC_LINE_LENGTH" : "DC_LINE_LENGTH";
1266 const char* const env_args = BC_IS_BC ? "BC_ENV_ARGS" : "DC_ENV_ARGS";
1268 // We need to know which of stdin, stdout, and stderr are tty's.
1269 ttyin = isatty(STDIN_FILENO);
1270 ttyout = isatty(STDOUT_FILENO);
1271 ttyerr = isatty(STDERR_FILENO);
1272 tty = (ttyin != 0 && ttyout != 0 && ttyerr != 0);
1274 vm.flags |= ttyin ? BC_FLAG_TTYIN : 0;
1275 vm.flags |= tty ? BC_FLAG_TTY : 0;
1276 vm.flags |= ttyin && ttyout ? BC_FLAG_I : 0;
1281 // Initialize some vm stuff. This is separate to make things easier for the
1285 // Explicitly set this in case NULL isn't all zeroes.
1288 // Set the error messages.
1291 // Initialize the output file buffers. They each take portions of the global
1292 // buffer. stdout gets more because it will probably have more data.
1293 bc_file_init(&vm.ferr, STDERR_FILENO, output_bufs + BC_VM_STDOUT_BUF_SIZE,
1294 BC_VM_STDERR_BUF_SIZE);
1295 bc_file_init(&vm.fout, STDOUT_FILENO, output_bufs, BC_VM_STDOUT_BUF_SIZE);
1297 // Set the input buffer to the rest of the global buffer.
1298 vm.buf = output_bufs + BC_VM_STDOUT_BUF_SIZE + BC_VM_STDERR_BUF_SIZE;
1300 // Set the line length by environment variable.
1301 vm.line_len = (uint16_t) bc_vm_envLen(env_len);
1303 // Clear the files and expressions vectors, just in case. This marks them as
1305 bc_vec_clear(&vm.files);
1306 bc_vec_clear(&vm.exprs);
1308 #if !BC_ENABLE_LIBRARY
1310 // Initialize the slab vectors.
1311 bc_slabvec_init(&vm.main_const_slab);
1312 bc_slabvec_init(&vm.main_slabs);
1313 bc_slabvec_init(&vm.other_slabs);
1315 #endif // !BC_ENABLE_LIBRARY
1317 // Initialize the program and main parser. These have to be in this order
1318 // because the program has to be initialized first, since a pointer to it is
1319 // passed to the parser.
1320 bc_program_init(&vm.prog);
1321 bc_parse_init(&vm.prs, &vm.prog, BC_PROG_MAIN);
1324 // bc checks this environment variable to see if it should run in standard
1328 char* var = bc_vm_getenv("POSIXLY_CORRECT");
1330 vm.flags |= BC_FLAG_S * (var != NULL);
1331 bc_vm_getenvFree(var);
1333 #endif // BC_ENABLED
1336 vm.flags |= BC_TTY ? BC_FLAG_P | BC_FLAG_R : 0;
1337 vm.flags |= BC_I ? BC_FLAG_Q : 0;
1340 if (BC_IS_BC && BC_I) {
1341 // Set whether we print the banner or not.
1342 bc_vm_setenvFlag("BC_BANNER", BC_DEFAULT_BANNER, BC_FLAG_Q);
1344 #endif // BC_ENABLED
1346 // Are we in TTY mode?
1349 const char* const env_tty = BC_IS_BC ? "BC_TTY_MODE" : "DC_TTY_MODE";
1350 int env_tty_def = BC_IS_BC ? BC_DEFAULT_TTY_MODE : DC_DEFAULT_TTY_MODE;
1351 const char* const env_prompt = BC_IS_BC ? "BC_PROMPT" : "DC_PROMPT";
1352 int env_prompt_def = BC_IS_BC ? BC_DEFAULT_PROMPT : DC_DEFAULT_PROMPT;
1354 // Set flags for TTY mode and prompt.
1355 bc_vm_setenvFlag(env_tty, env_tty_def, BC_FLAG_TTY);
1356 bc_vm_setenvFlag(env_prompt, tty ? env_prompt_def : 0, BC_FLAG_P);
1358 #if BC_ENABLE_HISTORY
1359 // If TTY mode is used, activate history.
1360 if (BC_TTY) bc_history_init(&vm.history);
1361 #endif // BC_ENABLE_HISTORY
1364 // Process environment and command-line arguments.
1365 bc_vm_envArgs(env_args);
1366 bc_args(argc, argv, true);
1368 // If we are in interactive mode...
1371 const char* const env_sigint = BC_IS_BC ? "BC_SIGINT_RESET" :
1373 int env_sigint_def = BC_IS_BC ? BC_DEFAULT_SIGINT_RESET :
1374 DC_DEFAULT_SIGINT_RESET;
1376 // Set whether we reset on SIGINT or not.
1377 bc_vm_setenvFlag(env_sigint, env_sigint_def, BC_FLAG_SIGINT);
1381 // Disable global stacks in POSIX mode.
1382 if (BC_IS_POSIX) vm.flags &= ~(BC_FLAG_G);
1383 #endif // BC_ENABLED
1386 // Print the banner if allowed. We have to be in bc, in interactive mode,
1387 // and not be quieted by command-line option or environment variable.
1388 if (BC_IS_BC && BC_I && (vm.flags & BC_FLAG_Q)) {
1390 bc_file_putchar(&vm.fout, bc_flush_none, '\n');
1391 bc_file_flush(&vm.fout, bc_flush_none);
1393 #endif // BC_ENABLED
1400 #endif // !BC_ENABLE_LIBRARY
1402 void bc_vm_init(void) {
1404 BC_SIG_ASSERT_LOCKED;
1406 #if !BC_ENABLE_LIBRARY
1407 // Set up the constant zero.
1408 bc_num_setup(&vm.zero, vm.zero_num, BC_VM_ONE_CAP);
1409 #endif // !BC_ENABLE_LIBRARY
1411 // Set up more constant BcNum's.
1412 bc_num_setup(&vm.one, vm.one_num, BC_VM_ONE_CAP);
1413 bc_num_one(&vm.one);
1415 // Set up more constant BcNum's.
1416 memcpy(vm.max_num, bc_num_bigdigMax,
1417 bc_num_bigdigMax_size * sizeof(BcDig));
1418 memcpy(vm.max2_num, bc_num_bigdigMax2,
1419 bc_num_bigdigMax2_size * sizeof(BcDig));
1420 bc_num_setup(&vm.max, vm.max_num, BC_NUM_BIGDIG_LOG10);
1421 bc_num_setup(&vm.max2, vm.max2_num, BC_NUM_BIGDIG_LOG10);
1422 vm.max.len = bc_num_bigdigMax_size;
1423 vm.max2.len = bc_num_bigdigMax2_size;
1425 // Set up the maxes for the globals.
1426 vm.maxes[BC_PROG_GLOBALS_IBASE] = BC_NUM_MAX_POSIX_IBASE;
1427 vm.maxes[BC_PROG_GLOBALS_OBASE] = BC_MAX_OBASE;
1428 vm.maxes[BC_PROG_GLOBALS_SCALE] = BC_MAX_SCALE;
1430 #if BC_ENABLE_EXTRA_MATH
1431 vm.maxes[BC_PROG_MAX_RAND] = ((BcRand) 0) - 1;
1432 #endif // BC_ENABLE_EXTRA_MATH
1435 #if !BC_ENABLE_LIBRARY
1436 // bc has a higher max ibase when it's not in POSIX mode.
1437 if (BC_IS_BC && !BC_IS_POSIX)
1438 #endif // !BC_ENABLE_LIBRARY
1440 vm.maxes[BC_PROG_GLOBALS_IBASE] = BC_NUM_MAX_IBASE;
1442 #endif // BC_ENABLED
1445 #if BC_ENABLE_LIBRARY
1446 void bc_vm_atexit(void) {
1451 bc_vec_free(&vm.jmp_bufs);
1454 #else // BC_ENABLE_LIBRARY
1455 int bc_vm_atexit(int status) {
1457 // Set the status correctly.
1458 int s = BC_STATUS_IS_ERROR(status) ? status : BC_STATUS_SUCCESS;
1463 bc_vec_free(&vm.jmp_bufs);
1468 #endif // BC_ENABLE_LIBRARY