diff --git a/contrib/bc/Makefile.in b/contrib/bc/Makefile.in index 89ddb7589c47..f936fc2c6de6 100644 --- a/contrib/bc/Makefile.in +++ b/contrib/bc/Makefile.in @@ -1,644 +1,644 @@ # # SPDX-License-Identifier: BSD-2-Clause # # Copyright (c) 2018-2023 Gavin D. Howard and contributors. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # # %%WARNING%% # .POSIX: ROOTDIR = %%ROOTDIR%% INCDIR = $(ROOTDIR)/include SRCDIR = $(ROOTDIR)/src TESTSDIR = $(ROOTDIR)/tests SCRIPTSDIR = $(ROOTDIR)/scripts GENDIR = $(ROOTDIR)/gen BUILDDIR = %%BUILDDIR%% SRC = %%SRC%% OBJ = %%OBJ%% GCDA = %%GCDA%% GCNO = %%GCNO%% BC_ENABLED_NAME = BC_ENABLED BC_ENABLED = %%BC_ENABLED%% DC_ENABLED_NAME = DC_ENABLED DC_ENABLED = %%DC_ENABLED%% HEADERS = $(INCDIR)/args.h $(INCDIR)/file.h $(INCDIR)/lang.h $(INCDIR)/lex.h $(INCDIR)/num.h $(INCDIR)/opt.h $(INCDIR)/parse.h $(INCDIR)/program.h $(INCDIR)/read.h $(INCDIR)/status.h $(INCDIR)/vector.h $(INCDIR)/vm.h BC_HEADERS = $(INCDIR)/bc.h DC_HEADERS = $(INCDIR)/dc.h HISTORY_HEADERS = $(INCDIR)/history.h EXTRA_MATH_HEADERS = $(INCDIR)/rand.h LIBRARY_HEADERS = $(INCDIR)/bcl.h $(INCDIR)/library.h GEN_DIR = %%GEN_DIR%% GEN = %%GEN%% GEN_EXEC = $(GEN_DIR)/$(GEN) GEN_C = $(GENDIR)/$(GEN).c GEN_EMU = %%GEN_EMU%% BC_LIB = $(GENDIR)/lib.bc BC_LIB_C = $(GEN_DIR)/lib.c BC_LIB_O = %%BC_LIB_O%% BC_LIB_GCDA = $(GEN_DIR)/lib.gcda BC_LIB_GCNO = $(GEN_DIR)/lib.gcno BC_LIB2 = $(GENDIR)/lib2.bc BC_LIB2_C = $(GEN_DIR)/lib2.c BC_LIB2_O = %%BC_LIB2_O%% BC_LIB2_GCDA = $(GEN_DIR)/lib2.gcda BC_LIB2_GCNO = $(GEN_DIR)/lib2.gcno BC_HELP = $(GENDIR)/bc_help.txt BC_HELP_C = $(GEN_DIR)/bc_help.c BC_HELP_O = %%BC_HELP_O%% BC_HELP_GCDA = $(GEN_DIR)/bc_help.gcda BC_HELP_GCNO = $(GEN_DIR)/bc_help.gcno DC_HELP = $(GENDIR)/dc_help.txt DC_HELP_C = $(GEN_DIR)/dc_help.c DC_HELP_O = %%DC_HELP_O%% DC_HELP_GCDA = $(GEN_DIR)/dc_help.gcda DC_HELP_GCNO = $(GEN_DIR)/dc_help.gcno BIN = bin EXEC_SUFFIX = %%EXECSUFFIX%% EXEC_PREFIX = %%EXECPREFIX%% BC = bc DC = dc BC_EXEC = $(BIN)/$(EXEC_PREFIX)$(BC) DC_EXEC = $(BIN)/$(EXEC_PREFIX)$(DC) BC_TEST_OUTPUTS = tests/bc_outputs BC_FUZZ_OUTPUTS = tests/fuzzing/bc_outputs1 tests/fuzzing/bc_outputs2 tests/fuzzing/bc_outputs3 DC_TEST_OUTPUTS = tests/dc_outputs DC_FUZZ_OUTPUTS = tests/fuzzing/dc_outputs LIB = libbcl LIB_NAME = $(LIB).a LIBBC = $(BIN)/$(LIB_NAME) BCL = bcl BCL_TEST = $(BIN)/$(BCL) BCL_TEST_C = $(TESTSDIR)/$(BCL).c MANUALS = manuals BC_MANPAGE_NAME = $(EXEC_PREFIX)$(BC)$(EXEC_SUFFIX).1 BC_MANPAGE = $(MANUALS)/$(BC).1 BC_MD = $(BC_MANPAGE).md DC_MANPAGE_NAME = $(EXEC_PREFIX)$(DC)$(EXEC_SUFFIX).1 DC_MANPAGE = $(MANUALS)/$(DC).1 DC_MD = $(DC_MANPAGE).md BCL_MANPAGE_NAME = bcl.3 BCL_MANPAGE = $(MANUALS)/$(BCL_MANPAGE_NAME) BCL_MD = $(BCL_MANPAGE).md MANPAGE_INSTALL_ARGS = -Dm644 BINARY_INSTALL_ARGS = -Dm755 PC_INSTALL_ARGS = $(MANPAGE_INSTALL_ARGS) BCL_PC = $(BCL).pc PC_PATH = %%PC_PATH%% BCL_HEADER_NAME = bcl.h BCL_HEADER = $(INCDIR)/$(BCL_HEADER_NAME) %%DESTDIR%% BINDIR = %%BINDIR%% INCLUDEDIR = %%INCLUDEDIR%% LIBDIR = %%LIBDIR%% MAN1DIR = %%MAN1DIR%% MAN3DIR = %%MAN3DIR%% MAIN_EXEC = $(EXEC_PREFIX)$(%%MAIN_EXEC%%)$(EXEC_SUFFIX) EXEC = $(%%EXEC%%) NLSPATH = %%NLSPATH%% BC_BUILD_TYPE = %%BUILD_TYPE%% BC_ENABLE_LIBRARY = %%LIBRARY%% BC_ENABLE_HISTORY = %%HISTORY%% BC_ENABLE_EXTRA_MATH_NAME = BC_ENABLE_EXTRA_MATH BC_ENABLE_EXTRA_MATH = %%EXTRA_MATH%% BC_ENABLE_NLS = %%NLS%% BC_EXCLUDE_EXTRA_MATH = %%EXCLUDE_EXTRA_MATH%% BC_ENABLE_AFL = %%FUZZ%% BC_ENABLE_MEMCHECK = %%MEMCHECK%% BC_DEFAULT_BANNER = %%BC_DEFAULT_BANNER%% BC_DEFAULT_SIGINT_RESET = %%BC_DEFAULT_SIGINT_RESET%% DC_DEFAULT_SIGINT_RESET = %%DC_DEFAULT_SIGINT_RESET%% BC_DEFAULT_TTY_MODE = %%BC_DEFAULT_TTY_MODE%% DC_DEFAULT_TTY_MODE = %%DC_DEFAULT_TTY_MODE%% BC_DEFAULT_PROMPT = %%BC_DEFAULT_PROMPT%% DC_DEFAULT_PROMPT = %%DC_DEFAULT_PROMPT%% BC_DEFAULT_EXPR_EXIT = %%BC_DEFAULT_EXPR_EXIT%% DC_DEFAULT_EXPR_EXIT = %%DC_DEFAULT_EXPR_EXIT%% BC_DEFAULT_DIGIT_CLAMP = %%BC_DEFAULT_DIGIT_CLAMP%% DC_DEFAULT_DIGIT_CLAMP = %%DC_DEFAULT_DIGIT_CLAMP%% RM = rm MKDIR = mkdir SCRIPTS = ./scripts MINISTAT = ministat MINISTAT_EXEC = $(SCRIPTS)/$(MINISTAT) BITFUNCGEN = bitfuncgen BITFUNCGEN_EXEC = $(SCRIPTS)/$(BITFUNCGEN) INSTALL = $(SCRIPTSDIR)/exec-install.sh SAFE_INSTALL = $(SCRIPTSDIR)/safe-install.sh LINK = $(SCRIPTSDIR)/link.sh MANPAGE = $(SCRIPTSDIR)/manpage.sh KARATSUBA = $(SCRIPTSDIR)/karatsuba.py LOCALE_INSTALL = $(SCRIPTSDIR)/locale_install.sh LOCALE_UNINSTALL = $(SCRIPTSDIR)/locale_uninstall.sh VALGRIND_ARGS = --error-exitcode=100 --leak-check=full --show-leak-kinds=all --errors-for-leak-kinds=all TEST_STARS = *********************************************************************** BC_NUM_KARATSUBA_LEN = %%KARATSUBA_LEN%% BC_DEFS0 = -DBC_DEFAULT_BANNER=$(BC_DEFAULT_BANNER) BC_DEFS1 = -DBC_DEFAULT_SIGINT_RESET=$(BC_DEFAULT_SIGINT_RESET) BC_DEFS2 = -DBC_DEFAULT_TTY_MODE=$(BC_DEFAULT_TTY_MODE) BC_DEFS3 = -DBC_DEFAULT_PROMPT=$(BC_DEFAULT_PROMPT) BC_DEFS4 = -DBC_DEFAULT_EXPR_EXIT=$(BC_DEFAULT_EXPR_EXIT) BC_DEFS5 = -DBC_DEFAULT_DIGIT_CLAMP=$(BC_DEFAULT_DIGIT_CLAMP) BC_DEFS = $(BC_DEFS0) $(BC_DEFS1) $(BC_DEFS2) $(BC_DEFS3) $(BC_DEFS4) $(BC_DEFS5) DC_DEFS1 = -DDC_DEFAULT_SIGINT_RESET=$(DC_DEFAULT_SIGINT_RESET) DC_DEFS2 = -DDC_DEFAULT_TTY_MODE=$(DC_DEFAULT_TTY_MODE) DC_DEFS3 = -DDC_DEFAULT_PROMPT=$(DC_DEFAULT_PROMPT) DC_DEFS4 = -DDC_DEFAULT_EXPR_EXIT=$(DC_DEFAULT_EXPR_EXIT) DC_DEFS5 = -DDC_DEFAULT_DIGIT_CLAMP=$(DC_DEFAULT_DIGIT_CLAMP) DC_DEFS = $(DC_DEFS1) $(DC_DEFS2) $(DC_DEFS3) $(DC_DEFS4) $(DC_DEFS5) CPPFLAGS1 = -D$(BC_ENABLED_NAME)=$(BC_ENABLED) -D$(DC_ENABLED_NAME)=$(DC_ENABLED) CPPFLAGS2 = $(CPPFLAGS1) -I$(INCDIR)/ -DBUILD_TYPE=$(BC_BUILD_TYPE) %%LONG_BIT_DEFINE%% CPPFLAGS3 = $(CPPFLAGS2) -DEXECPREFIX=$(EXEC_PREFIX) -DMAINEXEC=$(MAIN_EXEC) CPPFLAGS4 = $(CPPFLAGS3) %%BSD%% CPPFLAGS5 = $(CPPFLAGS4) -DBC_NUM_KARATSUBA_LEN=$(BC_NUM_KARATSUBA_LEN) CPPFLAGS6 = $(CPPFLAGS5) -DBC_ENABLE_NLS=$(BC_ENABLE_NLS) CPPFLAGS7 = $(CPPFLAGS6) -D$(BC_ENABLE_EXTRA_MATH_NAME)=$(BC_ENABLE_EXTRA_MATH) CPPFLAGS8 = $(CPPFLAGS7) -DBC_ENABLE_HISTORY=$(BC_ENABLE_HISTORY) -DBC_ENABLE_LIBRARY=$(BC_ENABLE_LIBRARY) CPPFLAGS = $(CPPFLAGS8) -DBC_ENABLE_MEMCHECK=$(BC_ENABLE_MEMCHECK) -DBC_ENABLE_AFL=$(BC_ENABLE_AFL) CFLAGS = $(CPPFLAGS) $(BC_DEFS) $(DC_DEFS) %%CPPFLAGS%% %%CFLAGS%% LDFLAGS = %%LDFLAGS%% HOSTCFLAGS = %%HOSTCFLAGS%% CC = %%CC%% HOSTCC = %%HOSTCC%% BC_LIB_C_ARGS = bc_lib bc_lib_name $(BC_ENABLED_NAME) 1 BC_LIB2_C_ARGS = bc_lib2 bc_lib2_name "$(BC_ENABLED_NAME) && $(BC_ENABLE_EXTRA_MATH_NAME)" 1 OBJS = $(DC_HELP_O) $(BC_HELP_O) $(BC_LIB_O) $(BC_LIB2_O) $(OBJ) all: %%DEFAULT_TARGET%% %%DEFAULT_TARGET%%: %%DEFAULT_TARGET_PREREQS%% %%DEFAULT_TARGET_CMD%% %%SECOND_TARGET%%: %%SECOND_TARGET_PREREQS%% %%SECOND_TARGET_CMD%% $(GEN_DIR): mkdir -p $(GEN_DIR) $(GEN_EXEC): $(GEN_DIR) %%GEN_EXEC_TARGET%% $(BC_LIB_C): $(GEN_EXEC) $(BC_LIB) $(GEN_EMU) $(GEN_EXEC) $(BC_LIB) $(BC_LIB_C) $(BC_EXCLUDE_EXTRA_MATH) $(BC_LIB_C_ARGS) "" "" 1 $(BC_LIB_O): $(BC_LIB_C) $(CC) $(CFLAGS) -o $@ -c $< $(BC_LIB2_C): $(GEN_EXEC) $(BC_LIB2) $(GEN_EMU) $(GEN_EXEC) $(BC_LIB2) $(BC_LIB2_C) $(BC_EXCLUDE_EXTRA_MATH) $(BC_LIB2_C_ARGS) "" "" 1 $(BC_LIB2_O): $(BC_LIB2_C) $(CC) $(CFLAGS) -o $@ -c $< $(BC_HELP_C): $(GEN_EXEC) $(BC_HELP) $(GEN_EMU) $(GEN_EXEC) $(BC_HELP) $(BC_HELP_C) $(BC_EXCLUDE_EXTRA_MATH) bc_help "" $(BC_ENABLED_NAME) 0 $(BC_HELP_O): $(BC_HELP_C) $(CC) $(CFLAGS) -o $@ -c $< $(DC_HELP_C): $(GEN_EXEC) $(DC_HELP) $(GEN_EMU) $(GEN_EXEC) $(DC_HELP) $(DC_HELP_C) $(BC_EXCLUDE_EXTRA_MATH) dc_help "" $(DC_ENABLED_NAME) 0 $(DC_HELP_O): $(DC_HELP_C) $(CC) $(CFLAGS) -o $@ -c $< $(BIN): $(MKDIR) -p $(BIN) src: $(MKDIR) -p src headers: %%HEADERS%% $(MINISTAT): mkdir -p $(SCRIPTS) $(HOSTCC) $(HOSTCFLAGS) -lm -o $(MINISTAT_EXEC) $(ROOTDIR)/scripts/ministat.c $(BITFUNCGEN): mkdir -p $(SCRIPTS) $(HOSTCC) $(HOSTCFLAGS) -lm -o $(BITFUNCGEN_EXEC) $(ROOTDIR)/scripts/bitfuncgen.c help: @printf 'available targets:\n' @printf '\n' @printf ' all (default) builds %%EXECUTABLES%%\n' @printf ' check alias for `make test`\n' @printf ' clean removes all build files\n' @printf ' clean_config removes all build files as well as the generated Makefile\n' @printf ' clean_tests removes all build files, the generated Makefile,\n' @printf ' and generated tests\n' @printf ' install installs binaries to "%s%s"\n' "$(DESTDIR)" "$(BINDIR)" @printf ' and (if enabled) manpages to "%s%s"\n' "$(DESTDIR)" "$(MAN1DIR)" @printf ' karatsuba runs the karatsuba script (requires Python 3)\n' @printf ' karatsuba_test runs the karatsuba script while running tests\n' @printf ' (requires Python 3)\n' @printf ' uninstall uninstalls binaries from "%s%s"\n' "$(DESTDIR)" "$(BINDIR)" @printf ' and (if enabled) manpages from "%s%s"\n' "$(DESTDIR)" "$(MAN1DIR)" @printf ' test runs the test suite\n' @printf ' test_bc runs the bc test suite, if bc has been built\n' @printf ' test_dc runs the dc test suite, if dc has been built\n' @printf ' time_test runs the test suite, displaying times for some things\n' @printf ' time_test_bc runs the bc test suite, displaying times for some things\n' @printf ' time_test_dc runs the dc test suite, displaying times for some things\n' @printf ' timeconst runs the test on the Linux timeconst.bc script,\n' @printf ' if it exists and bc has been built\n' run_all_tests: bc_all_tests timeconst_all_tests dc_all_tests run_all_tests_np: bc_all_tests_np timeconst_all_tests dc_all_tests_np bc_all_tests: %%BC_ALL_TESTS%% bc_all_tests_np: %%BC_ALL_TESTS_NP%% timeconst_all_tests: %%TIMECONST_ALL_TESTS%% dc_all_tests: %%DC_ALL_TESTS%% dc_all_tests_np: %%DC_ALL_TESTS_NP%% history_all_tests: %%HISTORY_TESTS%% check: test test: %%TESTS%% test_bc: test_bc_header test_bc_tests test_bc_scripts test_bc_errors test_bc_stdin test_bc_read test_bc_other @printf '\nAll bc tests passed.\n\n$(TEST_STARS)\n' test_bc_tests:%%BC_TESTS%% test_bc_scripts:%%BC_SCRIPT_TESTS%% test_bc_stdin: @export BC_TEST_OUTPUT_DIR="$(BUILDDIR)/tests"; sh $(TESTSDIR)/stdin.sh bc %%BC_TEST_EXEC%% test_bc_read: @export BC_TEST_OUTPUT_DIR="$(BUILDDIR)/tests"; sh $(TESTSDIR)/read.sh bc %%BC_TEST_EXEC%% test_bc_errors: test_bc_error_lines%%BC_ERROR_TESTS%% test_bc_error_lines: @export BC_TEST_OUTPUT_DIR="$(BUILDDIR)/tests"; sh $(TESTSDIR)/errors.sh bc %%BC_TEST_EXEC%% test_bc_other: @export BC_TEST_OUTPUT_DIR="$(BUILDDIR)/tests"; sh $(TESTSDIR)/other.sh bc $(BC_ENABLE_EXTRA_MATH) %%BC_TEST_EXEC%% test_bc_header: @printf '$(TEST_STARS)\n\nRunning bc tests...\n\n' test_dc: test_dc_header test_dc_tests test_dc_scripts test_dc_errors test_dc_stdin test_dc_read test_dc_other @printf '\nAll dc tests passed.\n\n$(TEST_STARS)\n' test_dc_tests:%%DC_TESTS%% test_dc_scripts:%%DC_SCRIPT_TESTS%% test_dc_stdin: @export BC_TEST_OUTPUT_DIR="$(BUILDDIR)/tests"; sh $(TESTSDIR)/stdin.sh dc %%DC_TEST_EXEC%% test_dc_read: @export BC_TEST_OUTPUT_DIR="$(BUILDDIR)/tests"; sh $(TESTSDIR)/read.sh dc %%DC_TEST_EXEC%% test_dc_errors: test_dc_error_lines%%DC_ERROR_TESTS%% test_dc_error_lines: @export BC_TEST_OUTPUT_DIR="$(BUILDDIR)/tests"; sh $(TESTSDIR)/errors.sh dc %%DC_TEST_EXEC%% test_dc_other: @export BC_TEST_OUTPUT_DIR="$(BUILDDIR)/tests"; sh $(TESTSDIR)/other.sh dc $(BC_ENABLE_EXTRA_MATH) %%DC_TEST_EXEC%% test_dc_header: @printf '$(TEST_STARS)\n\nRunning dc tests...\n\n' timeconst: %%TIMECONST%% test_history: test_history_header test_bc_history test_dc_history @printf '\nAll history tests passed.\n\n$(TEST_STARS)\n' test_bc_history:%%BC_HISTORY_TEST_PREREQS%% test_bc_history_all: test_bc_history0 test_bc_history1 test_bc_history2 test_bc_history3 test_bc_history4 test_bc_history5 test_bc_history6 test_bc_history7 test_bc_history8 test_bc_history9 test_bc_history10 test_bc_history11 test_bc_history12 test_bc_history13 test_bc_history14 test_bc_history15 test_bc_history16 test_bc_history17 test_bc_history18 test_bc_history19 test_bc_history20 test_bc_history21 test_bc_history_skip: @printf 'No bc history tests to run\n' test_bc_history0: @sh $(TESTSDIR)/history.sh bc 0 %%BC_TEST_EXEC%% test_bc_history1: @sh $(TESTSDIR)/history.sh bc 1 %%BC_TEST_EXEC%% test_bc_history2: @sh $(TESTSDIR)/history.sh bc 2 %%BC_TEST_EXEC%% test_bc_history3: @sh $(TESTSDIR)/history.sh bc 3 %%BC_TEST_EXEC%% test_bc_history4: @sh $(TESTSDIR)/history.sh bc 4 %%BC_TEST_EXEC%% test_bc_history5: @sh $(TESTSDIR)/history.sh bc 5 %%BC_TEST_EXEC%% test_bc_history6: @sh $(TESTSDIR)/history.sh bc 6 %%BC_TEST_EXEC%% test_bc_history7: @sh $(TESTSDIR)/history.sh bc 7 %%BC_TEST_EXEC%% test_bc_history8: @sh $(TESTSDIR)/history.sh bc 8 %%BC_TEST_EXEC%% test_bc_history9: @sh $(TESTSDIR)/history.sh bc 9 %%BC_TEST_EXEC%% test_bc_history10: @sh $(TESTSDIR)/history.sh bc 10 %%BC_TEST_EXEC%% test_bc_history11: @sh $(TESTSDIR)/history.sh bc 11 %%BC_TEST_EXEC%% test_bc_history12: @sh $(TESTSDIR)/history.sh bc 12 %%BC_TEST_EXEC%% test_bc_history13: @sh $(TESTSDIR)/history.sh bc 13 %%BC_TEST_EXEC%% test_bc_history14: @sh $(TESTSDIR)/history.sh bc 14 %%BC_TEST_EXEC%% test_bc_history15: @sh $(TESTSDIR)/history.sh bc 15 %%BC_TEST_EXEC%% test_bc_history16: @sh $(TESTSDIR)/history.sh bc 16 %%BC_TEST_EXEC%% test_bc_history17: @sh $(TESTSDIR)/history.sh bc 17 %%BC_TEST_EXEC%% test_bc_history18: @sh $(TESTSDIR)/history.sh bc 18 %%BC_TEST_EXEC%% test_bc_history19: @sh $(TESTSDIR)/history.sh bc 19 %%BC_TEST_EXEC%% test_bc_history20: @sh $(TESTSDIR)/history.sh bc 20 %%BC_TEST_EXEC%% test_bc_history21: @sh $(TESTSDIR)/history.sh bc 21 %%BC_TEST_EXEC%% test_dc_history:%%DC_HISTORY_TEST_PREREQS%% test_dc_history_all: test_dc_history0 test_dc_history1 test_dc_history2 test_dc_history3 test_dc_history4 test_dc_history5 test_dc_history6 test_dc_history7 test_dc_history8 test_dc_history9 test_dc_history10 test_dc_history_skip: @printf 'No dc history tests to run\n' test_dc_history0: @sh $(TESTSDIR)/history.sh dc 0 %%DC_TEST_EXEC%% test_dc_history1: @sh $(TESTSDIR)/history.sh dc 1 %%DC_TEST_EXEC%% test_dc_history2: @sh $(TESTSDIR)/history.sh dc 2 %%DC_TEST_EXEC%% test_dc_history3: @sh $(TESTSDIR)/history.sh dc 3 %%DC_TEST_EXEC%% test_dc_history4: @sh $(TESTSDIR)/history.sh dc 4 %%DC_TEST_EXEC%% test_dc_history5: @sh $(TESTSDIR)/history.sh dc 5 %%DC_TEST_EXEC%% test_dc_history6: @sh $(TESTSDIR)/history.sh dc 6 %%DC_TEST_EXEC%% test_dc_history7: @sh $(TESTSDIR)/history.sh dc 7 %%DC_TEST_EXEC%% test_dc_history8: @sh $(TESTSDIR)/history.sh dc 8 %%DC_TEST_EXEC%% test_dc_history9: @sh $(TESTSDIR)/history.sh dc 9 %%DC_TEST_EXEC%% test_dc_history10: @sh $(TESTSDIR)/history.sh dc 10 %%DC_TEST_EXEC%% test_history_header: @printf '$(TEST_STARS)\n\nRunning history tests...\n\n' library_test: $(LIBBC) $(CC) $(CFLAGS) -lpthread $(BCL_TEST_C) $(LIBBC) -o $(BCL_TEST) test_library: library_test %%BCL_TEST_EXEC%% karatsuba: %%KARATSUBA%% karatsuba_test: %%KARATSUBA_TEST%% coverage_output: %%COVERAGE_OUTPUT%% coverage:%%COVERAGE_PREREQS%% manpages: $(MANPAGE) bc $(MANPAGE) dc $(MANPAGE) bcl clean_gen: @$(RM) -f $(GEN_EXEC) clean:%%CLEAN_PREREQS%% @printf 'Cleaning files...\n' @$(RM) -f src/*.tmp gen/*.tmp @$(RM) -f $(OBJ) @$(RM) -f $(BC_EXEC) @$(RM) -f $(DC_EXEC) @$(RM) -fr $(BIN) @$(RM) -f $(BC_LIB_C) $(BC_LIB_O) @$(RM) -f $(BC_LIB2_C) $(BC_LIB2_O) @$(RM) -f $(BC_HELP_C) $(BC_HELP_O) @$(RM) -f $(DC_HELP_C) $(DC_HELP_O) @$(RM) -fr vs/bin/ vs/lib/ - @$(RM) -f $(BCL_PC) clean_benchmarks: @printf 'Cleaning benchmarks...\n' @$(RM) -f $(MINISTAT_EXEC) @$(RM) -f $(ROOTDIR)/benchmarks/bc/*.txt @$(RM) -f $(ROOTDIR)/benchmarks/dc/*.txt clean_config: clean clean_benchmarks @printf 'Cleaning config...\n' @$(RM) -f Makefile @$(RM) -f $(BC_MD) $(BC_MANPAGE) @$(RM) -f $(DC_MD) $(DC_MANPAGE) @$(RM) -f compile_commands.json + @$(RM) -f $(BCL_PC) clean_coverage: @printf 'Cleaning coverage files...\n' @$(RM) -f *.gcov @$(RM) -f *.html @$(RM) -f *.gcda *.gcno @$(RM) -f *.profraw @$(RM) -f $(GCDA) $(GCNO) @$(RM) -f $(BC_GCDA) $(BC_GCNO) @$(RM) -f $(DC_GCDA) $(DC_GCNO) @$(RM) -f $(HISTORY_GCDA) $(HISTORY_GCNO) @$(RM) -f $(RAND_GCDA) $(RAND_GCNO) @$(RM) -f $(BC_LIB_GCDA) $(BC_LIB_GCNO) @$(RM) -f $(BC_LIB2_GCDA) $(BC_LIB2_GCNO) @$(RM) -f $(BC_HELP_GCDA) $(BC_HELP_GCNO) @$(RM) -f $(DC_HELP_GCDA) $(DC_HELP_GCNO) clean_tests: clean clean_config clean_coverage @printf 'Cleaning test files...\n' @$(RM) -fr $(BC_TEST_OUTPUTS) $(DC_TEST_OUTPUTS) @$(RM) -fr $(BC_FUZZ_OUTPUTS) $(DC_FUZZ_OUTPUTS) @$(RM) -f $(TESTSDIR)/bc/parse.txt $(TESTSDIR)/bc/parse_results.txt @$(RM) -f $(TESTSDIR)/bc/print.txt $(TESTSDIR)/bc/print_results.txt @$(RM) -f $(TESTSDIR)/bc/bessel.txt $(TESTSDIR)/bc/bessel_results.txt @$(RM) -f $(TESTSDIR)/bc/strings2.txt $(TESTSDIR)/bc/strings2_results.txt @$(RM) -f $(TESTSDIR)/bc/scripts/bessel.txt @$(RM) -f $(TESTSDIR)/bc/scripts/parse.txt @$(RM) -f $(TESTSDIR)/bc/scripts/print.txt @$(RM) -f $(TESTSDIR)/bc/scripts/add.txt @$(RM) -f $(TESTSDIR)/bc/scripts/divide.txt @$(RM) -f $(TESTSDIR)/bc/scripts/multiply.txt @$(RM) -f $(TESTSDIR)/bc/scripts/subtract.txt @$(RM) -f $(TESTSDIR)/bc/scripts/strings2.txt @$(RM) -f $(TESTSDIR)/dc/scripts/prime.txt @$(RM) -f .log_*.txt @$(RM) -f .math.txt .results.txt .ops.txt @$(RM) -f .test.txt @$(RM) -f tags .gdbbreakpoints .gdb_history .gdbsetup @$(RM) -f cscope.* @$(RM) -f bc.old @$(RM) -f $(BITFUNCGEN_EXEC) install_locales: %%INSTALL_LOCALES%% install_bc_manpage: $(SAFE_INSTALL) $(MANPAGE_INSTALL_ARGS) $(BC_MANPAGE) $(DESTDIR)$(MAN1DIR)/$(BC_MANPAGE_NAME) install_dc_manpage: $(SAFE_INSTALL) $(MANPAGE_INSTALL_ARGS) $(DC_MANPAGE) $(DESTDIR)$(MAN1DIR)/$(DC_MANPAGE_NAME) install_bcl_manpage: $(SAFE_INSTALL) $(MANPAGE_INSTALL_ARGS) $(BCL_MANPAGE) $(DESTDIR)$(MAN3DIR)/$(BCL_MANPAGE_NAME) install_bcl_header: $(SAFE_INSTALL) $(MANPAGE_INSTALL_ARGS) $(BCL_HEADER) $(DESTDIR)$(INCLUDEDIR)/$(BCL_HEADER_NAME) install_execs: $(INSTALL) $(DESTDIR)$(BINDIR) "$(EXEC_SUFFIX)" "$(BUILDDIR)/bin" install_library: install_bcl_header $(SAFE_INSTALL) $(BINARY_INSTALL_ARGS) $(LIBBC) $(DESTDIR)$(LIBDIR)/$(LIB_NAME) %%PKG_CONFIG_INSTALL%% install:%%INSTALL_LOCALES_PREREQS%%%%INSTALL_MAN_PREREQS%%%%INSTALL_PREREQS%% uninstall_locales: $(LOCALE_UNINSTALL) $(NLSPATH) $(MAIN_EXEC) $(DESTDIR) uninstall_bc_manpage: $(RM) -f $(DESTDIR)$(MAN1DIR)/$(BC_MANPAGE_NAME) uninstall_bc: $(RM) -f $(DESTDIR)$(BINDIR)/$(EXEC_PREFIX)$(BC)$(EXEC_SUFFIX) uninstall_dc_manpage: $(RM) -f $(DESTDIR)$(MAN1DIR)/$(DC_MANPAGE_NAME) uninstall_dc: $(RM) -f $(DESTDIR)$(BINDIR)/$(EXEC_PREFIX)$(DC)$(EXEC_SUFFIX) uninstall_library: uninstall_bcl_header $(RM) -f $(DESTDIR)$(LIBDIR)/$(LIB_NAME) %%PKG_CONFIG_UNINSTALL%% uninstall_bcl_header: $(RM) -f $(DESTDIR)$(INCLUDEDIR)/$(BCL_HEADER_NAME) uninstall_bcl_manpage: $(RM) -f $(DESTDIR)$(MAN3DIR)/$(BCL_MANPAGE_NAME) uninstall:%%UNINSTALL_LOCALES_PREREQS%%%%UNINSTALL_MAN_PREREQS%%%%UNINSTALL_PREREQS%% diff --git a/contrib/bc/NEWS.md b/contrib/bc/NEWS.md index ad118e401c32..6dff6822fb16 100644 --- a/contrib/bc/NEWS.md +++ b/contrib/bc/NEWS.md @@ -1,1475 +1,1494 @@ # News +## 6.4.0 + +This is a production release that fixes a `read()`/`?` bug and adds features to +`bcl`. + +The bug was that multiple read calls could repeat old data. + +The new features in `bcl` are functions to preserve `BclNumber` arguments and +not free them. + +***WARNING for `bcl` Users***: The `bcl_rand_seedWithNum()` function used to not +consume its arguments. Now it does. This change could have made this version +`7.0.0`, but I'm 99.9% confident that there are no `bcl` users, or if there are, +they probably don't use the PRNG. So I took a risk and didn't update the major +version. + +`bcl` now includes more capacity to check for invalid numbers when built to run +under Valgrind. + ## 6.3.1 This is a production release that fixes a `bc` dependency loop for minimal environments and Linux from Scratch. ## 6.3.0 This is a production release with a couple of fixes for manuals and a new feature for `dc`: there is now a command to query whether extended registers are enabled or not. Users who don't care do not need to upgrade. ## 6.2.6 This is a production release that fixes an install bug that affected locale installation of all locales when using `mksh`. Users do ***NOT*** need to upgrade if they don't use `mksh` and/or don't need to install all locales. ## 6.2.5 This is a production release that fixes a test bug that affected Android and `mksh`. Users do ***NOT*** need to upgrade unless they use `mksh` or another affected shell and need to run the test suite. ## 6.2.4 This is a production release that fixes a test failure that happens when `tests/bc/scripts/timeconst.bc` doesn't exist. This should only affect packagers. This bug happened because I forgot something I added in the previous release: better error checking in tests to help packagers. Unfortunately, I was too zealous with the error checking. ## 6.2.3 This is a production release that moves `bc` to . That's all it does: update links. Users do ***NOT*** need to upgrade; there are redirects that will stay in place indefinitely. This release is only for new users. ## 6.2.2 This is a production release that fixes a bug. The bug was that if an array element was used as a parameter, and then a later parameter had the same name as the array whose element was used, `bc` would grab the element from the new array parameter, not the actual element from before the function call. ## 6.2.1 This is a production release with one bug fix for a memory bug in history. ## 6.2.0 This is a production release with a new feature and a few bug fixes. The bug fixes include: * A crash when `bc` and `dc` are built using editline, but history is not activated. * A missing local in the `uint*()` family of functions in the extended math library. * A failure to clear the tail call list in `dc` on error. * A crash when attempting to swap characters in command-line history when no characters exist. * `SIGWINCH` was activated even when history was not. The new feature is that stack traces are now given for runtime errors. In debug mode, the C source file and line of errors are given as well. ## 6.1.1 This is a production release that fixes a build issue with predefined builds and generated tests. ## 6.1.0 This is a production release that fixes a discrepancy from the `bc` standard, a couple of memory bugs, and adds new features. The discrepancy from the `bc` standard was with regards to the behavior of the `quit` command. This `bc` used to quit whenever it encountered `quit` during parsing, even if it was parsing a full file. Now, `bc` only quits when encountering `quit` *after* it has executed all executable statements up to that point. This behavior is slightly different from GNU `bc`, but users will only notice the difference if they put `quit` on the same line as other statements. The first memory bug could be reproduced by assigning a string to a non-local variable in a function, then redefining the function with use of the same non-local variable, which would still refer to a string in the previous version of the function. The second memory bug was caused by passing an array argument to the `asciify()` built-in function. In certain cases, that was wrongly allowed, and the interpreter just assumed everything was correct and accessed memory. Now that arrays are allowed as arguments (see below), this is not an issue. The first feature was the addition of the `is_number()` built-in function (`u` in `dc`) that returns 1 if the runtime argument is a number and 0 otherwise. The second feature was the addition of the `is_string()` built-in function (`t` in `dc`) that returns 1 if the runtime argument is a string and 0 otherwise. These features were added because I realized that type-checking is necessary now that strings can be assigned to variables in `bc` and because they've always been assignable to variables in `dc`. The last added feature is the ability of the `asciify()` built-in function in `bc` to convert a full array of numbers into a string. This means that character-by-character printing will not be necessary, and more strings than just single-character ones will be able to be created. ## 6.0.4 This is a production release that most users will not need to upgrade to. This fixes a build bug for `bcl` only on OpenBSD. Users that do not need `bcl` or have not run into build errors with `bcl` do ***NOT*** need to upgrade. ## 6.0.3 This is a production release that fixes a build bug for cross-compilation. Users that do not need cross-compilation do ***NOT*** need to upgrade. ## 6.0.2 This is a production release that fixes two bugs: * The `-l` option overrode the `-S` option. * A double-free and crash when sending a `SIGINT` while executing expressions given on the command-line. ## 6.0.1 This is a production release that fixes memory bugs and memory leaks in `bcl`. Users that do not use `bcl` (use only `bc` and/or `dc`) do ***NOT*** need to upgrade. These happened because I was unaware that the `bcl` test was not hooked into the Valgrind test infrastructure. Then, when I ran the release script, which tests everything under Valgrind (or so I thought), it caught nothing, and I thought it was safe. But it was not. Nevertheless, I have now run it under Valgrind and fixed all of the memory bugs (caused by not using `memset()` where I should have but previously didn't have to) and memory leaks. ## 6.0.0 This is a production release that fixes an oversight in the `bc` parser (that sometimes caused the wrong error message) and adds a feature for compatibility with the BSD `bc` and `dc`: turning off digit clamping when parsing numbers. The default for clamping can be set during the build (see the [build manual][13]), it can be set with the `BC_DIGIT_CLAMP` and `DC_DIGIT_CLAMP` environment variables, and it can be set with the `-c` and `-C` command-line options. Turning off clamping was also added to the `bcl` library. In addition, signal handling was removed from the `bcl` library in order to add the capability for multi-threading. This required a major version bump. I apologize to all library users (I don't know of any), but signals and threads do not play well together. To help with building, a convenience option (`-p`) to `configure.sh` was added to build a `bc` and `dc` that is by default compatible with either the BSD `bc` and `dc` or the GNU `bc` and `dc`. ## 5.3.3 This is a production release that fixes a build problem in the FreeBSD base system. All other users do **NOT** need to upgrade. ## 5.3.2 This is a production release that fixes prompt bugs with editline and readline where the `BC_PROMPT` environment variable was not being respected. This also fixes editline and readline output on `EOF`. ## 5.3.1 This is a production release that fixes a build problem in the FreeBSD base system, as well as a problem in the `en_US` locale. If you don't have problems with either, you do not need to upgrade. ## 5.3.0 This is a production release that adds features and has a few bug fixes. First, support for editline and readline history has been added. To use editline, pass `-e` to `configure.sh`, and to use readline, pass `-r`. Second, history support for Windows has been fixed and re-enabled. Third, command-line options to set `scale`, `ibase`, `obase`, and `seed` were added. This was requested long ago, and I originally disagreed with the idea. Fourth, the manuals had typos and were missing information. That has been fixed. Fifth, the manuals received different formatting to be more readable as manpages. ## 5.2.5 This is a production release that fixes this `bc`'s behavior on `^D` to match GNU `bc`. ## 5.2.4 This is a production release that fixes two bugs in history: * Without prompt, the cursor could not be placed on the first character in a line. * Home and End key handling in `tmux` was fixed. Any users that do not care about these improvements do not need to upgrade. ## 5.2.3 This is a production release that fixes one bug, a parse error when passing a file to `bc` using `-f` if that file had a multiline comment or string in it. ## 5.2.2 This is a production release that fixes one bug, a segmentation fault if `argv[0]` equals `NULL`. This is not a critical bug; there will be no vulnerability as far as I can tell. There is no need to update if you do not wish to. ## 5.2.1 This is a production release that fixes two parse bugs when in POSIX standard mode. One of these bugs was due to a quirk of the POSIX grammar, and the other was because `bc` was too strict. ## 5.2.0 This is a production release that adds a new feature, fixes some bugs, and adds out-of-source builds and a `pkg-config` file for `bcl`. The new feature is the ability to turn off exiting on expressions. It is also possible to set the default using `configure.sh`. This behavior used to exist with the `BC_EXPR_EXIT` environment variable, which is now used again. Bugs fixed include: * Some possible race conditions with error handling. * Install and uninstall targets for `bcl` did not work. ## 5.1.1 This is a production release that completes a bug fix from `5.1.0`. The bug exists in all versions of `bc`. The bug was that `if` statements without `else` statements would not be handled correctly at the end of files or right before a function definition. ## 5.1.0 This is a production release with some fixes and new features. * Fixed a bug where an `if` statement without an `else` before defining a function caused an error. * Fixed a bug with the `bc` banner and `-q`. * Fixed a bug on Windows where files were not read correctly. * Added a command-line flag (`-z`) to make `bc` and `dc` print leading zeroes on numbers `-1 < x < 1`. * Added four functions to `lib2.bc` (`plz()`, `plznl()`, `pnlz()`, and `pnlznl()`) to allow printing numbers with or without leading zeros, despite the use of `-z` or not. * Added builtin functions to query global state like line length, global stacks, and leading zeroes. * Added a command-line flag (`-L`) to disable wrapping when printing numbers. * Improved builds on Windows. ## 5.0.2 This is a production release with one fix for a flaky test. If you have not experienced problems with the test suite, you do ***NOT*** need to upgrade. The test was one that tested whether `bc` fails gracefully when it can't allocate memory. Unfortunately, there are cases when Linux and FreeBSD lie and pretend to allocate the memory. The reason they do this is because a lot of programs don't use all of the memory they allocate, so those OS's usually get away with it. However, this `bc` uses all of the memory it allocates (at least at page granularity), so when it tries to use the memory, FreeBSD and Linux kill it. This only happens sometimes, however. Other times (on my machine), they do, in fact, refuse the request. So I changed the test to not test for that because I think the graceful failure code won't really change much. ## 5.0.1 This is a production release with two fixes: * Fix for the build on Mac OSX. * Fix for the build on Android. Users that do not use those platforms do ***NOT*** need to update. ## 5.0.0 This is a major production release with several changes: * Added support for OpenBSD's `pledge()` and `unveil()`. * Fixed print bug where a backslash newline combo was printed even if only one digit was left, something I blindly copied from GNU `bc`, like a fool. * Fixed bugs in the manuals. * Fixed a possible multiplication overflow in power. * Temporary numbers are garbage collected if allocation fails, and the allocation is retried. This is to make `bc` and `dc` more resilient to running out of memory. * Limited the number of temporary numbers and made the space for them static so that allocating more space for them cannot fail. * Allowed integers with non-zero `scale` to be used with power, places, and shift operators. * Added greatest common divisor and least common multiple to `lib2.bc`. * Added `SIGQUIT` handling to history. * Added a command to `dc` (`y`) to get the length of register stacks. * Fixed multi-digit bugs in `lib2.bc`. * Removed the no prompt build option. * Created settings that builders can set defaults for and users can set their preferences for. This includes the `bc` banner, resetting on `SIGINT`, TTY mode, and prompt. * Added history support to Windows. * Fixed bugs with the handling of register names in `dc`. * Fixed bugs with multi-line comments and strings in both calculators. * Added a new error type and message for `dc` when register stacks don't have enough items. * Optimized string allocation. * Made `bc` and `dc` UTF-8 capable. * Fixed a bug with `void` functions. * Fixed a misspelled symbol in `bcl`. This is technically a breaking change, which requires this to be `5.0.0`. * Added the ability for users to get the copyright banner back. * Added the ability for users to have `bc` and `dc` quit on `SIGINT`. * Added the ability for users to disable prompt and TTY mode by environment variables. * Added the ability for users to redefine keywords. This is another reason this is `5.0.0`. * Added `dc`'s modular exponentiation and divmod to `bc`. * Added the ability to assign strings to variables and array elements and pass them to functions in `bc`. * Added `dc`'s asciify command and stream printing to `bc`. * Added a command to `dc` (`Y`) to get the length of an array. * Added a command to `dc` (`,`) to get the depth of the execution stack. * Added bitwise and, or, xor, left shift, right shift, reverse, left rotate, right rotate, and mod functions to `lib2.bc`. * Added the functions `s2u(x)` and `s2un(x,n)`, to `lib2.bc`. ## 4.0.2 This is a production release that fixes two bugs: 1. If no files are used and the first statement on `stdin` is invalid, `scale` would not be set to `20` even if `-l` was used. 2. When using history, `bc` failed to respond properly to `SIGSTOP` and `SIGTSTP`. ## 4.0.1 This is a production release that only adds one thing: flushing output when it is printed with a print statement. ## 4.0.0 This is a production release with many fixes, a new command-line option, and a big surprise: * A bug was fixed in `dc`'s `P` command where the item on the stack was *not* popped. * Various bugs in the manuals have been fixed. * A known bug was fixed where history did not interact well with prompts printed by user code without newlines. * A new command-line option, `-R` and `--no-read-prompt` was added to disable just the prompt when using `read()` (`bc`) or `?` (`dc`). * And finally, **official support for Windows was added**. The last item is why this is a major version bump. Currently, only one set of build options (extra math and prompt enabled, history and NLS/locale support disabled, both calculators enabled) is supported on Windows. However, both debug and release builds are supported. In addition, Windows builds are supported for the the library (`bcl`). For more details about how to build on Windows, see the [README][5] or the [build manual][13]. ## 3.3.4 This is a production release that fixes a small bug. The bug was that output was not flushed before a `read()` call, so prompts without a newline on the end were not flushed before the `read()` call. This is such a tiny bug that users only need to upgrade if they are affected. ## 3.3.3 This is a production release with one tweak and fixes for manuals. The tweak is that `length(0)` returns `1` instead of `0`. In `3.3.1`, I changed it so `length(0.x)`, where `x` could be any number of digits, returned the `scale`, but `length(0)` still returned `0` because I believe that `0` has `0` significant digits. After request of FreeBSD and considering the arguments of a mathematician, compatibility with other `bc`'s, and the expectations of users, I decided to make the change. The fixes for manuals fixed a bug where `--` was rendered as `-`. ## 3.3.2 This is a production release that fixes a divide-by-zero bug in `root()` in the [extended math library][16]. All previous versions with `root()` have the bug. ## 3.3.1 This is a production release that fixes a bug. The bug was in the reporting of number length when the value was 0. ## 3.3.0 This is a production release that changes one behavior and fixes documentation bugs. The changed behavior is the treatment of `-e` and `-f` when given through `BC_ENV_ARGS` or `DC_ENV_ARGS`. Now `bc` and `dc` do not exit when those options (or their equivalents) are given through those environment variables. However, `bc` and `dc` still exit when they or their equivalents are given on the command-line. ## 3.2.7 This is a production release that removes a small non-portable shell operation in `configure.sh`. This problem was only noticed on OpenBSD, not FreeBSD or Linux. Non-OpenBSD users do ***NOT*** need to upgrade, although NetBSD users may also need to upgrade. ## 3.2.6 This is a production release that fixes the build on FreeBSD. There was a syntax error in `configure.sh` that the Linux shell did not catch, and FreeBSD depends on the existence of `tests/all.sh`. All users that already upgraded to `3.2.5` should update to this release, with my apologies for the poor release of `3.2.5`. Other users should skip `3.2.5` in favor of this version. ## 3.2.5 This is a production release that fixes several bugs and adds a couple small things. The two most important bugs were bugs that causes `dc` to access memory out-of-bounds (crash in debug builds). This was found by upgrading to `afl++` from `afl`. Both were caused by a failure to distinguish between the same two cases. Another bug was the failure to put all of the licenses in the `LICENSE.md` file. Third, some warnings by `scan-build` were found and eliminated. This needed one big change: `bc` and `dc` now bail out as fast as possible on fatal errors instead of unwinding the stack. Fourth, the pseudo-random number now attempts to seed itself with `/dev/random` if `/dev/urandom` fails. Finally, this release has a few quality-of-life changes to the build system. The usage should not change at all; the only thing that changed was making sure the `Makefile.in` was written to rebuild properly when headers changed and to not rebuild when not necessary. ## 3.2.4 This is a production release that fixes a warning on `gcc` 6 or older, which does not have an attribute that is used. Users do ***NOT*** need to upgrade if they don't use `gcc` 6 or older. ## 3.2.3 This is a production release that fixes a bug in `gen/strgen.sh`. I recently changed `gen/strgen.c`, but I did not change `gen/strgen.sh`. Users that do not use `gen/strgen.sh` do not need to upgrade. ## 3.2.2 This is a production release that fixes a portability bug in `configure.sh`. The bug was using the GNU `find` extension `-wholename`. ## 3.2.1 This is a production release that has one fix for `bcl(3)`. It is technically not a bug fix since the behavior is undefined, but the `BclNumber`s that `bcl_divmod()` returns will be set to `BCL_ERROR_INVALID_NUM` if there is an error. Previously, they were not set. ## 3.2.0 This is a production release that has one bug fix and a major addition. The bug fix was a missing `auto` variable in the bessel `j()` function in the math library. The major addition is a way to build a version of `bc`'s math code as a library. This is done with the `-a` option to `configure.sh`. The API for the library can be read in `./manuals/bcl.3.md` or `man bcl` once the library is installed with `make install`. This library was requested by developers before I even finished version 1.0, but I could not figure out how to do it until now. If the library has API breaking changes, the major version of `bc` will be incremented. ## 3.1.6 This is a production release that fixes a new warning from Clang 12 for FreeBSD and also removes some possible undefined behavior found by UBSan that compilers did not seem to take advantage of. Users do ***NOT*** need to upgrade, if they do not want to. ## 3.1.5 This is a production release that fixes the Chinese locales (which caused `bc` to crash) and a crash caused by `bc` executing code when it should not have been able to. ***ALL USERS SHOULD UPGRADE.*** ## 3.1.4 This is a production release that fixes one bug, changes two behaviors, and removes one environment variable. The bug is like the one in the last release except it applies if files are being executed. I also made the fix more general. The behavior that was changed is that `bc` now exits when given `-e`, `-f`, `--expression` or `--file`. However, if the last one of those is `-f-` (using `stdin` as the file), `bc` does not exit. If `-f-` exists and is not the last of the `-e` and `-f` options (and equivalents), `bc` gives a fatal error and exits. Next, I removed the `BC_EXPR_EXIT` and `DC_EXPR_EXIT` environment variables since their use is not needed with the behavior change. Finally, I made it so `bc` does not print the header, though the `-q` and `--quiet` options were kept for compatibility with GNU `bc`. ## 3.1.3 This is a production release that fixes one minor bug: if `bc` was invoked like the following, it would error: ``` echo "if (1 < 3) 1" | bc ``` Unless users run into this bug, they do not need to upgrade, but it is suggested that they do. ## 3.1.2 This is a production release that adds a way to install *all* locales. Users do ***NOT*** need to upgrade. For package maintainers wishing to make use of the change, just pass `-l` to `configure.sh`. ## 3.1.1 This is a production release that adds two Spanish locales. Users do ***NOT*** need to upgrade, unless they want those locales. ## 3.1.0 This is a production release that adjusts one behavior, fixes eight bugs, and improves manpages for FreeBSD. Because this release fixes bugs, **users and package maintainers should update to this version as soon as possible**. The behavior that was adjusted was how code from the `-e` and `-f` arguments (and equivalents) were executed. They used to be executed as one big chunk, but in this release, they are now executed line-by-line. The first bug fix in how output to `stdout` was handled in `SIGINT`. If a `SIGINT` came in, the `stdout` buffer was not correctly flushed. In fact, a clean-up function was not getting called. This release fixes that bug. The second bug is in how `dc` handled input from `stdin`. This affected `bc` as well since it was a mishandling of the `stdin` buffer. The third fixed bug was that `bc` and `dc` could `abort()` (in debug mode) when receiving a `SIGTERM`. This one was a race condition with pushing and popping items onto and out of vectors. The fourth bug fixed was that `bc` could leave extra items on the stack and thus, not properly clean up some memory. (The memory would still get `free()`'ed, but it would not be `free()`'ed when it could have been.) The next two bugs were bugs in `bc`'s parser that caused crashes when executing the resulting code. The last two bugs were crashes in `dc` that resulted from mishandling of strings. The manpage improvement was done by switching from [ronn][20] to [Pandoc][21] to generate manpages. Pandoc generates much cleaner manpages and doesn't leave blank lines where they shouldn't be. ## 3.0.3 This is a production release that adds one new feature: specific manpages. Before this release, `bc` and `dc` only used one manpage each that referred to various build options. This release changes it so there is one manpage set per relevant build type. Each manual only has information about its particular build, and `configure.sh` selects the correct set for install. ## 3.0.2 This is a production release that adds `utf8` locale symlinks and removes an unused `auto` variable from the `ceil()` function in the [extended math library][16]. Users do ***NOT*** need to update unless they want the locales. ## 3.0.1 This is a production release with two small changes. Users do ***NOT*** need to upgrade to this release; however, if they haven't upgraded to `3.0.0` yet, it may be worthwhile to upgrade to this release. The first change is fixing a compiler warning on FreeBSD with strict warnings on. The second change is to make the new implementation of `ceil()` in `lib2.bc` much more efficient. ## 3.0.0 *Notes for package maintainers:* *First, the `2.7.0` release series saw a change in the option parsing. This made me change one error message and add a few others. The error message that was changed removed one format specifier. This means that `printf()` will seqfault on old locale files. Unfortunately, `bc` cannot use any locale files except the global ones that are already installed, so it will use the previous ones while running tests during install. **If `bc` segfaults while running arg tests when updating, it is because the global locale files have not been replaced. Make sure to either prevent the test suite from running on update or remove the old locale files before updating.** (Removing the locale files can be done with `make uninstall` or by running the [`locale_uninstall.sh`][22] script.) Once this is done, `bc` should install without problems.* *Second, **the option to build without signal support has been removed**. See below for the reasons why.* This is a production release with some small bug fixes, a few improvements, three major bug fixes, and a complete redesign of `bc`'s error and signal handling. **Users and package maintainers should update to this version as soon as possible.** The first major bug fix was in how `bc` executed files. Previously, a whole file was parsed before it was executed, but if a function is defined *after* code, especially if the function definition was actually a redefinition, and the code before the definition referred to the previous function, this `bc` would replace the function before executing any code. The fix was to make sure that all code that existed before a function definition was executed. The second major bug fix was in `bc`'s `lib2.bc`. The `ceil()` function had a bug where a `0` in the decimal place after the truncation position, caused it to output the wrong numbers if there was any non-zero digit after. The third major bug is that when passing parameters to functions, if an expression included an array (not an array element) as a parameter, it was accepted, when it should have been rejected. It is now correctly rejected. Beyond that, this `bc` got several improvements that both sped it up, improved the handling of signals, and improved the error handling. First, the requirements for `bc` were pushed back to POSIX 2008. `bc` uses one function, `strdup()`, which is not in POSIX 2001, and it is in the X/Open System Interfaces group 2001. It is, however, in POSIX 2008, and since POSIX 2008 is old enough to be supported anywhere that I care, that should be the requirement. Second, the BcVm global variable was put into `bss`. This actually slightly reduces the size of the executable from a massive code shrink, and it will stop `bc` from allocating a large set of memory when `bc` starts. Third, the default Karatsuba length was updated from 64 to 32 after making the optimization changes below, since 32 is going to be better than 64 after the changes. Fourth, Spanish translations were added. Fifth, the interpreter received a speedup to make performance on non-math-heavy scripts more competitive with GNU `bc`. While improvements did, in fact, get it much closer (see the [benchmarks][19]), it isn't quite there. There were several things done to speed up the interpreter: First, several small inefficiencies were removed. These inefficiencies included calling the function `bc_vec_pop(v)` twice instead of calling `bc_vec_npop(v, 2)`. They also included an extra function call for checking the size of the stack and checking the size of the stack more than once on several operations. Second, since the current `bc` function is the one that stores constants and strings, the program caches pointers to the current function's vectors of constants and strings to prevent needing to grab the current function in order to grab a constant or a string. Third, `bc` tries to reuse `BcNum`'s (the internal representation of arbitary-precision numbers). If a `BcNum` has the default capacity of `BC_NUM_DEF_SIZE` (32 on 64-bit and 16 on 32-bit) when it is freed, it is added to a list of available `BcNum`'s. And then, when a `BcNum` is allocated with a capacity of `BC_NUM_DEF_SIZE` and any `BcNum`'s exist on the list of reusable ones, one of those ones is grabbed instead. In order to support these changes, the `BC_NUM_DEF_SIZE` was changed. It used to be 16 bytes on all systems, but it was changed to more closely align with the minimum allocation size on Linux, which is either 32 bytes (64-bit musl), 24 bytes (64-bit glibc), 16 bytes (32-bit musl), or 12 bytes (32-bit glibc). Since these are the minimum allocation sizes, these are the sizes that would be allocated anyway, making it worth it to just use the whole space, so the value of `BC_NUM_DEF_SIZE` on 64-bit systems was changed to 32 bytes. On top of that, at least on 64-bit, `BC_NUM_DEF_SIZE` supports numbers with either 72 integer digits or 45 integer digits and 27 fractional digits. This should be more than enough for most cases since `bc`'s default `scale` values are 0 or 20, meaning that, by default, it has at most 20 fractional digits. And 45 integer digits are *a lot*; it's enough to calculate the amount of mass in the Milky Way galaxy in kilograms. Also, 72 digits is enough to calculate the diameter of the universe in Planck lengths. (For 32-bit, these numbers are either 32 integer digits or 12 integer digits and 20 fractional digits. These are also quite big, and going much bigger on a 32-bit system seems a little pointless since 12 digits is just under a trillion and 20 fractional digits is still enough for about any use since `10^-20` light years is just under a millimeter.) All of this together means that for ordinary uses, and even uses in scientific work, the default number size will be all that is needed, which means that nearly all, if not all, numbers will be reused, relieving pressure on the system allocator. I did several experiments to find the changes that had the most impact, especially with regard to reusing `BcNum`'s. One was putting `BcNum`'s into buckets according to their capacity in powers of 2 up to 512. That performed worse than `bc` did in `2.7.2`. Another was putting any `BcNum` on the reuse list that had a capacity of `BC_NUM_DEF_SIZE * 2` and reusing them for `BcNum`'s that requested `BC_NUM_DEF_SIZE`. This did reduce the amount of time spent, but it also spent a lot of time in the system allocator for an unknown reason. (When using `strace`, a bunch more `brk` calls showed up.) Just reusing `BcNum`'s that had exactly `BC_NUM_DEF_SIZE` capacity spent the smallest amount of time in both user and system time. This makes sense, especially with the changes to make `BC_NUM_DEF_SIZE` bigger on 64-bit systems, since the vast majority of numbers will only ever use numbers with a size less than or equal to `BC_NUM_DEF_SIZE`. Last of all, `bc`'s signal handling underwent a complete redesign. (This is the reason that this version is `3.0.0` and not `2.8.0`.) The change was to move from a polling approach to signal handling to an interrupt-based approach. Previously, every single loop condition had a check for signals. I suspect that this could be expensive when in tight loops. Now, the signal handler just uses `longjmp()` (actually `siglongjmp()`) to start an unwinding of the stack until it is stopped or the stack is unwound to `main()`, which just returns. If `bc` is currently executing code that cannot be safely interrupted (according to POSIX), then signals are "locked." The signal handler checks if the lock is taken, and if it is, it just sets the status to indicate that a signal arrived. Later, when the signal lock is released, the status is checked to see if a signal came in. If so, the stack unwinding starts. This design eliminates polling in favor of maintaining a stack of `jmp_buf`'s. This has its own performance implications, but it gives better interaction. And the cost of pushing and popping a `jmp_buf` in a function is paid at most twice. Most functions do not pay that price, and most of the rest only pay it once. (There are only some 3 functions in `bc` that push and pop a `jmp_buf` twice.) As a side effect of this change, I had to eliminate the use of `stdio.h` in `bc` because `stdio` does not play nice with signals and `longjmp()`. I implemented custom I/O buffer code that takes a fraction of the size. This means that static builds will be smaller, but non-static builds will be bigger, though they will have less linking time. This change is also good because my history implementation was already bypassing `stdio` for good reasons, and unifying the architecture was a win. Another reason for this change is that my `bc` should *always* behave correctly in the presence of signals like `SIGINT`, `SIGTERM`, and `SIGQUIT`. With the addition of my own I/O buffering, I needed to also make sure that the buffers were correctly flushed even when such signals happened. For this reason, I **removed the option to build without signal support**. As a nice side effect of this change, the error handling code could be changed to take advantage of the stack unwinding that signals used. This means that signals and error handling use the same code paths, which means that the stack unwinding is well-tested. (Errors are tested heavily in the test suite.) It also means that functions do not need to return a status code that ***every*** caller needs to check. This eliminated over 100 branches that simply checked return codes and then passed that return code up the stack if necessary. The code bloat savings from this is at least 1700 bytes on `x86_64`, *before* taking into account the extra code from removing `stdio.h`. ## 2.7.2 This is a production release with one major bug fix. The `length()` built-in function can take either a number or an array. If it takes an array, it returns the length of the array. Arrays can be passed by reference. The bug is that the `length()` function would not properly dereference arrays that were references. This is a bug that affects all users. **ALL USERS SHOULD UPDATE `bc`**. ## 2.7.1 This is a production release with fixes for new locales and fixes for compiler warnings on FreeBSD. ## 2.7.0 This is a production release with a bug fix for Linux, new translations, and new features. Bug fixes: * Option parsing in `BC_ENV_ARGS` was broken on Linux in 2.6.1 because `glibc`'s `getopt_long()` is broken. To get around that, and to support long options on every platform, an adapted version of [`optparse`][17] was added. Now, `bc` does not even use `getopt()`. * Parsing `BC_ENV_ARGS` with quotes now works. It isn't the smartest, but it does the job if there are spaces in file names. The following new languages are supported: * Dutch * Polish * Russian * Japanes * Simplified Chinese All of these translations were generated using [DeepL][18], so improvements are welcome. There is only one new feature: **`bc` now has a built-in pseudo-random number generator** (PRNG). The PRNG is seeded, making it useful for applications where `/dev/urandom` does not work because output needs to be reproducible. However, it also uses `/dev/urandom` to seed itself by default, so it will start with a good seed by default. It also outputs 32 bits on 32-bit platforms and 64 bits on 64-bit platforms, far better than the 15 bits of C's `rand()` and `bash`'s `$RANDOM`. In addition, the PRNG can take a bound, and when it gets a bound, it automatically adjusts to remove bias. It can also generate numbers of arbitrary size. (As of the time of release, the largest pseudo-random number generated by this `bc` was generated with a bound of `2^(2^20)`.) ***IMPORTANT: read the [`bc` manual][9] and the [`dc` manual][10] to find out exactly what guarantees the PRNG provides. The underlying implementation is not guaranteed to stay the same, but the guarantees that it provides are guaranteed to stay the same regardless of the implementation.*** On top of that, four functions were added to `bc`'s [extended math library][16] to make using the PRNG easier: * `frand(p)`: Generates a number between `[0,1)` to `p` decimal places. * `ifrand(i, p)`: Generates an integer with bound `i` and adds it to `frand(p)`. * `srand(x)`: Randomizes the sign of `x`. In other words, it flips the sign of `x` with probability `0.5`. * `brand()`: Returns a random boolean value (either `0` or `1`). ## 2.6.1 This is a production release with a bug fix for FreeBSD. The bug was that when `bc` was built without long options, it would give a fatal error on every run. This was caused by a mishandling of `optind`. ## 2.6.0 This release is a production release ***with no bugfixes***. If you do not want to upgrade, you don't have to. No source code changed; the only thing that changed was `lib2.bc`. This release adds one function to the [extended math library][16]: `p(x, y)`, which calculates `x` to the power of `y`, whether or not `y` is an integer. (The `^` operator can only accept integer powers.) This release also includes a couple of small tweaks to the [extended math library][16], mostly to fix returning numbers with too high of `scale`. ## 2.5.3 This release is a production release which addresses inconsistencies in the Portuguese locales. No `bc` code was changed. The issues were that the ISO files used different naming, and also that the files that should have been symlinks were not. I did not catch that because GitHub rendered them the exact same way. ## 2.5.2 This release is a production release. No code was changed, but the build system was changed to allow `CFLAGS` to be given to `CC`, like this: ``` CC="gcc -O3 -march=native" ./configure.sh ``` If this happens, the flags are automatically put into `CFLAGS`, and the compiler is set appropriately. In the example above this means that `CC` will be "gcc" and `CFLAGS` will be "-O3 -march=native". This behavior was added to conform to GNU autotools practices. ## 2.5.1 This is a production release which addresses portability concerns discovered in the `bc` build system. No `bc` code was changed. * Support for Solaris SPARC and AIX were added. * Minor documentations edits were performed. * An option for `configure.sh` was added to disable long options if `getopt_long()` is missing. ## 2.5.0 This is a production release with new translations. No code changed. The translations were contributed by [bugcrazy][15], and they are for Portuguese, both Portugal and Brazil locales. ## 2.4.0 This is a production release primarily aimed at improving `dc`. * A couple of copy and paste errors in the [`dc` manual][10] were fixed. * `dc` startup was optimized by making sure it didn't have to set up `bc`-only things. * The `bc` `&&` and `||` operators were made available to `dc` through the `M` and `m` commands, respectively. * `dc` macros were changed to be tail call-optimized. The last item, tail call optimization, means that if the last thing in a macro is a call to another macro, then the old macro is popped before executing the new macro. This change was made to stop `dc` from consuming more and more memory as macros are executed in a loop. The `q` and `Q` commands still respect the "hidden" macros by way of recording how many macros were removed by tail call optimization. ## 2.3.2 This is a production release meant to fix warnings in the Gentoo `ebuild` by making it possible to disable binary stripping. Other users do *not* need to upgrade. ## 2.3.1 This is a production release. It fixes a bug that caused `-1000000000 < -1` to return `0`. This only happened with negative numbers and only if the value on the left was more negative by a certain amount. That said, this bug *is* a bad bug, and needs to be fixed. **ALL USERS SHOULD UPDATE `bc`**. ## 2.3.0 This is a production release with changes to the build system. ## 2.2.0 This release is a production release. It only has new features and performance improvements. 1. The performance of `sqrt(x)` was improved. 2. The new function `root(x, n)` was added to the extended math library to calculate `n`th roots. 3. The new function `cbrt(x)` was added to the extended math library to calculate cube roots. ## 2.1.3 This is a non-critical release; it just changes the build system, and in non-breaking ways: 1. Linked locale files were changed to link to their sources with a relative link. 2. A bug in `configure.sh` that caused long option parsing to fail under `bash` was fixed. ## 2.1.2 This release is not a critical release. 1. A few codes were added to history. 2. Multiplication was optimized a bit more. 3. Addition and subtraction were both optimized a bit more. ## 2.1.1 This release contains a fix for the test suite made for Linux from Scratch: now the test suite prints `pass` when a test is passed. Other than that, there is no change in this release, so distros and other users do not need to upgrade. ## 2.1.0 This release is a production release. The following bugs were fixed: 1. A `dc` bug that caused stack mishandling was fixed. 2. A warning on OpenBSD was fixed. 3. Bugs in `ctrl+arrow` operations in history were fixed. 4. The ability to paste multiple lines in history was added. 5. A `bc` bug, mishandling of array arguments to functions, was fixed. 6. A crash caused by freeing the wrong pointer was fixed. 7. A `dc` bug where strings, in a rare case, were mishandled in parsing was fixed. In addition, the following changes were made: 1. Division was slightly optimized. 2. An option was added to the build to disable printing of prompts. 3. The special case of empty arguments is now handled. This is to prevent errors in scripts that end up passing empty arguments. 4. A harmless bug was fixed. This bug was that, with the pop instructions (mostly) removed (see below), `bc` would leave extra values on its stack for `void` functions and in a few other cases. These extra items would not affect anything put on the stack and would not cause any sort of crash or even buggy behavior, but they would cause `bc` to take more memory than it needed. On top of the above changes, the following optimizations were added: 1. The need for pop instructions in `bc` was removed. 2. Extra tests on every iteration of the interpreter loop were removed. 3. Updating function and code pointers on every iteration of the interpreter loop was changed to only updating them when necessary. 4. Extra assignments to pointers were removed. Altogether, these changes sped up the interpreter by around 2x. ***NOTE***: This is the last release with new features because this `bc` is now considered complete. From now on, only bug fixes and new translations will be added to this `bc`. ## 2.0.3 This is a production, bug-fix release. Two bugs were fixed in this release: 1. A rare and subtle signal handling bug was fixed. 2. A misbehavior on `0` to a negative power was fixed. The last bug bears some mentioning. When I originally wrote power, I did not thoroughly check its error cases; instead, I had it check if the first number was `0` and then if so, just return `0`. However, `0` to a negative power means that `1` will be divided by `0`, which is an error. I caught this, but only after I stopped being cocky. You see, sometime later, I had noticed that GNU `bc` returned an error, correctly, but I thought it was wrong simply because that's not what my `bc` did. I saw it again later and had a double take. I checked for real, finally, and found out that my `bc` was wrong all along. That was bad on me. But the bug was easy to fix, so it is fixed now. There are two other things in this release: 1. Subtraction was optimized by [Stefan Eßer][14]. 2. Division was also optimized, also by Stefan Eßer. ## 2.0.2 This release contains a fix for a possible overflow in the signal handling. I would be surprised if any users ran into it because it would only happen after 2 billion (`2^31-1`) `SIGINT`'s, but I saw it and had to fix it. ## 2.0.1 This release contains very few things that will apply to any users. 1. A slight bug in `dc`'s interactive mode was fixed. 2. A bug in the test suite that was only triggered on NetBSD was fixed. 3. **The `-P`/`--no-prompt` option** was added for users that do not want a prompt. 4. A `make check` target was added as an alias for `make test`. 5. `dc` got its own read prompt: `?> `. ## 2.0.0 This release is a production release. This release is also a little different from previous releases. From here on out, I do not plan on adding any more features to this `bc`; I believe that it is complete. However, there may be bug fix releases in the future, if I or any others manage to find bugs. This release has only a few new features: 1. `atan2(y, x)` was added to the extended math library as both `a2(y, x)` and `atan2(y, x)`. 2. Locales were fixed. 3. A **POSIX shell-compatible script was added as an alternative to compiling `gen/strgen.c`** on a host machine. More details about making the choice between the two can be found by running `./configure.sh --help` or reading the [build manual][13]. 4. Multiplication was optimized by using **diagonal multiplication**, rather than straight brute force. 5. The `locale_install.sh` script was fixed. 6. `dc` was given the ability to **use the environment variable `DC_ENV_ARGS`**. 7. `dc` was also given the ability to **use the `-i` or `--interactive`** options. 8. Printing the prompt was fixed so that it did not print when it shouldn't. 9. Signal handling was fixed. 10. **Handling of `SIGTERM` and `SIGQUIT`** was fixed. 11. The **built-in functions `maxibase()`, `maxobase()`, and `maxscale()`** (the commands `T`, `U`, `V` in `dc`, respectively) were added to allow scripts to query for the max allowable values of those globals. 12. Some incompatibilities with POSIX were fixed. In addition, this release is `2.0.0` for a big reason: the internal format for numbers changed. They used to be a `char` array. Now, they are an array of larger integers, packing more decimal digits into each integer. This has delivered ***HUGE*** performance improvements, especially for multiplication, division, and power. This `bc` should now be the fastest `bc` available, but I may be wrong. ## 1.2.8 This release contains a fix for a harmless bug (it is harmless in that it still works, but it just copies extra data) in the [`locale_install.sh`][12] script. ## 1.2.7 This version contains fixes for the build on Arch Linux. ## 1.2.6 This release removes the use of `local` in shell scripts because it's not POSIX shell-compatible, and also updates a man page that should have been updated a long time ago but was missed. ## 1.2.5 This release contains some missing locale `*.msg` files. ## 1.2.4 This release contains a few bug fixes and new French translations. ## 1.2.3 This release contains a fix for a bug: use of uninitialized data. Such data was only used when outputting an error message, but I am striving for perfection. As Michelangelo said, "Trifles make perfection, and perfection is no trifle." ## 1.2.2 This release contains fixes for OpenBSD. ## 1.2.1 This release contains bug fixes for some rare bugs. ## 1.2.0 This is a production release. There have been several changes since `1.1.0`: 1. The build system had some changes. 2. Locale support has been added. (Patches welcome for translations.) 3. **The ability to turn `ibase`, `obase`, and `scale` into stacks** was added with the `-g` command-line option. (See the [`bc` manual][9] for more details.) 4. Support for compiling on Mac OSX out of the box was added. 5. The extended math library got `t(x)`, `ceil(x)`, and some aliases. 6. The extended math library also got `r2d(x)` (for converting from radians to degrees) and `d2r(x)` (for converting from degrees to radians). This is to allow using degrees with the standard library. 7. Both calculators now accept numbers in **scientific notation**. See the [`bc` manual][9] and the [`dc` manual][10] for details. 8. Both calculators can **output in either scientific or engineering notation**. See the [`bc` manual][9] and the [`dc` manual][10] for details. 9. Some inefficiencies were removed. 10. Some bugs were fixed. 11. Some bugs in the extended library were fixed. 12. Some defects from [Coverity Scan][11] were fixed. ## 1.1.4 This release contains a fix to the build system that allows it to build on older versions of `glibc`. ## 1.1.3 This release contains a fix for a bug in the test suite where `bc` tests and `dc` tests could not be run in parallel. ## 1.1.2 This release has a fix for a history bug; the down arrow did not work. ## 1.1.1 This release fixes a bug in the `1.1.0` build system. The source is exactly the same. The bug that was fixed was a failure to install if no `EXECSUFFIX` was used. ## 1.1.0 This is a production release. However, many new features were added since `1.0`. 1. **The build system has been changed** to use a custom, POSIX shell-compatible configure script ([`configure.sh`][6]) to generate a POSIX make-compatible `Makefile`, which means that `bc` and `dc` now build out of the box on any POSIX-compatible system. 2. Out-of-memory and output errors now cause the `bc` to report the error, clean up, and die, rather than just reporting and trying to continue. 3. **Strings and constants are now garbage collected** when possible. 4. Signal handling and checking has been made more simple and more thorough. 5. `BcGlobals` was refactored into `BcVm` and `BcVm` was made global. Some procedure names were changed to reflect its difference to everything else. 6. Addition got a speed improvement. 7. Some common code for addition and multiplication was refactored into its own procedure. 8. A bug was removed where `dc` could have been selected, but the internal `#define` that returned `true` for a query about `dc` would not have returned `true`. 9. Useless calls to `bc_num_zero()` were removed. 10. **History support was added.** The history support is based off of a [UTF-8 aware fork][7] of [`linenoise`][8], which has been customized with `bc`'s own data structures and signal handling. 11. Generating C source from the math library now removes tabs from the library, shrinking the size of the executable. 12. The math library was shrunk. 13. Error handling and reporting was improved. 14. Reallocations were reduced by giving access to the request size for each operation. 15. **`abs()` (`b` command for `dc`) was added as a builtin.** 16. Both calculators were tested on FreeBSD. 17. Many obscure parse bugs were fixed. 18. Markdown and man page manuals were added, and the man pages are installed by `make install`. 19. Executable size was reduced, though the added features probably made the executable end up bigger. 20. **GNU-style array references were added as a supported feature.** 21. Allocations were reduced. 22. **New operators were added**: `$` (`$` for `dc`), `@` (`@` for `dc`), `@=`, `<<` (`H` for `dc`), `<<=`, `>>` (`h` for `dc`), and `>>=`. See the [`bc` manual][9] and the [`dc` manual][10] for more details. 23. **An extended math library was added.** This library contains code that makes it so I can replace my desktop calculator with this `bc`. See the [`bc` manual][3] for more details. 24. Support for all capital letters as numbers was added. 25. **Support for GNU-style void functions was added.** 26. A bug fix for improper handling of function parameters was added. 27. Precedence for the or (`||`) operator was changed to match GNU `bc`. 28. `dc` was given an explicit negation command. 29. `dc` was changed to be able to handle strings in arrays. ## 1.1 Release Candidate 3 This release is the eighth release candidate for 1.1, though it is the third release candidate meant as a general release candidate. The new code has not been tested as thoroughly as it should for release. ## 1.1 Release Candidate 2 This release is the seventh release candidate for 1.1, though it is the second release candidate meant as a general release candidate. The new code has not been tested as thoroughly as it should for release. ## 1.1 FreeBSD Beta 5 This release is the sixth release candidate for 1.1, though it is the fifth release candidate meant specifically to test if `bc` works on FreeBSD. The new code has not been tested as thoroughly as it should for release. ## 1.1 FreeBSD Beta 4 This release is the fifth release candidate for 1.1, though it is the fourth release candidate meant specifically to test if `bc` works on FreeBSD. The new code has not been tested as thoroughly as it should for release. ## 1.1 FreeBSD Beta 3 This release is the fourth release candidate for 1.1, though it is the third release candidate meant specifically to test if `bc` works on FreeBSD. The new code has not been tested as thoroughly as it should for release. ## 1.1 FreeBSD Beta 2 This release is the third release candidate for 1.1, though it is the second release candidate meant specifically to test if `bc` works on FreeBSD. The new code has not been tested as thoroughly as it should for release. ## 1.1 FreeBSD Beta 1 This release is the second release candidate for 1.1, though it is meant specifically to test if `bc` works on FreeBSD. The new code has not been tested as thoroughly as it should for release. ## 1.1 Release Candidate 1 This is the first release candidate for 1.1. The new code has not been tested as thoroughly as it should for release. ## 1.0 This is the first non-beta release. `bc` is ready for production use. As such, a lot has changed since 0.5. 1. `dc` has been added. It has been tested even more thoroughly than `bc` was for `0.5`. It does not have the `!` command, and for security reasons, it never will, so it is complete. 2. `bc` has been more thoroughly tested. An entire section of the test suite (for both programs) has been added to test for errors. 3. A prompt (`>>> `) has been added for interactive mode, making it easier to see inputs and outputs. 4. Interrupt handling has been improved, including elimination of race conditions (as much as possible). 5. MinGW and [Windows Subsystem for Linux][1] support has been added (see [xstatic][2] for binaries). 6. Memory leaks and errors have been eliminated (as far as ASan and Valgrind can tell). 7. Crashes have been eliminated (as far as [afl][3] can tell). 8. Karatsuba multiplication was added (and thoroughly) tested, speeding up multiplication and power by orders of magnitude. 9. Performance was further enhanced by using a "divmod" function to reduce redundant divisions and by removing superfluous `memset()` calls. 10. To switch between Karatsuba and `O(n^2)` multiplication, the config variable `BC_NUM_KARATSUBA_LEN` was added. It is set to a sane default, but the optimal number can be found with [`karatsuba.py`][4] (requires Python 3) and then configured through `make`. 11. The random math test generator script was changed to Python 3 and improved. `bc` and `dc` have together been run through 30+ million random tests. 12. All known math bugs have been fixed, including out of control memory allocations in `sine` and `cosine` (that was actually a parse bug), certain cases of infinite loop on square root, and slight inaccuracies (as much as possible; see the [README][5]) in transcendental functions. 13. Parsing has been fixed as much as possible. 14. Test coverage was improved to 94.8%. The only paths not covered are ones that happen when `malloc()` or `realloc()` fails. 15. An extension to get the length of an array was added. 16. The boolean not (`!`) had its precedence change to match negation. 17. Data input was hardened. 18. `bc` was made fully compliant with POSIX when the `-s` flag is used or `POSIXLY_CORRECT` is defined. 19. Error handling was improved. 20. `bc` now checks that files it is given are not directories. ## 1.0 Release Candidate 7 This is the seventh release candidate for 1.0. It fixes a few bugs in 1.0 Release Candidate 6. ## 1.0 Release Candidate 6 This is the sixth release candidate for 1.0. It fixes a few bugs in 1.0 Release Candidate 5. ## 1.0 Release Candidate 5 This is the fifth release candidate for 1.0. It fixes a few bugs in 1.0 Release Candidate 4. ## 1.0 Release Candidate 4 This is the fourth release candidate for 1.0. It fixes a few bugs in 1.0 Release Candidate 3. ## 1.0 Release Candidate 3 This is the third release candidate for 1.0. It fixes a few bugs in 1.0 Release Candidate 2. ## 1.0 Release Candidate 2 This is the second release candidate for 1.0. It fixes a few bugs in 1.0 Release Candidate 1. ## 1.0 Release Candidate 1 This is the first Release Candidate for 1.0. `bc` is complete, with `dc`, but it is not tested. ## 0.5 This beta release completes more features, but it is still not complete nor tested as thoroughly as necessary. ## 0.4.1 This beta release fixes a few bugs in 0.4. ## 0.4 This is a beta release. It does not have the complete set of features, and it is not thoroughly tested. [1]: https://docs.microsoft.com/en-us/windows/wsl/install-win10 [2]: https://pkg.musl.cc/bc/ [3]: http://lcamtuf.coredump.cx/afl/ [4]: ./scripts/karatsuba.py [5]: ./README.md [6]: ./configure.sh [7]: https://github.com/rain-1/linenoise-mob [8]: https://github.com/antirez/linenoise [9]: ./manuals/bc/A.1.md [10]: ./manuals/dc/A.1.md [11]: https://scan.coverity.com/projects/gavinhoward-bc [12]: ./scripts/locale_install.sh [13]: ./manuals/build.md [14]: https://github.com/stesser [15]: https://github.com/bugcrazy [16]: ./manuals/bc/A.1.md#extended-library [17]: https://github.com/skeeto/optparse [18]: https://www.deepl.com/translator [19]: ./manuals/benchmarks.md [20]: https://github.com/apjanke/ronn-ng [21]: https://pandoc.org/ [22]: ./scripts/locale_uninstall.sh diff --git a/contrib/bc/configure.sh b/contrib/bc/configure.sh index 3ada5298e9ed..021d30807ffb 100755 --- a/contrib/bc/configure.sh +++ b/contrib/bc/configure.sh @@ -1,2111 +1,2111 @@ #! /bin/sh # # SPDX-License-Identifier: BSD-2-Clause # # Copyright (c) 2018-2023 Gavin D. Howard and contributors. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # script="$0" scriptdir=$(dirname "$script") script=$(basename "$script") builddir=$(pwd) . "$scriptdir/scripts/functions.sh" # Simply prints the help message and quits based on the argument. # @param msg The help message to print. usage() { if [ $# -gt 0 ]; then _usage_val=1 printf '%s\n\n' "$1" else _usage_val=0 fi printf 'usage:\n' printf ' %s -h\n' "$script" printf ' %s --help\n' "$script" printf ' %s [-a|-bD|-dB|-c] [-CeEfgGHilmMNPrtTvz] [-O OPT_LEVEL] [-k KARATSUBA_LEN]\\\n' "$script" printf ' [-s SETTING] [-S SETTING] [-p TYPE]\n' printf ' %s \\\n' "$script" printf ' [--library|--bc-only --disable-dc|--dc-only --disable-bc|--coverage] \\\n' printf ' [--force --debug --disable-extra-math --disable-generated-tests] \\\n' printf ' [--disable-history --disable-man-pages --disable-nls --disable-strip] \\\n' printf ' [--enable-editline] [--enable-readline] [--enable-internal-history] \\\n' printf ' [--disable-problematic-tests] [--install-all-locales] \\\n' printf ' [--opt=OPT_LEVEL] [--karatsuba-len=KARATSUBA_LEN] \\\n' printf ' [--set-default-on=SETTING] [--set-default-off=SETTING] \\\n' printf ' [--predefined-build-type=TYPE] \\\n' printf ' [--prefix=PREFIX] [--bindir=BINDIR] [--datarootdir=DATAROOTDIR] \\\n' printf ' [--datadir=DATADIR] [--mandir=MANDIR] [--man1dir=MAN1DIR] \\\n' printf ' [--man3dir=MAN3DIR]\n' if [ "$_usage_val" -ne 0 ]; then exit fi printf '\n' printf ' -a, --library\n' printf ' Build the libbcl instead of the programs. This is meant to be used with\n' printf ' Other software like programming languages that want to make use of the\n' printf ' parsing and math capabilities. This option will install headers using\n' printf ' `make install`.\n' printf ' -b, --bc-only\n' printf ' Build bc only. It is an error if "-d", "--dc-only", "-B", or\n' printf ' "--disable-bc" are specified too.\n' printf ' -B, --disable-bc\n' printf ' Disable bc. It is an error if "-b", "--bc-only", "-D", or "--disable-dc"\n' printf ' are specified too.\n' printf ' -c, --coverage\n' printf ' Generate test coverage code. Requires gcov and gcovr.\n' printf ' It is an error if either "-b" ("-D") or "-d" ("-B") is specified.\n' printf ' Requires a compiler that use gcc-compatible coverage options\n' printf ' -C, --disable-clean\n' printf ' Disable the clean that configure.sh does before configure.\n' printf ' -d, --dc-only\n' printf ' Build dc only. It is an error if "-b", "--bc-only", "-D", or\n' printf ' "--disable-dc" are specified too.\n' printf ' -D, --disable-dc\n' printf ' Disable dc. It is an error if "-d", "--dc-only", "-B", or "--disable-bc"\n' printf ' are specified too.\n' printf ' -e, --enable-editline\n' printf ' Enable the use of libedit/editline. This is meant for those users that\n' printf ' want vi-like or Emacs-like behavior in history. This option is ignored\n' printf ' if history is disabled. If the -r or -i options are given with this\n' printf ' option, the last occurrence of all of the three is used.\n' printf ' -E, --disable-extra-math\n' printf ' Disable extra math. This includes: "$" operator (truncate to integer),\n' printf ' "@" operator (set number of decimal places), and r(x, p) (rounding\n' printf ' function). Additionally, this option disables the extra printing\n' printf ' functions in the math library.\n' printf ' -f, --force\n' printf ' Force use of all enabled options, even if they do not work. This\n' printf ' option is to allow the maintainer a way to test that certain options\n' printf ' are not failing invisibly. (Development only.)\n' printf ' -g, --debug\n' printf ' Build in debug mode. Adds the "-g" flag, and if there are no\n' printf ' other CFLAGS, and "-O" was not given, this also adds the "-O0"\n' printf ' flag. If this flag is *not* given, "-DNDEBUG" is added to CPPFLAGS\n' printf ' and a strip flag is added to the link stage.\n' printf ' -G, --disable-generated-tests\n' printf ' Disable generating tests. This is for platforms that do not have a\n' printf ' GNU bc-compatible bc to generate tests.\n' printf ' -h, --help\n' printf ' Print this help message and exit.\n' printf ' -H, --disable-history\n' printf ' Disable history.\n' printf ' -i, --enable-internal-history\n' printf ' Enable the internal history implementation and do not depend on either\n' printf ' editline or readline. This option is ignored if history is disabled.\n' printf ' If this option is given along with -e and -r, the last occurrence of\n' printf ' all of the three is used.\n' printf ' -k KARATSUBA_LEN, --karatsuba-len KARATSUBA_LEN\n' printf ' Set the karatsuba length to KARATSUBA_LEN (default is 64).\n' printf ' It is an error if KARATSUBA_LEN is not a number or is less than 16.\n' printf ' -l, --install-all-locales\n' printf ' Installs all locales, regardless of how many are on the system. This\n' printf ' option is useful for package maintainers who want to make sure that\n' printf ' a package contains all of the locales that end users might need.\n' printf ' -m, --enable-memcheck\n' printf ' Enable memcheck mode, to ensure no memory leaks. For development only.\n' printf ' -M, --disable-man-pages\n' printf ' Disable installing manpages.\n' printf ' -N, --disable-nls\n' printf ' Disable POSIX locale (NLS) support.\n' printf ' ***WARNING***: Locales ignore the prefix because they *must* be\n' printf ' installed at a fixed location to work at all. If you do not want that\n' printf ' to happen, you must disable locales (NLS) completely.\n' printf ' -O OPT_LEVEL, --opt OPT_LEVEL\n' printf ' Set the optimization level. This can also be included in the CFLAGS,\n' printf ' but it is provided, so maintainers can build optimized debug builds.\n' printf ' This is passed through to the compiler, so it must be supported.\n' printf ' -p TYPE, --predefined-build-type=TYPE\n' printf ' Sets a given predefined build type with specific defaults. This is for\n' printf ' easy setting of predefined builds. For example, to get a build that\n' printf ' acts like the GNU bc by default, TYPE should be "GNU" (without the\n' printf ' quotes) This option *must* come before any others that might change the\n' printf ' build options. Currently supported values for TYPE include: "BSD" (for\n' printf ' matching the BSD bc and BSD dc), "GNU" (for matching the GNU bc and\n' printf ' dc), "GDH" (for the preferred build of the author, Gavin D. Howard),\n' printf ' and "DBG" (for the preferred debug build of the author). This will\n' printf ' also automatically enable a release build (except for "DBG").\n' printf ' -P, --disable-problematic-tests\n' printf ' Disables problematic tests. These tests usually include tests that\n' printf ' can cause a SIGKILL because of too much memory usage.\n' printf ' -r, --enable-readline\n' printf ' Enable the use of libreadline/readline. This is meant for those users\n' printf ' that want vi-like or Emacs-like behavior in history. This option is\n' printf ' ignored if history is disabled. If this option is given along with -e\n' printf ' and -r, the last occurrence of all of the three is used.\n' printf ' -s SETTING, --set-default-on SETTING\n' printf ' Set the default named by SETTING to on. See below for possible values\n' printf ' for SETTING. For multiple instances of the -s or -S for the the same\n' printf ' setting, the last one is used.\n' printf ' -S SETTING, --set-default-off SETTING\n' printf ' Set the default named by SETTING to off. See below for possible values\n' printf ' for SETTING. For multiple instances of the -s or -S for the the same\n' printf ' setting, the last one is used.\n' printf ' -t, --enable-test-timing\n' printf ' Enable the timing of tests. This is for development only.\n' printf ' -T, --disable-strip\n' printf ' Disable stripping symbols from the compiled binary or binaries.\n' printf ' Stripping symbols only happens when debug mode is off.\n' printf ' -v, --enable-valgrind\n' printf ' Enable a build appropriate for valgrind. For development only.\n' printf ' -z, --enable-fuzz-mode\n' printf ' Enable fuzzing mode. THIS IS FOR DEVELOPMENT ONLY.\n' printf ' --prefix PREFIX\n' printf ' The prefix to install to. Overrides "$PREFIX" if it exists.\n' printf ' If PREFIX is "/usr", install path will be "/usr/bin".\n' printf ' Default is "/usr/local".\n' printf ' ***WARNING***: Locales ignore the prefix because they *must* be\n' printf ' installed at a fixed location to work at all. If you do not want that to\n' printf ' happen, you must disable locales (NLS) completely.\n' printf ' --bindir BINDIR\n' printf ' The directory to install binaries in. Overrides "$BINDIR" if it exists.\n' printf ' Default is "$PREFIX/bin".\n' printf ' --includedir INCLUDEDIR\n' printf ' The directory to install headers in. Overrides "$INCLUDEDIR" if it\n' printf ' exists. Default is "$PREFIX/include".\n' printf ' --libdir LIBDIR\n' printf ' The directory to install libraries in. Overrides "$LIBDIR" if it exists.\n' printf ' Default is "$PREFIX/lib".\n' printf ' --datarootdir DATAROOTDIR\n' printf ' The root location for data files. Overrides "$DATAROOTDIR" if it exists.\n' printf ' Default is "$PREFIX/share".\n' printf ' --datadir DATADIR\n' printf ' The location for data files. Overrides "$DATADIR" if it exists.\n' printf ' Default is "$DATAROOTDIR".\n' printf ' --mandir MANDIR\n' printf ' The location to install manpages to. Overrides "$MANDIR" if it exists.\n' printf ' Default is "$DATADIR/man".\n' printf ' --man1dir MAN1DIR\n' printf ' The location to install Section 1 manpages to. Overrides "$MAN1DIR" if\n' printf ' it exists. Default is "$MANDIR/man1".\n' printf ' --man3dir MAN3DIR\n' printf ' The location to install Section 3 manpages to. Overrides "$MAN3DIR" if\n' printf ' it exists. Default is "$MANDIR/man3".\n' printf '\n' printf 'In addition, the following environment variables are used:\n' printf '\n' printf ' CC C compiler. Must be compatible with POSIX c99. If there is a\n' printf ' space in the basename of the compiler, the items after the\n' printf ' first space are assumed to be compiler flags, and in that case,\n' printf ' the flags are automatically moved into CFLAGS. Default is\n' printf ' "c99".\n' printf ' HOSTCC Host C compiler. Must be compatible with POSIX c99. If there is\n' printf ' a space in the basename of the compiler, the items after the\n' printf ' first space are assumed to be compiler flags, and in the case,\n' printf ' the flags are automatically moved into HOSTCFLAGS. Default is\n' printf ' "$CC".\n' printf ' HOST_CC Same as HOSTCC. If HOSTCC also exists, it is used.\n' printf ' CFLAGS C compiler flags.\n' printf ' HOSTCFLAGS CFLAGS for HOSTCC. Default is "$CFLAGS".\n' printf ' HOST_CFLAGS Same as HOST_CFLAGS. If HOST_CFLAGS also exists, it is used.\n' printf ' CPPFLAGS C preprocessor flags. Default is "".\n' printf ' LDFLAGS Linker flags. Default is "".\n' printf ' PREFIX The prefix to install to. Default is "/usr/local".\n' printf ' If PREFIX is "/usr", install path will be "/usr/bin".\n' printf ' ***WARNING***: Locales ignore the prefix because they *must* be\n' printf ' installed at a fixed location to work at all. If you do not\n' printf ' want that to happen, you must disable locales (NLS) completely.\n' printf ' BINDIR The directory to install binaries in. Default is "$PREFIX/bin".\n' printf ' INCLUDEDIR The directory to install header files in. Default is\n' printf ' "$PREFIX/include".\n' printf ' LIBDIR The directory to install libraries in. Default is\n' printf ' "$PREFIX/lib".\n' printf ' DATAROOTDIR The root location for data files. Default is "$PREFIX/share".\n' printf ' DATADIR The location for data files. Default is "$DATAROOTDIR".\n' printf ' MANDIR The location to install manpages to. Default is "$DATADIR/man".\n' printf ' MAN1DIR The location to install Section 1 manpages to. Default is\n' printf ' "$MANDIR/man1".\n' printf ' MAN3DIR The location to install Section 3 manpages to. Default is\n' printf ' "$MANDIR/man3".\n' printf ' NLSPATH The location to install locale catalogs to. Must be an absolute\n' printf ' path (or contain one). This is treated the same as the POSIX\n' printf ' definition of $NLSPATH (see POSIX environment variables for\n' printf ' more information). Default is "/usr/share/locale/%%L/%%N".\n' printf ' PC_PATH The location to install pkg-config files to. Must be an\n' printf ' path or contain one. Default is the first path given by the\n' printf ' output of `pkg-config --variable=pc_path pkg-config`.\n' printf ' EXECSUFFIX The suffix to append to the executable names, used to not\n' printf ' interfere with other installed bc executables. Default is "".\n' printf ' EXECPREFIX The prefix to append to the executable names, used to not\n' printf ' interfere with other installed bc executables. Default is "".\n' printf ' DESTDIR For package creation. Default is "". If it is empty when\n' printf ' `%s` is run, it can also be passed to `make install`\n' "$script" printf ' later as an environment variable. If both are specified,\n' printf ' the one given to `%s` takes precedence.\n' "$script" printf ' LONG_BIT The number of bits in a C `long` type. This is mostly for the\n' printf ' embedded space since this `bc` uses `long`s internally for\n' printf ' overflow checking. In C99, a `long` is required to be 32 bits.\n' printf ' For most normal desktop systems, setting this is unnecessary,\n' printf ' except that 32-bit platforms with 64-bit longs may want to set\n' printf ' it to `32`. Default is the default of `LONG_BIT` for the target\n' printf ' platform. Minimum allowed is `32`. It is a build time error if\n' printf ' the specified value of `LONG_BIT` is greater than the default\n' printf ' value of `LONG_BIT` for the target platform.\n' printf ' GEN_HOST Whether to use `gen/strgen.c`, instead of `gen/strgen.sh`, to\n' printf ' produce the C files that contain the help texts as well as the\n' printf ' math libraries. By default, `gen/strgen.c` is used, compiled by\n' printf ' "$HOSTCC" and run on the host machine. Using `gen/strgen.sh`\n' printf ' removes the need to compile and run an executable on the host\n' printf ' machine since `gen/strgen.sh` is a POSIX shell script. However,\n' printf ' `gen/lib2.bc` is over 4095 characters, the max supported length\n' printf ' of a string literal in C99, and `gen/strgen.sh` generates a\n' printf ' string literal instead of an array, as `gen/strgen.c` does. For\n' printf ' most production-ready compilers, this limit probably is not\n' printf ' enforced, but it could be. Both options are still available for\n' printf ' this reason. If you are sure your compiler does not have the\n' printf ' limit and do not want to compile and run a binary on the host\n' printf ' machine, set this variable to "0". Any other value, or a\n' printf ' non-existent value, will cause the build system to compile and\n' printf ' run `gen/strgen.c`. Default is "".\n' printf ' GEN_EMU Emulator to run string generator code under (leave empty if not\n' printf ' necessary). This is not necessary when using `gen/strgen.sh`.\n' printf ' Default is "".\n' printf '\n' printf 'WARNING: even though `configure.sh` supports both option types, short and\n' printf 'long, it does not support handling both at the same time. Use only one type.\n' printf '\n' printf 'Settings\n' printf '========\n' printf '\n' printf 'bc and dc have some settings that, while they cannot be removed by build time\n' printf 'options, can have their defaults changed at build time by packagers. Users are\n' printf 'also able to change each setting with environment variables.\n' printf '\n' printf 'The following is a table of settings, along with their default values and the\n' printf 'environment variables users can use to change them. (For the defaults, non-zero\n' printf 'means on, and zero means off.)\n' printf '\n' printf '| Setting | Description | Default | Env Variable |\n' printf '| =============== | ==================== | ============ | ==================== |\n' printf '| bc.banner | Whether to display | 0 | BC_BANNER |\n' printf '| | the bc version | | |\n' printf '| | banner when in | | |\n' printf '| | interactive mode. | | |\n' printf '| --------------- | -------------------- | ------------ | -------------------- |\n' printf '| bc.sigint_reset | Whether SIGINT will | 1 | BC_SIGINT_RESET |\n' printf '| | reset bc, instead of | | |\n' printf '| | exiting, when in | | |\n' printf '| | interactive mode. | | |\n' printf '| --------------- | -------------------- | ------------ | -------------------- |\n' printf '| dc.sigint_reset | Whether SIGINT will | 1 | DC_SIGINT_RESET |\n' printf '| | reset dc, instead of | | |\n' printf '| | exiting, when in | | |\n' printf '| | interactive mode. | | |\n' printf '| --------------- | -------------------- | ------------ | -------------------- |\n' printf '| bc.tty_mode | Whether TTY mode for | 1 | BC_TTY_MODE |\n' printf '| | bc should be on when | | |\n' printf '| | available. | | |\n' printf '| --------------- | -------------------- | ------------ | -------------------- |\n' printf '| dc.tty_mode | Whether TTY mode for | 0 | BC_TTY_MODE |\n' printf '| | dc should be on when | | |\n' printf '| | available. | | |\n' printf '| --------------- | -------------------- | ------------ | -------------------- |\n' printf '| bc.prompt | Whether the prompt | $BC_TTY_MODE | BC_PROMPT |\n' printf '| | for bc should be on | | |\n' printf '| | in tty mode. | | |\n' printf '| --------------- | -------------------- | ------------ | -------------------- |\n' printf '| dc.prompt | Whether the prompt | $DC_TTY_MODE | DC_PROMPT |\n' printf '| | for dc should be on | | |\n' printf '| | in tty mode. | | |\n' printf '| --------------- | -------------------- | ------------ | -------------------- |\n' printf '| bc.expr_exit | Whether to exit bc | 1 | BC_EXPR_EXIT |\n' printf '| | if an expression or | | |\n' printf '| | expression file is | | |\n' printf '| | given with the -e or | | |\n' printf '| | -f options. | | |\n' printf '| --------------- | -------------------- | ------------ | -------------------- |\n' printf '| dc.expr_exit | Whether to exit dc | 1 | DC_EXPR_EXIT |\n' printf '| | if an expression or | | |\n' printf '| | expression file is | | |\n' printf '| | given with the -e or | | |\n' printf '| | -f options. | | |\n' printf '| --------------- | -------------------- | ------------ | -------------------- |\n' printf '| bc.digit_clamp | Whether to have bc | 0 | BC_DIGIT_CLAMP |\n' printf '| | clamp digits that | | |\n' printf '| | are greater than or | | |\n' printf '| | equal to the current | | |\n' printf '| | ibase when parsing | | |\n' printf '| | numbers. | | |\n' printf '| --------------- | -------------------- | ------------ | -------------------- |\n' printf '| dc.digit_clamp | Whether to have dc | 0 | DC_DIGIT_CLAMP |\n' printf '| | clamp digits that | | |\n' printf '| | are greater than or | | |\n' printf '| | equal to the current | | |\n' printf '| | ibase when parsing | | |\n' printf '| | numbers. | | |\n' printf '| --------------- | -------------------- | ------------ | -------------------- |\n' printf '\n' printf 'These settings are not meant to be changed on a whim. They are meant to ensure\n' printf 'that this bc and dc will conform to the expectations of the user on each\n' printf 'platform.\n' exit "$_usage_val" } # Replaces a file extension in a filename. This is used mostly to turn filenames # like `src/num.c` into `src/num.o`. In other words, it helps to link targets to # the files they depend on. # # @param file The filename. # @param ext1 The extension to replace. # @param ext2 The new extension. replace_ext() { if [ "$#" -ne 3 ]; then err_exit "Invalid number of args to $0" fi _replace_ext_file="$1" _replace_ext_ext1="$2" _replace_ext_ext2="$3" _replace_ext_result="${_replace_ext_file%.$_replace_ext_ext1}.$_replace_ext_ext2" printf '%s\n' "$_replace_ext_result" } # Replaces a file extension in every filename given in a list. The list is just # a space-separated list of words, so filenames are expected to *not* have # spaces in them. See the documentation for `replace_ext()`. # # @param files The list of space-separated filenames to replace extensions for. # @param ext1 The extension to replace. # @param ext2 The new extension. replace_exts() { if [ "$#" -ne 3 ]; then err_exit "Invalid number of args to $0" fi _replace_exts_files="$1" _replace_exts_ext1="$2" _replace_exts_ext2="$3" for _replace_exts_file in $_replace_exts_files; do _replace_exts_new_name=$(replace_ext "$_replace_exts_file" "$_replace_exts_ext1" "$_replace_exts_ext2") _replace_exts_result="$_replace_exts_result $_replace_exts_new_name" done printf '%s\n' "$_replace_exts_result" } # Finds a placeholder in @a str and replaces it. This is the workhorse of # configure.sh. It's what replaces placeholders in Makefile.in with the data # needed for the chosen build. Below, you will see a lot of calls to this # function. # # Note that needle can never contain an exclamation point. For more information, # see substring_replace() in scripts/functions.sh. # # @param str The string to find and replace placeholders in. # @param needle The placeholder name. # @param replacement The string to use to replace the placeholder. replace() { if [ "$#" -ne 3 ]; then err_exit "Invalid number of args to $0" fi _replace_str="$1" _replace_needle="$2" _replace_replacement="$3" substring_replace "$_replace_str" "%%$_replace_needle%%" "$_replace_replacement" } # This function finds all the source files that need to be built. If there is # only one argument and it is empty, then all source files are built. Otherwise, # the arguments are all assumed to be source files that should *not* be built. find_src_files() { _find_src_files_args="" if [ "$#" -ge 1 ] && [ "$1" != "" ]; then while [ "$#" -ge 1 ]; do _find_src_files_a="${1## }" shift _find_src_files_args=$(printf '%s\n%s/src/%s\n' "$_find_src_files_args" "$scriptdir" "${_find_src_files_a}") done fi _find_src_files_files=$(find "$scriptdir/src/" -depth -name "*.c" -print | LC_ALL=C sort) _find_src_files_result="" for _find_src_files_f in $_find_src_files_files; do # If this is true, the file is part of args, and therefore, unneeded. if [ "${_find_src_files_args##*$_find_src_files_f}" != "${_find_src_files_args}" ]; then continue fi _find_src_files_result=$(printf '%s\n%s\n' "$_find_src_files_result" "$_find_src_files_f") done printf '%s\n' "$_find_src_files_result" } # This function generates a list of files to go into the Makefile. It generates # the list of object files, as well as the list of test coverage files. # # @param contents The contents of the Makefile template to put the list of # files into. gen_file_list() { if [ "$#" -lt 1 ]; then err_exit "Invalid number of args to $0" fi _gen_file_list_contents="$1" shift if [ "$#" -ge 1 ]; then _gen_file_list_unneeded="$@" else _gen_file_list_unneeded="" fi _gen_file_list_needle_src="SRC" _gen_file_list_needle_obj="OBJ" _gen_file_list_needle_gcda="GCDA" _gen_file_list_needle_gcno="GCNO" _gen_file_list_replacement=$(find_src_files $_gen_file_list_unneeded | tr '\n' ' ') _gen_file_list_contents=$(replace "$_gen_file_list_contents" \ "$_gen_file_list_needle_src" "$_gen_file_list_replacement") _gen_file_list_cbases="" for _gen_file_list_f in $_gen_file_list_replacement; do _gen_file_list_b=$(basename "$_gen_file_list_f") _gen_file_list_cbases="$_gen_file_list_cbases src/$_gen_file_list_b" done _gen_file_list_replacement=$(replace_exts "$_gen_file_list_cbases" "c" "o") _gen_file_list_contents=$(replace "$_gen_file_list_contents" \ "$_gen_file_list_needle_obj" "$_gen_file_list_replacement") _gen_file_list_replacement=$(replace_exts "$_gen_file_list_replacement" "o" "gcda") _gen_file_list_contents=$(replace "$_gen_file_list_contents" \ "$_gen_file_list_needle_gcda" "$_gen_file_list_replacement") _gen_file_list_replacement=$(replace_exts "$_gen_file_list_replacement" "gcda" "gcno") _gen_file_list_contents=$(replace "$_gen_file_list_contents" \ "$_gen_file_list_needle_gcno" "$_gen_file_list_replacement") printf '%s\n' "$_gen_file_list_contents" } # Generates the proper test targets for each test to have its own target. This # allows `make test` to run in parallel. # # @param name Which calculator to generate tests for. # @param extra_math An integer that, if non-zero, activates extra math tests. # @param time_tests An integer that, if non-zero, tells the test suite to time # the execution of each test. gen_std_tests() { _gen_std_tests_name="$1" shift _gen_std_tests_extra_math="$1" shift _gen_std_tests_time_tests="$1" shift _gen_std_tests_extra_required=$(cat "$scriptdir/tests/extra_required.txt") for _gen_std_tests_t in $(cat "$scriptdir/tests/$_gen_std_tests_name/all.txt"); do if [ "$_gen_std_tests_extra_math" -eq 0 ]; then if [ -z "${_gen_std_tests_extra_required##*$_gen_std_tests_t*}" ]; then printf 'test_%s_%s:\n\t@printf "Skipping %s %s\\n"\n\n' \ "$_gen_std_tests_name" "$_gen_std_tests_t" "$_gen_std_tests_name" \ "$_gen_std_tests_t" >> "Makefile" continue fi fi printf 'test_%s_%s:\n\t@export BC_TEST_OUTPUT_DIR="%s/tests"; sh $(TESTSDIR)/test.sh %s %s %s %s %s\n\n' \ "$_gen_std_tests_name" "$_gen_std_tests_t" "$builddir" "$_gen_std_tests_name" \ "$_gen_std_tests_t" "$generate_tests" "$time_tests" \ "$*" >> "Makefile" done } # Generates a list of test targets that will be used as prerequisites for other # targets. # # @param name The name of the calculator to generate test targets for. gen_std_test_targets() { _gen_std_test_targets_name="$1" shift _gen_std_test_targets_tests=$(cat "$scriptdir/tests/${_gen_std_test_targets_name}/all.txt") for _gen_std_test_targets_t in $_gen_std_test_targets_tests; do printf ' test_%s_%s' "$_gen_std_test_targets_name" "$_gen_std_test_targets_t" done printf '\n' } # Generates the proper test targets for each error test to have its own target. # This allows `make test_bc_errors` and `make test_dc_errors` to run in # parallel. # # @param name Which calculator to generate tests for. gen_err_tests() { _gen_err_tests_name="$1" shift _gen_err_tests_fs=$(ls "$scriptdir/tests/$_gen_err_tests_name/errors/") for _gen_err_tests_t in $_gen_err_tests_fs; do printf 'test_%s_error_%s:\n\t@export BC_TEST_OUTPUT_DIR="%s/tests"; sh $(TESTSDIR)/error.sh %s %s %s %s\n\n' \ "$_gen_err_tests_name" "$_gen_err_tests_t" "$builddir" "$_gen_err_tests_name" \ "$_gen_err_tests_t" "$problematic_tests" "$*" >> "Makefile" done } # Generates a list of error test targets that will be used as prerequisites for # other targets. # # @param name The name of the calculator to generate test targets for. gen_err_test_targets() { _gen_err_test_targets_name="$1" shift _gen_err_test_targets_tests=$(ls "$scriptdir/tests/$_gen_err_test_targets_name/errors/") for _gen_err_test_targets_t in $_gen_err_test_targets_tests; do printf ' test_%s_error_%s' "$_gen_err_test_targets_name" "$_gen_err_test_targets_t" done printf '\n' } # Generates the proper script test targets for each script test to have its own # target. This allows `make test` to run in parallel. # # @param name Which calculator to generate tests for. # @param extra_math An integer that, if non-zero, activates extra math tests. # @param generate An integer that, if non-zero, activates generated tests. # @param time_tests An integer that, if non-zero, tells the test suite to time # the execution of each test. gen_script_tests() { _gen_script_tests_name="$1" shift _gen_script_tests_extra_math="$1" shift _gen_script_tests_generate="$1" shift _gen_script_tests_time="$1" shift _gen_script_tests_tests=$(cat "$scriptdir/tests/$_gen_script_tests_name/scripts/all.txt") for _gen_script_tests_f in $_gen_script_tests_tests; do _gen_script_tests_b=$(basename "$_gen_script_tests_f" ".${_gen_script_tests_name}") printf 'test_%s_script_%s:\n\t@export BC_TEST_OUTPUT_DIR="%s/tests"; sh $(TESTSDIR)/script.sh %s %s %s 1 %s %s %s\n\n' \ "$_gen_script_tests_name" "$_gen_script_tests_b" "$builddir" "$_gen_script_tests_name" \ "$_gen_script_tests_f" "$_gen_script_tests_extra_math" "$_gen_script_tests_generate" \ "$_gen_script_tests_time" "$*" >> "Makefile" done } set_default() { _set_default_on="$1" shift _set_default_name="$1" shift # The reason that the variables that are being set do not have the same # non-collision avoidance that the other variables do is that we *do* want # the settings of these variables to leak out of the function. They adjust # the settings outside of the function. case "$_set_default_name" in bc.banner) bc_default_banner="$_set_default_on" ;; bc.sigint_reset) bc_default_sigint_reset="$_set_default_on" ;; dc.sigint_reset) dc_default_sigint_reset="$_set_default_on" ;; bc.tty_mode) bc_default_tty_mode="$_set_default_on" ;; dc.tty_mode) dc_default_tty_mode="$_set_default_on" ;; bc.prompt) bc_default_prompt="$_set_default_on" ;; dc.prompt) dc_default_prompt="$_set_default_on" ;; bc.expr_exit) bc_default_expr_exit="$_set_default_on";; dc.expr_exit) dc_default_expr_exit="$_set_default_on";; bc.digit_clamp) bc_default_digit_clamp="$_set_default_on";; dc.digit_clamp) dc_default_digit_clamp="$_set_default_on";; ?) usage "Invalid setting: $_set_default_name" ;; esac } predefined_build() { _predefined_build_type="$1" shift # The reason that the variables that are being set do not have the same # non-collision avoidance that the other variables do is that we *do* want # the settings of these variables to leak out of the function. They adjust # the settings outside of the function. case "$_predefined_build_type" in BSD) bc_only=0 dc_only=0 coverage=0 debug=0 optimization="3" hist=1 hist_impl="editline" extra_math=1 generate_tests=$generate_tests install_manpages=0 nls=1 force=0 strip_bin=1 all_locales=0 library=0 fuzz=0 time_tests=0 vg=0 memcheck=0 clean=1 bc_default_banner=0 bc_default_sigint_reset=1 dc_default_sigint_reset=1 bc_default_tty_mode=1 dc_default_tty_mode=0 bc_default_prompt="" dc_default_prompt="" bc_default_expr_exit=1 dc_default_expr_exit=1 bc_default_digit_clamp=0 dc_default_digit_clamp=0;; GNU) bc_only=0 dc_only=0 coverage=0 debug=0 optimization="3" hist=1 hist_impl="internal" extra_math=1 generate_tests=$generate_tests install_manpages=1 nls=1 force=0 strip_bin=1 all_locales=0 library=0 fuzz=0 time_tests=0 vg=0 memcheck=0 clean=1 bc_default_banner=1 bc_default_sigint_reset=1 dc_default_sigint_reset=0 bc_default_tty_mode=1 dc_default_tty_mode=0 bc_default_prompt="" dc_default_prompt="" bc_default_expr_exit=1 dc_default_expr_exit=1 bc_default_digit_clamp=1 dc_default_digit_clamp=0;; GDH) CFLAGS="-flto -Weverything -Wno-padded -Werror -pedantic -std=c11" bc_only=0 dc_only=0 coverage=0 debug=0 optimization="3" hist=1 hist_impl="internal" extra_math=1 generate_tests=1 install_manpages=1 nls=0 force=0 strip_bin=1 all_locales=0 library=0 fuzz=0 time_tests=0 vg=0 memcheck=0 clean=1 bc_default_banner=1 bc_default_sigint_reset=1 dc_default_sigint_reset=1 bc_default_tty_mode=1 dc_default_tty_mode=1 bc_default_prompt="" dc_default_prompt="" bc_default_expr_exit=0 dc_default_expr_exit=0 bc_default_digit_clamp=1 dc_default_digit_clamp=1;; DBG) CFLAGS="-Weverything -Wno-padded -Werror -pedantic -std=c11" bc_only=0 dc_only=0 coverage=0 debug=1 optimization="0" hist=1 hist_impl="internal" extra_math=1 generate_tests=1 install_manpages=1 nls=1 force=0 strip_bin=1 all_locales=0 library=0 fuzz=0 time_tests=0 vg=0 memcheck=1 clean=1 bc_default_banner=1 bc_default_sigint_reset=1 dc_default_sigint_reset=1 bc_default_tty_mode=1 dc_default_tty_mode=1 bc_default_prompt="" dc_default_prompt="" bc_default_expr_exit=0 dc_default_expr_exit=0 bc_default_digit_clamp=1 dc_default_digit_clamp=1;; ?|'') usage "Invalid user build: \"$_predefined_build_type\". Accepted types are BSD, GNU, GDH, DBG.";; esac } # Generates a list of script test targets that will be used as prerequisites for # other targets. # # @param name The name of the calculator to generate script test targets for. gen_script_test_targets() { _gen_script_test_targets_name="$1" shift _gen_script_test_targets_tests=$(cat "$scriptdir/tests/$_gen_script_test_targets_name/scripts/all.txt") for _gen_script_test_targets_f in $_gen_script_test_targets_tests; do _gen_script_test_targets_b=$(basename "$_gen_script_test_targets_f" \ ".$_gen_script_test_targets_name") printf ' test_%s_script_%s' "$_gen_script_test_targets_name" \ "$_gen_script_test_targets_b" done printf '\n' } # This is a list of defaults, but it is also the list of possible options for # users to change. # # The development options are: force (force options even if they fail), valgrind # (build in a way suitable for valgrind testing), memcheck (same as valgrind), # and fuzzing (build in a way suitable for fuzzing). bc_only=0 dc_only=0 coverage=0 karatsuba_len=32 debug=0 hist=1 hist_impl="internal" extra_math=1 optimization="" generate_tests=1 install_manpages=1 nls=1 force=0 strip_bin=1 all_locales=0 library=0 fuzz=0 time_tests=0 vg=0 memcheck=0 clean=1 problematic_tests=1 # The empty strings are because they depend on TTY mode. If they are directly # set, though, they will be integers. We test for empty strings later. bc_default_banner=0 bc_default_sigint_reset=1 dc_default_sigint_reset=1 bc_default_tty_mode=1 dc_default_tty_mode=0 bc_default_prompt="" dc_default_prompt="" bc_default_expr_exit=1 dc_default_expr_exit=1 bc_default_digit_clamp=0 dc_default_digit_clamp=0 # getopts is a POSIX utility, but it cannot handle long options. Thus, the # handling of long options is done by hand, and that's the reason that short and # long options cannot be mixed. while getopts "abBcdDeEfgGhHik:lMmNO:p:PrS:s:tTvz-" opt; do case "$opt" in a) library=1 ;; b) bc_only=1 ;; B) dc_only=1 ;; c) coverage=1 ;; C) clean=0 ;; d) dc_only=1 ;; D) bc_only=1 ;; e) hist_impl="editline" ;; E) extra_math=0 ;; f) force=1 ;; g) debug=1 ;; G) generate_tests=0 ;; h) usage ;; H) hist=0 ;; i) hist_impl="internal" ;; k) karatsuba_len="$OPTARG" ;; l) all_locales=1 ;; m) memcheck=1 ;; M) install_manpages=0 ;; N) nls=0 ;; O) optimization="$OPTARG" ;; p) predefined_build "$OPTARG" ;; P) problematic_tests=0 ;; r) hist_impl="readline" ;; S) set_default 0 "$OPTARG" ;; s) set_default 1 "$OPTARG" ;; t) time_tests=1 ;; T) strip_bin=0 ;; v) vg=1 ;; z) fuzz=1 ;; -) arg="$1" arg="${arg#--}" LONG_OPTARG="${arg#*=}" case $arg in help) usage ;; library) library=1 ;; bc-only) bc_only=1 ;; dc-only) dc_only=1 ;; coverage) coverage=1 ;; debug) debug=1 ;; force) force=1 ;; prefix=?*) PREFIX="$LONG_OPTARG" ;; prefix) if [ "$#" -lt 2 ]; then usage "No argument given for '--$arg' option" fi PREFIX="$2" shift ;; bindir=?*) BINDIR="$LONG_OPTARG" ;; bindir) if [ "$#" -lt 2 ]; then usage "No argument given for '--$arg' option" fi BINDIR="$2" shift ;; includedir=?*) INCLUDEDIR="$LONG_OPTARG" ;; includedir) if [ "$#" -lt 2 ]; then usage "No argument given for '--$arg' option" fi INCLUDEDIR="$2" shift ;; libdir=?*) LIBDIR="$LONG_OPTARG" ;; libdir) if [ "$#" -lt 2 ]; then usage "No argument given for '--$arg' option" fi LIBDIR="$2" shift ;; datarootdir=?*) DATAROOTDIR="$LONG_OPTARG" ;; datarootdir) if [ "$#" -lt 2 ]; then usage "No argument given for '--$arg' option" fi DATAROOTDIR="$2" shift ;; datadir=?*) DATADIR="$LONG_OPTARG" ;; datadir) if [ "$#" -lt 2 ]; then usage "No argument given for '--$arg' option" fi DATADIR="$2" shift ;; mandir=?*) MANDIR="$LONG_OPTARG" ;; mandir) if [ "$#" -lt 2 ]; then usage "No argument given for '--$arg' option" fi MANDIR="$2" shift ;; man1dir=?*) MAN1DIR="$LONG_OPTARG" ;; man1dir) if [ "$#" -lt 2 ]; then usage "No argument given for '--$arg' option" fi MAN1DIR="$2" shift ;; man3dir=?*) MAN3DIR="$LONG_OPTARG" ;; man3dir) if [ "$#" -lt 2 ]; then usage "No argument given for '--$arg' option" fi MAN3DIR="$2" shift ;; karatsuba-len=?*) karatsuba_len="$LONG_OPTARG" ;; karatsuba-len) if [ "$#" -lt 2 ]; then usage "No argument given for '--$arg' option" fi karatsuba_len="$1" shift ;; opt=?*) optimization="$LONG_OPTARG" ;; opt) if [ "$#" -lt 2 ]; then usage "No argument given for '--$arg' option" fi optimization="$1" shift ;; set-default-on=?*) set_default 1 "$LONG_OPTARG" ;; set-default-on) if [ "$#" -lt 2 ]; then usage "No argument given for '--$arg' option" fi set_default 1 "$1" shift ;; set-default-off=?*) set_default 0 "$LONG_OPTARG" ;; set-default-off) if [ "$#" -lt 2 ]; then usage "No argument given for '--$arg' option" fi set_default 0 "$1" shift ;; predefined-build-type=?*) predefined_build "$LONG_OPTARG" ;; predefined-build-type) if [ "$#" -lt 2 ]; then usage "No argument given for '--$arg' option" fi predefined_build "$1" shift ;; disable-bc) dc_only=1 ;; disable-dc) bc_only=1 ;; disable-clean) clean=0 ;; disable-extra-math) extra_math=0 ;; disable-generated-tests) generate_tests=0 ;; disable-history) hist=0 ;; disable-man-pages) install_manpages=0 ;; disable-nls) nls=0 ;; disable-strip) strip_bin=0 ;; disable-problematic-tests) problematic_tests=0 ;; enable-editline) hist_impl="editline" ;; enable-readline) hist_impl="readline" ;; enable-internal-history) hist_impl="internal" ;; enable-test-timing) time_tests=1 ;; enable-valgrind) vg=1 ;; enable-fuzz-mode) fuzz=1 ;; enable-memcheck) memcheck=1 ;; install-all-locales) all_locales=1 ;; help* | bc-only* | dc-only* | coverage* | debug*) usage "No arg allowed for --$arg option" ;; disable-bc* | disable-dc* | disable-clean*) usage "No arg allowed for --$arg option" ;; disable-extra-math*) usage "No arg allowed for --$arg option" ;; disable-generated-tests* | disable-history*) usage "No arg allowed for --$arg option" ;; disable-man-pages* | disable-nls* | disable-strip*) usage "No arg allowed for --$arg option" ;; disable-problematic-tests*) usage "No arg allowed for --$arg option" ;; enable-fuzz-mode* | enable-test-timing* | enable-valgrind*) usage "No arg allowed for --$arg option" ;; enable-memcheck* | install-all-locales*) usage "No arg allowed for --$arg option" ;; enable-editline* | enable-readline*) usage "No arg allowed for --$arg option" ;; enable-internal-history*) usage "No arg allowed for --$arg option" ;; '') break ;; # "--" terminates argument processing * ) usage "Invalid option $LONG_OPTARG" ;; esac shift OPTIND=1 ;; ?) usage "Invalid option: $opt" ;; esac done # Sometimes, developers don't want configure.sh to do a config clean. But # sometimes they do. if [ "$clean" -ne 0 ]; then if [ -f ./Makefile ]; then make clean_config > /dev/null fi fi # It is an error to say that bc only should be built and likewise for dc. if [ "$bc_only" -eq 1 ] && [ "$dc_only" -eq 1 ]; then usage "Can only specify one of -b(-D) or -d(-B)" fi # The library is mutually exclusive to the calculators, so it's an error to # give an option for either of them. if [ "$library" -ne 0 ]; then if [ "$bc_only" -eq 1 ] || [ "$dc_only" -eq 1 ]; then usage "Must not specify -b(-D) or -d(-B) when building the library" fi fi # KARATSUBA_LEN must be an integer and must be 16 or greater. case $karatsuba_len in (*[!0-9]*|'') usage "KARATSUBA_LEN is not a number" ;; (*) ;; esac if [ "$karatsuba_len" -lt 16 ]; then usage "KARATSUBA_LEN is less than 16" fi set -e if [ -z "${LONG_BIT+set}" ]; then LONG_BIT_DEFINE="" elif [ "$LONG_BIT" -lt 32 ]; then usage "LONG_BIT is less than 32" else LONG_BIT_DEFINE="-DBC_LONG_BIT=$LONG_BIT" fi if [ -z "$CC" ]; then CC="c99" else # I had users complain that, if they gave CFLAGS as part of CC, which # autotools allows in its braindead way, the build would fail with an error. # I don't like adjusting for autotools, but oh well. These lines puts the # stuff after the first space into CFLAGS. ccbase=$(basename "$CC") suffix=" *" prefix="* " if [ "${ccbase%%$suffix}" != "$ccbase" ]; then ccflags="${ccbase#$prefix}" cc="${ccbase%%$suffix}" ccdir=$(dirname "$CC") if [ "$ccdir" = "." ] && [ "${CC#.}" = "$CC" ]; then ccdir="" else ccdir="$ccdir/" fi CC="${ccdir}${cc}" CFLAGS="$CFLAGS $ccflags" fi fi if [ -z "$HOSTCC" ] && [ -z "$HOST_CC" ]; then HOSTCC="$CC" elif [ -z "$HOSTCC" ]; then HOSTCC="$HOST_CC" fi if [ "$HOSTCC" != "$CC" ]; then # Like above, this splits HOSTCC and HOSTCFLAGS. ccbase=$(basename "$HOSTCC") suffix=" *" prefix="* " if [ "${ccbase%%$suffix}" != "$ccbase" ]; then ccflags="${ccbase#$prefix}" cc="${ccbase%%$suffix}" ccdir=$(dirname "$HOSTCC") if [ "$ccdir" = "." ] && [ "${HOSTCC#.}" = "$HOSTCC" ]; then ccdir="" else ccdir="$ccdir/" fi HOSTCC="${ccdir}${cc}" HOSTCFLAGS="$HOSTCFLAGS $ccflags" fi fi if [ -z "${HOSTCFLAGS+set}" ] && [ -z "${HOST_CFLAGS+set}" ]; then HOSTCFLAGS="$CFLAGS" elif [ -z "${HOSTCFLAGS+set}" ]; then HOSTCFLAGS="$HOST_CFLAGS" fi # Store these for the cross compilation detection later. OLDCFLAGS="$CFLAGS" OLDHOSTCFLAGS="$HOSTCFLAGS" link="@printf 'No link necessary\\\\n'" main_exec="BC" executable="BC_EXEC" tests="test_bc timeconst test_dc" bc_test="@export BC_TEST_OUTPUT_DIR=\"$builddir/tests\"; \$(TESTSDIR)/all.sh bc $extra_math 1 $generate_tests $problematic_tests $time_tests \$(BC_EXEC)" bc_test_np="@export BC_TEST_OUTPUT_DIR=\"$builddir/tests\"; \$(TESTSDIR)/all.sh -n bc $extra_math 1 $generate_tests $problematic_tests $time_tests \$(BC_EXEC)" dc_test="@export BC_TEST_OUTPUT_DIR=\"$builddir/tests\"; \$(TESTSDIR)/all.sh dc $extra_math 1 $generate_tests $problematic_tests $time_tests \$(DC_EXEC)" dc_test_np="@export BC_TEST_OUTPUT_DIR=\"$builddir/tests\"; \$(TESTSDIR)/all.sh -n dc $extra_math 1 $generate_tests $problematic_tests $time_tests \$(DC_EXEC)" timeconst="@export BC_TEST_OUTPUT_DIR=\"$builddir/tests\"; \$(TESTSDIR)/bc/timeconst.sh \$(TESTSDIR)/bc/scripts/timeconst.bc \$(BC_EXEC)" # In order to have cleanup at exit, we need to be in # debug mode, so don't run valgrind without that. if [ "$vg" -ne 0 ]; then debug=1 bc_test_exec='valgrind $(VALGRIND_ARGS) $(BC_EXEC)' dc_test_exec='valgrind $(VALGRIND_ARGS) $(DC_EXEC)' bcl_test_exec='valgrind $(VALGRIND_ARGS) $(BCL_TEST)' else bc_test_exec='$(BC_EXEC)' dc_test_exec='$(DC_EXEC)' bcl_test_exec='$(BCL_TEST)' fi test_bc_history_prereqs="test_bc_history_all" test_dc_history_prereqs="test_dc_history_all" karatsuba="@printf 'karatsuba cannot be run because one of bc or dc is not built\\\\n'" karatsuba_test="@printf 'karatsuba cannot be run because one of bc or dc is not built\\\\n'" bc_lib="\$(GEN_DIR)/lib.o" bc_help="\$(GEN_DIR)/bc_help.o" dc_help="\$(GEN_DIR)/dc_help.o" default_target_prereqs="\$(BIN) \$(OBJS)" default_target_cmd="\$(CC) \$(CFLAGS) \$(OBJS) \$(LDFLAGS) -o \$(EXEC)" default_target="\$(DC_EXEC)" second_target_prereqs="" second_target_cmd="$default_target_cmd" second_target="\$(BC_EXEC)" # This if/else if chain is for setting the defaults that change based on whether # the library is being built, bc only, dc only, or both calculators. if [ "$library" -ne 0 ]; then extra_math=1 nls=0 hist=0 bc=1 dc=1 default_target_prereqs="\$(BIN) \$(OBJ)" default_target_cmd="ar -r -cu \$(LIBBC) \$(OBJ)" default_target="\$(LIBBC)" tests="test_library" test_bc_history_prereqs=" test_bc_history_skip" test_dc_history_prereqs=" test_dc_history_skip" install_prereqs=" install_library" uninstall_prereqs=" uninstall_library" install_man_prereqs=" install_bcl_manpage" uninstall_man_prereqs=" uninstall_bcl_manpage" elif [ "$bc_only" -eq 1 ]; then bc=1 dc=0 dc_help="" executables="bc" dc_test="@printf 'No dc tests to run\\\\n'" dc_test_np="@printf 'No dc tests to run\\\\n'" test_dc_history_prereqs=" test_dc_history_skip" install_prereqs=" install_execs" install_man_prereqs=" install_bc_manpage" uninstall_prereqs=" uninstall_bc" uninstall_man_prereqs=" uninstall_bc_manpage" default_target="\$(BC_EXEC)" second_target="\$(DC_EXEC)" tests="test_bc timeconst" elif [ "$dc_only" -eq 1 ]; then bc=0 dc=1 bc_lib="" bc_help="" executables="dc" main_exec="DC" executable="DC_EXEC" bc_test="@printf 'No bc tests to run\\\\n'" bc_test_np="@printf 'No bc tests to run\\\\n'" test_bc_history_prereqs=" test_bc_history_skip" timeconst="@printf 'timeconst cannot be run because bc is not built\\\\n'" install_prereqs=" install_execs" install_man_prereqs=" install_dc_manpage" uninstall_prereqs=" uninstall_dc" uninstall_man_prereqs=" uninstall_dc_manpage" tests="test_dc" else bc=1 dc=1 executables="bc and dc" karatsuba="@\$(KARATSUBA) 30 0 \$(BC_EXEC)" karatsuba_test="@\$(KARATSUBA) 1 100 \$(BC_EXEC)" if [ "$library" -eq 0 ]; then install_prereqs=" install_execs" install_man_prereqs=" install_bc_manpage install_dc_manpage" uninstall_prereqs=" uninstall_bc uninstall_dc" uninstall_man_prereqs=" uninstall_bc_manpage uninstall_dc_manpage" else install_prereqs=" install_library install_bcl_header" install_man_prereqs=" install_bcl_manpage" uninstall_prereqs=" uninstall_library uninstall_bcl_header" uninstall_man_prereqs=" uninstall_bcl_manpage" tests="test_library" fi second_target_prereqs="$default_target_prereqs" default_target_prereqs="$second_target" default_target_cmd="\$(LINK) \$(BIN) \$(EXEC_PREFIX)\$(DC)" fi # We need specific stuff for fuzzing. if [ "$fuzz" -ne 0 ]; then debug=1 hist=0 nls=0 optimization="3" fi # This sets some necessary things for debug mode. if [ "$debug" -eq 1 ]; then if [ -z "$CFLAGS" ] && [ -z "$optimization" ]; then CFLAGS="-O0" fi ccbase=$(basename "$CC") if [ "$ccbase" = "clang" ]; then CFLAGS="-gdwarf-4 $CFLAGS" else CFLAGS="-g $CFLAGS" fi else CPPFLAGS="-DNDEBUG $CPPFLAGS" if [ "$strip_bin" -ne 0 ]; then LDFLAGS="-s $LDFLAGS" fi fi # Set optimization CFLAGS. if [ -n "$optimization" ]; then CFLAGS="-O$optimization $CFLAGS" fi # Set test coverage defaults. if [ "$coverage" -eq 1 ]; then if [ "$bc_only" -eq 1 ] || [ "$dc_only" -eq 1 ]; then usage "Can only specify -c without -b or -d" fi CFLAGS="-fprofile-arcs -ftest-coverage -g -O0 $CFLAGS" CPPFLAGS="-DNDEBUG $CPPFLAGS" COVERAGE_OUTPUT="@gcov -pabcdf \$(GCDA) \$(BC_GCDA) \$(DC_GCDA) \$(HISTORY_GCDA) \$(RAND_GCDA)" COVERAGE_OUTPUT="$COVERAGE_OUTPUT;\$(RM) -f \$(GEN)*.gc*" COVERAGE_OUTPUT="$COVERAGE_OUTPUT;gcovr --exclude-unreachable-branches --exclude-throw-branches --html-details --output index.html" COVERAGE_PREREQS=" test coverage_output" else COVERAGE_OUTPUT="@printf 'Coverage not generated\\\\n'" COVERAGE_PREREQS="" fi # Set some defaults. if [ -z "${DESTDIR+set}" ]; then destdir="" else destdir="DESTDIR = $DESTDIR" fi # defprefix is for a warning about locales later. if [ -z "${PREFIX+set}" ]; then PREFIX="/usr/local" defprefix=1 else defprefix=0 fi if [ -z "${BINDIR+set}" ]; then BINDIR="$PREFIX/bin" fi if [ -z "${INCLUDEDIR+set}" ]; then INCLUDEDIR="$PREFIX/include" fi if [ -z "${LIBDIR+set}" ]; then LIBDIR="$PREFIX/lib" fi if [ -z "${PC_PATH+set}" ]; then set +e command -v pkg-config > /dev/null err=$? set -e if [ "$err" -eq 0 ]; then PC_PATH=$(pkg-config --variable=pc_path pkg-config) PC_PATH="${PC_PATH%%:*}" else PC_PATH="" fi fi # Set a default for the DATAROOTDIR. This is done if either manpages will be # installed, or locales are enabled because that's probably where NLSPATH # points. if [ "$install_manpages" -ne 0 ] || [ "$nls" -ne 0 ]; then if [ -z "${DATAROOTDIR+set}" ]; then DATAROOTDIR="$PREFIX/share" fi fi # Set defaults for manpage environment variables. if [ "$install_manpages" -ne 0 ]; then if [ -z "${DATADIR+set}" ]; then DATADIR="$DATAROOTDIR" fi if [ -z "${MANDIR+set}" ]; then MANDIR="$DATADIR/man" fi if [ -z "${MAN1DIR+set}" ]; then MAN1DIR="$MANDIR/man1" fi if [ -z "${MAN3DIR+set}" ]; then MAN3DIR="$MANDIR/man3" fi else install_man_prereqs="" uninstall_man_prereqs="" fi # Here is where we test NLS (the locale system). This is done by trying to # compile src/vm.c, which has the relevant code. If it fails, then it is # disabled. if [ "$nls" -ne 0 ]; then set +e printf 'Testing NLS...\n' flags="-DBC_ENABLE_NLS=1 -DBC_ENABLED=$bc -DDC_ENABLED=$dc" flags="$flags -DBC_ENABLE_HISTORY=$hist -DBC_ENABLE_LIBRARY=0 -DBC_ENABLE_AFL=0" flags="$flags -DBC_ENABLE_EXTRA_MATH=$extra_math -I$scriptdir/include/" flags="$flags -D_POSIX_C_SOURCE=200809L -D_XOPEN_SOURCE=700" ccbase=$(basename "$CC") if [ "$ccbase" = "clang" ]; then flags="$flags -Wno-unreachable-code" fi "$CC" $CPPFLAGS $CFLAGS $flags -c "$scriptdir/src/vm.c" -o "./vm.o" > /dev/null 2>&1 err="$?" rm -rf "./vm.o" # If this errors, it is probably because of building on Windows, # and NLS is not supported on Windows, so disable it. if [ "$err" -ne 0 ]; then printf 'NLS does not work.\n' if [ $force -eq 0 ]; then printf 'Disabling NLS...\n\n' nls=0 else printf 'Forcing NLS...\n\n' fi else printf 'NLS works.\n\n' printf 'Testing gencat...\n' gencat "./en_US.cat" "$scriptdir/locales/en_US.msg" > /dev/null 2>&1 err="$?" rm -rf "./en_US.cat" if [ "$err" -ne 0 ]; then printf 'gencat does not work.\n' if [ $force -eq 0 ]; then printf 'Disabling NLS...\n\n' nls=0 else printf 'Forcing NLS...\n\n' fi else printf 'gencat works.\n\n' # It turns out that POSIX locales are really terrible, and running # gencat on one machine is not guaranteed to make those cat files # portable to another machine, so we had better warn the user here. if [ "$HOSTCC" != "$CC" ] || [ "$OLDHOSTCFLAGS" != "$OLDCFLAGS" ]; then printf 'Cross-compile detected.\n\n' printf 'WARNING: Catalog files generated with gencat may not be portable\n' printf ' across different architectures.\n\n' fi if [ -z "$NLSPATH" ]; then NLSPATH="/usr/share/locale/%L/%N" fi install_locales_prereqs=" install_locales" uninstall_locales_prereqs=" uninstall_locales" fi fi set -e else install_locales_prereqs="" uninstall_locales_prereqs="" all_locales=0 fi if [ "$nls" -ne 0 ] && [ "$all_locales" -ne 0 ]; then install_locales="\$(LOCALE_INSTALL) -l \$(NLSPATH) \$(MAIN_EXEC) \$(DESTDIR)" else install_locales="\$(LOCALE_INSTALL) \$(NLSPATH) \$(MAIN_EXEC) \$(DESTDIR)" fi # Like the above tested locale support, this tests history. if [ "$hist" -eq 1 ]; then if [ "$hist_impl" = "editline" ]; then editline=1 readline=0 elif [ "$hist_impl" = "readline" ]; then editline=0 readline=1 else editline=0 readline=0 fi set +e printf 'Testing history...\n' flags="-DBC_ENABLE_HISTORY=1 -DBC_ENABLED=$bc -DDC_ENABLED=$dc" flags="$flags -DBC_ENABLE_NLS=$nls -DBC_ENABLE_LIBRARY=0 -DBC_ENABLE_AFL=0" flags="$flags -DBC_ENABLE_EDITLINE=$editline -DBC_ENABLE_READLINE=$readline" flags="$flags -DBC_ENABLE_EXTRA_MATH=$extra_math -I$scriptdir/include/" flags="$flags -D_POSIX_C_SOURCE=200809L -D_XOPEN_SOURCE=700" "$CC" $CPPFLAGS $CFLAGS $flags -c "$scriptdir/src/history.c" -o "./history.o" > /dev/null 2>&1 err="$?" rm -rf "./history.o" # If this errors, it is probably because of building on Windows, # and history is not supported on Windows, so disable it. if [ "$err" -ne 0 ]; then printf 'History does not work.\n' if [ $force -eq 0 ]; then printf 'Disabling history...\n\n' hist=0 else printf 'Forcing history...\n\n' fi else printf 'History works.\n\n' fi set -e else editline=0 readline=0 fi # We have to disable the history tests if it is disabled or valgrind is on. Or # if we are using editline or readline. if [ "$hist" -eq 0 ] || [ "$vg" -ne 0 ]; then test_bc_history_prereqs=" test_bc_history_skip" test_dc_history_prereqs=" test_dc_history_skip" history_tests="@printf 'Skipping history tests...\\\\n'" CFLAGS="$CFLAGS -DBC_ENABLE_EDITLINE=0 -DBC_ENABLE_READLINE=0" else if [ "$editline" -eq 0 ] && [ "$readline" -eq 0 ]; then history_tests="@printf '\$(TEST_STARS)\\\\n\\\\nRunning history tests...\\\\n\\\\n'" history_tests="$history_tests \&\& \$(TESTSDIR)/history.sh bc -a \&\&" history_tests="$history_tests \$(TESTSDIR)/history.sh dc -a \&\& printf" history_tests="$history_tests '\\\\nAll history tests passed.\\\\n\\\\n\$(TEST_STARS)\\\\n'" else test_bc_history_prereqs=" test_bc_history_skip" test_dc_history_prereqs=" test_dc_history_skip" history_tests="@printf 'Skipping history tests...\\\\n'" fi # We are also setting the CFLAGS and LDFLAGS here. if [ "$editline" -ne 0 ]; then LDFLAGS="$LDFLAGS -ledit" CFLAGS="$CFLAGS -DBC_ENABLE_EDITLINE=1 -DBC_ENABLE_READLINE=0" elif [ "$readline" -ne 0 ]; then LDFLAGS="$LDFLAGS -lreadline" CFLAGS="$CFLAGS -DBC_ENABLE_EDITLINE=0 -DBC_ENABLE_READLINE=1" else CFLAGS="$CFLAGS -DBC_ENABLE_EDITLINE=0 -DBC_ENABLE_READLINE=0" fi fi # Test FreeBSD. This is not in an if statement because regardless of whatever # the user says, we need to know if we are on FreeBSD. If we are, we cannot set # _POSIX_C_SOURCE and _XOPEN_SOURCE. The FreeBSD headers turn *off* stuff when # that is done. set +e printf 'Testing for FreeBSD...\n' flags="-DBC_TEST_FREEBSD -DBC_ENABLE_AFL=0" "$CC" $CPPFLAGS $CFLAGS $flags "-I$scriptdir/include" -E "$scriptdir/src/vm.c" > /dev/null 2>&1 err="$?" if [ "$err" -ne 0 ]; then printf 'On FreeBSD. Not using _POSIX_C_SOURCE and _XOPEN_SOURCE.\n\n' else printf 'Not on FreeBSD. Using _POSIX_C_SOURCE and _XOPEN_SOURCE.\n\n' CPPFLAGS="$CPPFLAGS -D_POSIX_C_SOURCE=200809L -D_XOPEN_SOURCE=700" fi # Test OpenBSD. This is not in an if statement because regardless of whatever # the user says, we need to know if we are on OpenBSD to activate _BSD_SOURCE. # No, I cannot `#define _BSD_SOURCE` in a header because OpenBSD's patched GCC # and Clang complain that that is only allowed for system headers. Sigh....So we # have to check at configure time and set it on the compiler command-line. And # we have to set it because we also set _POSIX_C_SOURCE, which OpenBSD headers # detect, and when they detect it, they turn off _BSD_SOURCE unless it is # specifically requested. set +e printf 'Testing for OpenBSD...\n' flags="-DBC_TEST_OPENBSD -DBC_ENABLE_AFL=0" "$CC" $CPPFLAGS $CFLAGS $flags "-I$scriptdir/include" -E "$scriptdir/src/vm.c" > /dev/null 2>&1 err="$?" if [ "$err" -ne 0 ]; then printf 'On OpenBSD. Using _BSD_SOURCE.\n\n' bsd="-D_BSD_SOURCE" # Readline errors on OpenBSD, for some weird reason. if [ "$readline" -ne 0 ]; then usage "Cannot use readline on OpenBSD" fi else printf 'Not on OpenBSD.\n\n' bsd="" fi if [ "$library" -eq 1 ]; then bc_lib="" fi if [ "$extra_math" -eq 1 ] && [ "$bc" -ne 0 ] && [ "$library" -eq 0 ]; then BC_LIB2_O="\$(GEN_DIR)/lib2.o" else BC_LIB2_O="" fi GEN_DIR="$scriptdir/gen" # These lines set the appropriate targets based on whether `gen/strgen.c` or # `gen/strgen.sh` is used. GEN="strgen" GEN_EXEC_TARGET="\$(HOSTCC) -DBC_ENABLE_AFL=0 -I$scriptdir/include/ \$(HOSTCFLAGS) -o \$(GEN_EXEC) \$(GEN_C)" CLEAN_PREREQS=" clean_gen clean_coverage" if [ -z "${GEN_HOST+set}" ]; then GEN_HOST=1 else if [ "$GEN_HOST" -eq 0 ]; then GEN="strgen.sh" GEN_EXEC_TARGET="@printf 'Do not need to build gen/strgen.c\\\\n'" CLEAN_PREREQS=" clean_coverage" fi fi manpage_args="" unneeded="" headers="\$(HEADERS)" # This series of if statements figure out what source files are *not* needed. if [ "$extra_math" -eq 0 ]; then exclude_extra_math=1 manpage_args="E" unneeded="$unneeded rand.c" else exclude_extra_math=0 headers="$headers \$(EXTRA_MATH_HEADERS)" fi # All of these next if statements set the build type and mark certain source # files as unneeded so that they won't have targets generated for them. if [ "$hist" -eq 0 ]; then manpage_args="${manpage_args}H" unneeded="$unneeded history.c" else headers="$headers \$(HISTORY_HEADERS)" fi if [ "$nls" -eq 0 ]; then manpage_args="${manpage_args}N" fi if [ "$bc" -eq 0 ]; then unneeded="$unneeded bc.c bc_lex.c bc_parse.c" else headers="$headers \$(BC_HEADERS)" fi if [ "$dc" -eq 0 ]; then unneeded="$unneeded dc.c dc_lex.c dc_parse.c" else headers="$headers \$(DC_HEADERS)" fi # This convoluted mess does pull the version out. If you change the format of # include/version.h, you may have to change this line. version=$(cat "$scriptdir/include/version.h" | grep "VERSION " - | awk '{ print $3 }' -) if [ "$library" -ne 0 ]; then unneeded="$unneeded args.c opt.c read.c file.c main.c" unneeded="$unneeded lang.c lex.c parse.c program.c" unneeded="$unneeded bc.c bc_lex.c bc_parse.c" unneeded="$unneeded dc.c dc_lex.c dc_parse.c" headers="$headers \$(LIBRARY_HEADERS)" if [ "$PC_PATH" != "" ]; then contents=$(cat "$scriptdir/bcl.pc.in") contents=$(replace "$contents" "INCLUDEDIR" "$INCLUDEDIR") contents=$(replace "$contents" "LIBDIR" "$LIBDIR") contents=$(replace "$contents" "VERSION" "$version") - printf '%s\n' "$contents" > "./bcl.pc" + printf '%s\n' "$contents" > "$scriptdir/bcl.pc" pkg_config_install="\$(SAFE_INSTALL) \$(PC_INSTALL_ARGS) \"\$(BCL_PC)\" \"\$(DESTDIR)\$(PC_PATH)/\$(BCL_PC)\"" pkg_config_uninstall="\$(RM) -f \"\$(DESTDIR)\$(PC_PATH)/\$(BCL_PC)\"" else pkg_config_install="" pkg_config_uninstall="" fi else unneeded="$unneeded library.c" PC_PATH="" pkg_config_install="" pkg_config_uninstall="" fi # library.c is not needed under normal circumstances. if [ "$unneeded" = "" ]; then unneeded="library.c" fi # This sets the appropriate manpage for a full build. if [ "$manpage_args" = "" ]; then manpage_args="A" fi if [ "$vg" -ne 0 ]; then memcheck=1 fi if [ "$bc_default_prompt" = "" ]; then bc_default_prompt="$bc_default_tty_mode" fi if [ "$dc_default_prompt" = "" ]; then dc_default_prompt="$dc_default_tty_mode" fi # Generate the test targets and prerequisites. bc_tests=$(gen_std_test_targets bc) bc_script_tests=$(gen_script_test_targets bc) bc_err_tests=$(gen_err_test_targets bc) dc_tests=$(gen_std_test_targets dc) dc_script_tests=$(gen_script_test_targets dc) dc_err_tests=$(gen_err_test_targets dc) # Print out the values; this is for debugging. printf 'Version: %s\n' "$version" if [ "$bc" -ne 0 ]; then printf 'Building bc\n' else printf 'Not building bc\n' fi if [ "$dc" -ne 0 ]; then printf 'Building dc\n' else printf 'Not building dc\n' fi printf '\n' printf 'BC_ENABLE_LIBRARY=%s\n\n' "$library" printf 'BC_ENABLE_HISTORY=%s\n' "$hist" printf 'BC_ENABLE_EXTRA_MATH=%s\n' "$extra_math" printf 'BC_ENABLE_NLS=%s\n\n' "$nls" printf 'BC_ENABLE_AFL=%s\n' "$fuzz" printf '\n' printf 'BC_NUM_KARATSUBA_LEN=%s\n' "$karatsuba_len" printf '\n' printf 'CC=%s\n' "$CC" printf 'CFLAGS=%s\n' "$CFLAGS" printf 'HOSTCC=%s\n' "$HOSTCC" printf 'HOSTCFLAGS=%s\n' "$HOSTCFLAGS" printf 'CPPFLAGS=%s\n' "$CPPFLAGS" printf 'LDFLAGS=%s\n' "$LDFLAGS" printf 'PREFIX=%s\n' "$PREFIX" printf 'BINDIR=%s\n' "$BINDIR" printf 'INCLUDEDIR=%s\n' "$INCLUDEDIR" printf 'LIBDIR=%s\n' "$LIBDIR" printf 'DATAROOTDIR=%s\n' "$DATAROOTDIR" printf 'DATADIR=%s\n' "$DATADIR" printf 'MANDIR=%s\n' "$MANDIR" printf 'MAN1DIR=%s\n' "$MAN1DIR" printf 'MAN3DIR=%s\n' "$MAN3DIR" printf 'NLSPATH=%s\n' "$NLSPATH" printf 'PC_PATH=%s\n' "$PC_PATH" printf 'EXECSUFFIX=%s\n' "$EXECSUFFIX" printf 'EXECPREFIX=%s\n' "$EXECPREFIX" printf 'DESTDIR=%s\n' "$DESTDIR" printf 'LONG_BIT=%s\n' "$LONG_BIT" printf 'GEN_HOST=%s\n' "$GEN_HOST" printf 'GEN_EMU=%s\n' "$GEN_EMU" printf '\n' printf 'Setting Defaults\n' printf '================\n' printf 'bc.banner=%s\n' "$bc_default_banner" printf 'bc.sigint_reset=%s\n' "$bc_default_sigint_reset" printf 'dc.sigint_reset=%s\n' "$dc_default_sigint_reset" printf 'bc.tty_mode=%s\n' "$bc_default_tty_mode" printf 'dc.tty_mode=%s\n' "$dc_default_tty_mode" printf 'bc.prompt=%s\n' "$bc_default_prompt" printf 'dc.prompt=%s\n' "$dc_default_prompt" printf 'bc.expr_exit=%s\n' "$bc_default_expr_exit" printf 'dc.expr_exit=%s\n' "$dc_default_expr_exit" printf 'bc.digit_clamp=%s\n' "$bc_default_digit_clamp" printf 'dc.digit_clamp=%s\n' "$dc_default_digit_clamp" # This code outputs a warning. The warning is to not surprise users when locales # are installed outside of the prefix. This warning is suppressed when the # default prefix is used, as well, so as not to panic users just installing by # hand. I believe this will be okay because NLSPATH is usually in /usr and the # default prefix is /usr/local, so they'll be close that way. if [ "$nls" -ne 0 ] && [ "${NLSPATH#$PREFIX}" = "${NLSPATH}" ] && [ "$defprefix" -eq 0 ]; then printf '\n********************************************************************************\n\n' printf 'WARNING: Locales will *NOT* be installed in $PREFIX (%s).\n' "$PREFIX" printf '\n' printf ' This is because they *MUST* be installed at a fixed location to even\n' printf ' work, and that fixed location is $NLSPATH (%s).\n' "$NLSPATH" printf '\n' printf ' This location is *outside* of $PREFIX. If you do not wish to install\n' printf ' locales outside of $PREFIX, you must disable NLS with the -N or the\n' printf ' --disable-nls options.\n' printf '\n' printf ' The author apologizes for the inconvenience, but the need to install\n' printf ' the locales at a fixed location is mandated by POSIX, and it is not\n' printf ' possible for the author to change that requirement.\n' printf '\n********************************************************************************\n' fi # This is where the real work begins. This is the point at which the Makefile.in # template is edited and output to the Makefile. contents=$(cat "$scriptdir/Makefile.in") needle="WARNING" replacement='*** WARNING: Autogenerated from Makefile.in. DO NOT MODIFY ***' contents=$(replace "$contents" "$needle" "$replacement") # The contents are edited to have the list of files to build. contents=$(gen_file_list "$contents" $unneeded) SRC_TARGETS="" # This line and loop generates the individual targets for source files. I used # to just use an implicit target, but that was found to be inadequate when I # added the library. src_files=$(find_src_files $unneeded) for f in $src_files; do o=$(replace_ext "$f" "c" "o") o=$(basename "$o") SRC_TARGETS=$(printf '%s\n\nsrc/%s: src %s %s\n\t$(CC) $(CFLAGS) -o src/%s -c %s\n' \ "$SRC_TARGETS" "$o" "$headers" "$f" "$o" "$f") done # Replace all the placeholders. contents=$(replace "$contents" "ROOTDIR" "$scriptdir") contents=$(replace "$contents" "BUILDDIR" "$builddir") contents=$(replace "$contents" "HEADERS" "$headers") contents=$(replace "$contents" "BC_ENABLED" "$bc") contents=$(replace "$contents" "DC_ENABLED" "$dc") contents=$(replace "$contents" "BC_ALL_TESTS" "$bc_test") contents=$(replace "$contents" "BC_ALL_TESTS_NP" "$bc_test_np") contents=$(replace "$contents" "BC_TESTS" "$bc_tests") contents=$(replace "$contents" "BC_SCRIPT_TESTS" "$bc_script_tests") contents=$(replace "$contents" "BC_ERROR_TESTS" "$bc_err_tests") contents=$(replace "$contents" "BC_TEST_EXEC" "$bc_test_exec") contents=$(replace "$contents" "TIMECONST_ALL_TESTS" "$timeconst") contents=$(replace "$contents" "DC_ALL_TESTS" "$dc_test") contents=$(replace "$contents" "DC_ALL_TESTS_NP" "$dc_test_np") contents=$(replace "$contents" "DC_TESTS" "$dc_tests") contents=$(replace "$contents" "DC_SCRIPT_TESTS" "$dc_script_tests") contents=$(replace "$contents" "DC_ERROR_TESTS" "$dc_err_tests") contents=$(replace "$contents" "DC_TEST_EXEC" "$dc_test_exec") contents=$(replace "$contents" "BCL_TEST_EXEC" "$bcl_test_exec") contents=$(replace "$contents" "BUILD_TYPE" "$manpage_args") contents=$(replace "$contents" "EXCLUDE_EXTRA_MATH" "$exclude_extra_math") contents=$(replace "$contents" "LIBRARY" "$library") contents=$(replace "$contents" "HISTORY" "$hist") contents=$(replace "$contents" "EXTRA_MATH" "$extra_math") contents=$(replace "$contents" "NLS" "$nls") contents=$(replace "$contents" "FUZZ" "$fuzz") contents=$(replace "$contents" "MEMCHECK" "$memcheck") contents=$(replace "$contents" "BC_LIB_O" "$bc_lib") contents=$(replace "$contents" "BC_HELP_O" "$bc_help") contents=$(replace "$contents" "DC_HELP_O" "$dc_help") contents=$(replace "$contents" "BC_LIB2_O" "$BC_LIB2_O") contents=$(replace "$contents" "KARATSUBA_LEN" "$karatsuba_len") contents=$(replace "$contents" "NLSPATH" "$NLSPATH") contents=$(replace "$contents" "DESTDIR" "$destdir") contents=$(replace "$contents" "EXECSUFFIX" "$EXECSUFFIX") contents=$(replace "$contents" "EXECPREFIX" "$EXECPREFIX") contents=$(replace "$contents" "BINDIR" "$BINDIR") contents=$(replace "$contents" "INCLUDEDIR" "$INCLUDEDIR") contents=$(replace "$contents" "LIBDIR" "$LIBDIR") contents=$(replace "$contents" "MAN1DIR" "$MAN1DIR") contents=$(replace "$contents" "MAN3DIR" "$MAN3DIR") contents=$(replace "$contents" "CFLAGS" "$CFLAGS") contents=$(replace "$contents" "HOSTCFLAGS" "$HOSTCFLAGS") contents=$(replace "$contents" "CPPFLAGS" "$CPPFLAGS") contents=$(replace "$contents" "LDFLAGS" "$LDFLAGS") contents=$(replace "$contents" "CC" "$CC") contents=$(replace "$contents" "HOSTCC" "$HOSTCC") contents=$(replace "$contents" "COVERAGE_OUTPUT" "$COVERAGE_OUTPUT") contents=$(replace "$contents" "COVERAGE_PREREQS" "$COVERAGE_PREREQS") contents=$(replace "$contents" "INSTALL_PREREQS" "$install_prereqs") contents=$(replace "$contents" "INSTALL_MAN_PREREQS" "$install_man_prereqs") contents=$(replace "$contents" "INSTALL_LOCALES" "$install_locales") contents=$(replace "$contents" "INSTALL_LOCALES_PREREQS" "$install_locales_prereqs") contents=$(replace "$contents" "UNINSTALL_MAN_PREREQS" "$uninstall_man_prereqs") contents=$(replace "$contents" "UNINSTALL_PREREQS" "$uninstall_prereqs") contents=$(replace "$contents" "UNINSTALL_LOCALES_PREREQS" "$uninstall_locales_prereqs") contents=$(replace "$contents" "PC_PATH" "$PC_PATH") contents=$(replace "$contents" "PKG_CONFIG_INSTALL" "$pkg_config_install") contents=$(replace "$contents" "PKG_CONFIG_UNINSTALL" "$pkg_config_uninstall") contents=$(replace "$contents" "DEFAULT_TARGET" "$default_target") contents=$(replace "$contents" "DEFAULT_TARGET_PREREQS" "$default_target_prereqs") contents=$(replace "$contents" "DEFAULT_TARGET_CMD" "$default_target_cmd") contents=$(replace "$contents" "SECOND_TARGET" "$second_target") contents=$(replace "$contents" "SECOND_TARGET_PREREQS" "$second_target_prereqs") contents=$(replace "$contents" "SECOND_TARGET_CMD" "$second_target_cmd") contents=$(replace "$contents" "ALL_PREREQ" "$ALL_PREREQ") contents=$(replace "$contents" "BC_EXEC_PREREQ" "$bc_exec_prereq") contents=$(replace "$contents" "BC_EXEC_CMD" "$bc_exec_cmd") contents=$(replace "$contents" "DC_EXEC_PREREQ" "$dc_exec_prereq") contents=$(replace "$contents" "DC_EXEC_CMD" "$dc_exec_cmd") contents=$(replace "$contents" "EXECUTABLES" "$executables") contents=$(replace "$contents" "MAIN_EXEC" "$main_exec") contents=$(replace "$contents" "EXEC" "$executable") contents=$(replace "$contents" "TESTS" "$tests") contents=$(replace "$contents" "BC_HISTORY_TEST_PREREQS" "$test_bc_history_prereqs") contents=$(replace "$contents" "DC_HISTORY_TEST_PREREQS" "$test_dc_history_prereqs") contents=$(replace "$contents" "HISTORY_TESTS" "$history_tests") contents=$(replace "$contents" "VG_BC_TEST" "$vg_bc_test") contents=$(replace "$contents" "VG_DC_TEST" "$vg_dc_test") contents=$(replace "$contents" "TIMECONST" "$timeconst") contents=$(replace "$contents" "KARATSUBA" "$karatsuba") contents=$(replace "$contents" "KARATSUBA_TEST" "$karatsuba_test") contents=$(replace "$contents" "LONG_BIT_DEFINE" "$LONG_BIT_DEFINE") contents=$(replace "$contents" "GEN_DIR" "$GEN_DIR") contents=$(replace "$contents" "GEN" "$GEN") contents=$(replace "$contents" "GEN_EXEC_TARGET" "$GEN_EXEC_TARGET") contents=$(replace "$contents" "CLEAN_PREREQS" "$CLEAN_PREREQS") contents=$(replace "$contents" "GEN_EMU" "$GEN_EMU") contents=$(replace "$contents" "BSD" "$bsd") contents=$(replace "$contents" "BC_DEFAULT_BANNER" "$bc_default_banner") contents=$(replace "$contents" "BC_DEFAULT_SIGINT_RESET" "$bc_default_sigint_reset") contents=$(replace "$contents" "DC_DEFAULT_SIGINT_RESET" "$dc_default_sigint_reset") contents=$(replace "$contents" "BC_DEFAULT_TTY_MODE" "$bc_default_tty_mode") contents=$(replace "$contents" "DC_DEFAULT_TTY_MODE" "$dc_default_tty_mode") contents=$(replace "$contents" "BC_DEFAULT_PROMPT" "$bc_default_prompt") contents=$(replace "$contents" "DC_DEFAULT_PROMPT" "$dc_default_prompt") contents=$(replace "$contents" "BC_DEFAULT_EXPR_EXIT" "$bc_default_expr_exit") contents=$(replace "$contents" "DC_DEFAULT_EXPR_EXIT" "$dc_default_expr_exit") contents=$(replace "$contents" "BC_DEFAULT_DIGIT_CLAMP" "$bc_default_digit_clamp") contents=$(replace "$contents" "DC_DEFAULT_DIGIT_CLAMP" "$dc_default_digit_clamp") # Do the first print to the Makefile. printf '%s\n%s\n\n' "$contents" "$SRC_TARGETS" > "Makefile" # Generate the individual test targets. if [ "$bc" -ne 0 ]; then gen_std_tests bc "$extra_math" "$time_tests" $bc_test_exec gen_script_tests bc "$extra_math" "$generate_tests" "$time_tests" $bc_test_exec gen_err_tests bc $bc_test_exec fi if [ "$dc" -ne 0 ]; then gen_std_tests dc "$extra_math" "$time_tests" $dc_test_exec gen_script_tests dc "$extra_math" "$generate_tests" "$time_tests" $dc_test_exec gen_err_tests dc $dc_test_exec fi # Copy the correct manuals to the expected places. mkdir -p manuals cp -f "$scriptdir/manuals/bc/$manpage_args.1.md" manuals/bc.1.md cp -f "$scriptdir/manuals/bc/$manpage_args.1" manuals/bc.1 cp -f "$scriptdir/manuals/dc/$manpage_args.1.md" manuals/dc.1.md cp -f "$scriptdir/manuals/dc/$manpage_args.1" manuals/dc.1 make clean > /dev/null diff --git a/contrib/bc/include/bcl.h b/contrib/bc/include/bcl.h index 253138231c66..0908e215182c 100644 --- a/contrib/bc/include/bcl.h +++ b/contrib/bc/include/bcl.h @@ -1,321 +1,372 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2023 Gavin D. Howard and contributors. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * ***************************************************************************** * * The public header for the bc library. * */ #ifndef BC_BCL_H #define BC_BCL_H +// TODO: Add a generation index when building with Valgrind to check for +// use-after-free's or double frees. + #include #include #include #include #ifndef NDEBUG #define BC_DEBUG (1) #else // NDEBUG #define BC_DEBUG (0) #endif // NDEBUG #ifdef _WIN32 #include #include #include #include #endif // _WIN32 #ifdef _WIN32 #define ssize_t SSIZE_T #endif // _WIN32 #define BCL_SEED_ULONGS (4) #define BCL_SEED_SIZE (sizeof(long) * BCL_SEED_ULONGS) // For some reason, LONG_BIT is not defined in some versions of gcc. // I define it here to the minimum accepted value in the POSIX standard. #ifndef LONG_BIT #define LONG_BIT (32) #endif // LONG_BIT #ifndef BC_LONG_BIT #define BC_LONG_BIT LONG_BIT #endif // BC_LONG_BIT #if BC_LONG_BIT > LONG_BIT #error BC_LONG_BIT cannot be greater than LONG_BIT #endif // BC_LONG_BIT > LONG_BIT // For more information about the items here, see the either the // manuals/bcl.3.md or manuals/bcl.3 manuals. // BclBigDig is a fixed-size integer type that bcl can convert numbers to. // // BclRandInt is the type of fixed-size integer natively returned by the // pseudo-random number generator. #if BC_LONG_BIT >= 64 typedef uint64_t BclBigDig; typedef uint64_t BclRandInt; #elif BC_LONG_BIT >= 32 typedef uint32_t BclBigDig; typedef uint32_t BclRandInt; #else #error BC_LONG_BIT must be at least 32 #endif // BC_LONG_BIT >= 64 #ifndef BC_ENABLE_LIBRARY #define BC_ENABLE_LIBRARY (1) #endif // BC_ENABLE_LIBRARY #if BC_ENABLE_LIBRARY typedef enum BclError { BCL_ERROR_NONE, BCL_ERROR_INVALID_NUM, BCL_ERROR_INVALID_CONTEXT, BCL_ERROR_SIGNAL, BCL_ERROR_MATH_NEGATIVE, BCL_ERROR_MATH_NON_INTEGER, BCL_ERROR_MATH_OVERFLOW, BCL_ERROR_MATH_DIVIDE_BY_ZERO, BCL_ERROR_PARSE_INVALID_STR, BCL_ERROR_FATAL_ALLOC_ERR, BCL_ERROR_FATAL_UNKNOWN_ERR, BCL_ERROR_NELEMS, } BclError; typedef struct BclNumber { size_t i; } BclNumber; struct BclCtxt; typedef struct BclCtxt* BclContext; BclError bcl_start(void); void bcl_end(void); BclError bcl_init(void); void bcl_free(void); bool bcl_abortOnFatalError(void); void bcl_setAbortOnFatalError(bool abrt); bool bcl_leadingZeroes(void); void bcl_setLeadingZeroes(bool leadingZeroes); bool bcl_digitClamp(void); void bcl_setDigitClamp(bool digitClamp); void bcl_gc(void); BclError bcl_pushContext(BclContext ctxt); void bcl_popContext(void); BclContext bcl_context(void); BclContext bcl_ctxt_create(void); void bcl_ctxt_free(BclContext ctxt); void bcl_ctxt_freeNums(BclContext ctxt); size_t bcl_ctxt_scale(BclContext ctxt); void bcl_ctxt_setScale(BclContext ctxt, size_t scale); size_t bcl_ctxt_ibase(BclContext ctxt); void bcl_ctxt_setIbase(BclContext ctxt, size_t ibase); size_t bcl_ctxt_obase(BclContext ctxt); void bcl_ctxt_setObase(BclContext ctxt, size_t obase); BclError bcl_err(BclNumber n); BclNumber bcl_num_create(void); void bcl_num_free(BclNumber n); bool bcl_num_neg(BclNumber n); void bcl_num_setNeg(BclNumber n, bool neg); size_t bcl_num_scale(BclNumber n); BclError bcl_num_setScale(BclNumber n, size_t scale); size_t bcl_num_len(BclNumber n); BclError bcl_copy(BclNumber d, BclNumber s); BclNumber bcl_dup(BclNumber s); BclError bcl_bigdig(BclNumber n, BclBigDig* result); +BclError +bcl_bigdig_keep(BclNumber n, BclBigDig* result); + BclNumber bcl_bigdig2num(BclBigDig val); BclNumber bcl_add(BclNumber a, BclNumber b); +BclNumber +bcl_add_keep(BclNumber a, BclNumber b); + BclNumber bcl_sub(BclNumber a, BclNumber b); +BclNumber +bcl_sub_keep(BclNumber a, BclNumber b); + BclNumber bcl_mul(BclNumber a, BclNumber b); +BclNumber +bcl_mul_keep(BclNumber a, BclNumber b); + BclNumber bcl_div(BclNumber a, BclNumber b); +BclNumber +bcl_div_keep(BclNumber a, BclNumber b); + BclNumber bcl_mod(BclNumber a, BclNumber b); +BclNumber +bcl_mod_keep(BclNumber a, BclNumber b); + BclNumber bcl_pow(BclNumber a, BclNumber b); +BclNumber +bcl_pow_keep(BclNumber a, BclNumber b); + BclNumber bcl_lshift(BclNumber a, BclNumber b); +BclNumber +bcl_lshift_keep(BclNumber a, BclNumber b); + BclNumber bcl_rshift(BclNumber a, BclNumber b); +BclNumber +bcl_rshift_keep(BclNumber a, BclNumber b); + BclNumber bcl_sqrt(BclNumber a); +BclNumber +bcl_sqrt_keep(BclNumber a); + BclError bcl_divmod(BclNumber a, BclNumber b, BclNumber* c, BclNumber* d); +BclError +bcl_divmod_keep(BclNumber a, BclNumber b, BclNumber* c, BclNumber* d); + BclNumber bcl_modexp(BclNumber a, BclNumber b, BclNumber c); +BclNumber +bcl_modexp_keep(BclNumber a, BclNumber b, BclNumber c); + ssize_t bcl_cmp(BclNumber a, BclNumber b); void bcl_zero(BclNumber n); void bcl_one(BclNumber n); BclNumber bcl_parse(const char* restrict val); char* bcl_string(BclNumber n); +char* +bcl_string_keep(BclNumber n); + BclNumber bcl_irand(BclNumber a); +BclNumber +bcl_irand_keep(BclNumber a); + BclNumber bcl_frand(size_t places); BclNumber bcl_ifrand(BclNumber a, size_t places); +BclNumber +bcl_ifrand_keep(BclNumber a, size_t places); + BclError bcl_rand_seedWithNum(BclNumber n); +BclError +bcl_rand_seedWithNum_keep(BclNumber n); + BclError bcl_rand_seed(unsigned char seed[BCL_SEED_SIZE]); void bcl_rand_reseed(void); BclNumber bcl_rand_seed2num(void); BclRandInt bcl_rand_int(void); BclRandInt bcl_rand_bounded(BclRandInt bound); #endif // BC_ENABLE_LIBRARY #endif // BC_BCL_H diff --git a/contrib/bc/include/library.h b/contrib/bc/include/library.h index 76df91392da1..1edd3757444c 100644 --- a/contrib/bc/include/library.h +++ b/contrib/bc/include/library.h @@ -1,249 +1,399 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2023 Gavin D. Howard and contributors. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * ***************************************************************************** * * The private header for the bc library. * */ #ifndef LIBBC_PRIVATE_H #define LIBBC_PRIVATE_H #ifndef _WIN32 #include #endif // _WIN32 #include #include #include +#if BC_ENABLE_MEMCHECK + +/** + * A typedef for Valgrind builds. This is to add a generation index for error + * checking. + */ +typedef struct BclNum +{ + /// The number. + BcNum n; + + /// The generation index. + size_t gen_idx; + +} BclNum; + +/** + * Clears the generation byte in a BclNumber and returns the value. + * @param n The BclNumber. + * @return The value of the index. + */ +#define BCL_NO_GEN(n) \ + ((n).i & ~(((size_t) UCHAR_MAX) << ((sizeof(size_t) - 1) * CHAR_BIT))) + +/** + * Gets the generation index in a BclNumber. + * @param n The BclNumber. + * @return The generation index. + */ +#define BCL_GET_GEN(n) ((n).i >> ((sizeof(size_t) - 1) * CHAR_BIT)) + +/** + * Turns a BclNumber into a BcNum. + * @param c The context. + * @param n The BclNumber. + */ +#define BCL_NUM(c, n) ((BclNum*) bc_vec_item(&(c)->nums, BCL_NO_GEN(n))) + +/** + * Clears the generation index top byte in the BclNumber. + * @param n The BclNumber. + */ +#define BCL_CLEAR_GEN(n) \ + do \ + { \ + (n).i &= ~(((size_t) UCHAR_MAX) << ((sizeof(size_t) - 1) * CHAR_BIT)); \ + } \ + while (0) + +#define BCL_CHECK_NUM_GEN(c, bn) \ + do \ + { \ + size_t gen_ = BCL_GET_GEN(bn); \ + BclNum* ptr_ = BCL_NUM(c, bn); \ + if (BCL_NUM_ARRAY(ptr_) == NULL) \ + { \ + bcl_nonexistentNum(); \ + } \ + if (gen_ != ptr_->gen_idx) \ + { \ + bcl_invalidGeneration(); \ + } \ + } \ + while (0) + +#define BCL_CHECK_NUM_VALID(c, bn) \ + do \ + { \ + size_t idx_ = BCL_NO_GEN(bn); \ + if ((c)->nums.len <= idx_) \ + { \ + bcl_numIdxOutOfRange(); \ + } \ + BCL_CHECK_NUM_GEN(c, bn); \ + } \ + while (0) + +/** + * Returns the limb array of the number. + * @param bn The number. + * @return The limb array. + */ +#define BCL_NUM_ARRAY(bn) ((bn)->n.num) + +/** + * Returns the limb array of the number for a non-pointer. + * @param bn The number. + * @return The limb array. + */ +#define BCL_NUM_ARRAY_NP(bn) ((bn).n.num) + +/** + * Returns the BcNum pointer. + * @param bn The number. + * @return The BcNum pointer. + */ +#define BCL_NUM_NUM(bn) (&(bn)->n) + +/** + * Returns the BcNum pointer for a non-pointer. + * @param bn The number. + * @return The BcNum pointer. + */ +#define BCL_NUM_NUM_NP(bn) (&(bn).n) + +// These functions only abort. They exist to give developers some idea of what +// went wrong when bugs are found, if they look at the Valgrind stack trace. + +BC_NORETURN void +bcl_invalidGeneration(void); + +BC_NORETURN void +bcl_nonexistentNum(void); + +BC_NORETURN void +bcl_numIdxOutOfRange(void); + +#else // BC_ENABLE_MEMCHECK + +/** + * A typedef for non-Valgrind builds. + */ +typedef BcNum BclNum; + +#define BCL_NO_GEN(n) ((n).i) +#define BCL_NUM(c, n) ((BclNum*) bc_vec_item(&(c)->nums, (n).i)) +#define BCL_CLEAR_GEN(n) ((void) (n)) + +#define BCL_CHECK_NUM_GEN(c, bn) +#define BCL_CHECK_NUM_VALID(c, n) + +#define BCL_NUM_ARRAY(bn) ((bn)->num) +#define BCL_NUM_ARRAY_NP(bn) ((bn).num) + +#define BCL_NUM_NUM(bn) (bn) +#define BCL_NUM_NUM_NP(bn) (&(bn)) + +#endif // BC_ENABLE_MEMCHECK + /** * A header that sets a jump. * @param vm The thread data. * @param l The label to jump to on error. */ #define BC_FUNC_HEADER(vm, l) \ do \ { \ BC_SETJMP(vm, l); \ vm->err = BCL_ERROR_NONE; \ } \ while (0) /** * A footer for functions that do not return an error code. */ #define BC_FUNC_FOOTER_NO_ERR(vm) \ do \ { \ BC_UNSETJMP(vm); \ } \ while (0) /** * A footer for functions that *do* return an error code. * @param vm The thread data. * @param e The error variable to set. */ #define BC_FUNC_FOOTER(vm, e) \ do \ { \ e = vm->err; \ BC_FUNC_FOOTER_NO_ERR(vm); \ } \ while (0) /** * A footer that sets up n based the value of e and sets up the return value in * idx. * @param c The context. * @param e The error. - * @param n The number. + * @param bn The number. * @param idx The idx to set as the return value. */ -#define BC_MAYBE_SETUP(c, e, n, idx) \ - do \ - { \ - if (BC_ERR((e) != BCL_ERROR_NONE)) \ - { \ - if ((n).num != NULL) bc_num_free(&(n)); \ - idx.i = 0 - (size_t) (e); \ - } \ - else idx = bcl_num_insert(c, &(n)); \ - } \ +#define BC_MAYBE_SETUP(c, e, bn, idx) \ + do \ + { \ + if (BC_ERR((e) != BCL_ERROR_NONE)) \ + { \ + if (BCL_NUM_ARRAY_NP(bn) != NULL) bc_num_free(BCL_NUM_NUM_NP(bn)); \ + idx.i = 0 - (size_t) (e); \ + } \ + else idx = bcl_num_insert(c, &(bn)); \ + } \ while (0) /** * A header to check the context and return an error encoded in a number if it * is bad. * @param c The context. */ -#define BC_CHECK_CTXT(vm, c) \ - do \ - { \ - c = bcl_contextHelper(vm); \ - if (BC_ERR(c == NULL)) \ - { \ - BclNumber n_num; \ - n_num.i = 0 - (size_t) BCL_ERROR_INVALID_CONTEXT; \ - return n_num; \ - } \ - } \ +#define BC_CHECK_CTXT(vm, c) \ + do \ + { \ + c = bcl_contextHelper(vm); \ + if (BC_ERR(c == NULL)) \ + { \ + BclNumber n_num_; \ + n_num_.i = 0 - (size_t) BCL_ERROR_INVALID_CONTEXT; \ + return n_num_; \ + } \ + } \ while (0) /** * A header to check the context and return an error directly if it is bad. * @param c The context. */ #define BC_CHECK_CTXT_ERR(vm, c) \ do \ { \ c = bcl_contextHelper(vm); \ if (BC_ERR(c == NULL)) \ { \ return BCL_ERROR_INVALID_CONTEXT; \ } \ } \ while (0) /** * A header to check the context and abort if it is bad. * @param c The context. */ #define BC_CHECK_CTXT_ASSERT(vm, c) \ do \ { \ c = bcl_contextHelper(vm); \ assert(c != NULL); \ } \ while (0) /** * A header to check the number in the context and return an error encoded as a * @param c The context. * number if it is bad. * @param n The BclNumber. */ #define BC_CHECK_NUM(c, n) \ do \ { \ - if (BC_ERR((n).i >= (c)->nums.len)) \ + size_t no_gen_ = BCL_NO_GEN(n); \ + if (BC_ERR(no_gen_ >= (c)->nums.len)) \ { \ if ((n).i > 0 - (size_t) BCL_ERROR_NELEMS) return (n); \ else \ { \ - BclNumber n_num; \ - n_num.i = 0 - (size_t) BCL_ERROR_INVALID_NUM; \ - return n_num; \ + BclNumber n_num_; \ + n_num_.i = 0 - (size_t) BCL_ERROR_INVALID_NUM; \ + return n_num_; \ } \ } \ + BCL_CHECK_NUM_GEN(c, n); \ } \ while (0) //clang-format off /** * A header to check the number in the context and return an error directly if * it is bad. * @param c The context. * @param n The BclNumber. */ #define BC_CHECK_NUM_ERR(c, n) \ do \ { \ - if (BC_ERR((n).i >= (c)->nums.len)) \ + size_t no_gen_ = BCL_NO_GEN(n); \ + if (BC_ERR(no_gen_ >= (c)->nums.len)) \ { \ if ((n).i > 0 - (size_t) BCL_ERROR_NELEMS) \ { \ return (BclError) (0 - (n).i); \ } \ else return BCL_ERROR_INVALID_NUM; \ } \ + BCL_CHECK_NUM_GEN(c, n); \ } \ while (0) //clang-format on /** - * Turns a BclNumber into a BcNum. + * Grows the context's nums array if necessary. * @param c The context. - * @param n The BclNumber. */ -#define BC_NUM(c, n) ((BcNum*) bc_vec_item(&(c)->nums, (n).i)) +#define BCL_GROW_NUMS(c) \ + do \ + { \ + if ((c)->free_nums.len == 0) \ + { \ + bc_vec_grow(&((c)->nums), 1); \ + } \ + } \ + while (0) /** * Frees a BcNum for bcl. This is a destructor. * @param num The BcNum to free, as a void pointer. */ void bcl_num_destruct(void* num); /// The actual context struct. typedef struct BclCtxt { /// The context's scale. size_t scale; /// The context's ibase. size_t ibase; /// The context's obase. size_t obase; /// A vector of BcNum numbers. BcVec nums; /// A vector of BclNumbers. These are the indices in nums that are currently /// not used (because they were freed). BcVec free_nums; } BclCtxt; /** * Returns the @a BcVm for the current thread. * @return The vm for the current thread. */ BcVm* bcl_getspecific(void); #ifndef _WIN32 typedef pthread_key_t BclTls; #else // _WIN32 typedef DWORD BclTls; #endif // _WIN32 #endif // LIBBC_PRIVATE_H diff --git a/contrib/bc/include/program.h b/contrib/bc/include/program.h index ff32d5db7760..1df753afad22 100644 --- a/contrib/bc/include/program.h +++ b/contrib/bc/include/program.h @@ -1,1066 +1,1000 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2023 Gavin D. Howard and contributors. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * ***************************************************************************** * * Definitions for bc programs. * */ #ifndef BC_PROGRAM_H #define BC_PROGRAM_H #include #include #include #include #include #include #include /// The index of ibase in the globals array. #define BC_PROG_GLOBALS_IBASE (0) /// The index of obase in the globals array. #define BC_PROG_GLOBALS_OBASE (1) /// The index of scale in the globals array. #define BC_PROG_GLOBALS_SCALE (2) #if BC_ENABLE_EXTRA_MATH /// The index of the rand max in the maxes array. #define BC_PROG_MAX_RAND (3) #endif // BC_ENABLE_EXTRA_MATH /// The length of the globals array. #define BC_PROG_GLOBALS_LEN (3 + BC_ENABLE_EXTRA_MATH) typedef struct BcProgram { /// The array of globals values. BcBigDig globals[BC_PROG_GLOBALS_LEN]; #if BC_ENABLED /// The array of globals stacks. BcVec globals_v[BC_PROG_GLOBALS_LEN]; #endif // BC_ENABLED #if BC_ENABLE_EXTRA_MATH /// The pseudo-random number generator. BcRNG rng; #endif // BC_ENABLE_EXTRA_MATH /// The results stack. BcVec results; /// The execution stack. BcVec stack; /// The constants encountered in the program. They are global to the program /// to prevent bad accesses when functions that used non-auto variables are /// replaced. BcVec consts; /// The map of constants to go with consts. BcVec const_map; /// The strings encountered in the program. They are global to the program /// to prevent bad accesses when functions that used non-auto variables are /// replaced. BcVec strs; /// The map of strings to go with strs. BcVec str_map; /// The array of functions. BcVec fns; /// The map of functions to go with fns. BcVec fn_map; /// The array of variables. BcVec vars; /// The map of variables to go with vars. BcVec var_map; /// The array of arrays. BcVec arrs; /// The map of arrays to go with arrs. BcVec arr_map; #if DC_ENABLED /// A vector of tail calls. These are just integers, which are the number of /// tail calls that have been executed for each function (string) on the /// stack for dc. This is to prevent dc from constantly growing memory use /// because of pushing more and more string executions on the stack. BcVec tail_calls; #endif // DC_ENABLED /// A BcNum that has the proper base for asciify. BcNum strmb; // A BcNum to run asciify. This is to prevent GCC longjmp() clobbering // warnings. BcNum asciify; #if BC_ENABLED /// The last printed value for bc. BcNum last; #endif // BC_ENABLED // The BcDig array for strmb. This uses BC_NUM_LONG_LOG10 because it is used // in bc_num_ulong2num(), which attempts to realloc, unless it is big // enough. This is big enough. BcDig strmb_num[BC_NUM_BIGDIG_LOG10]; } BcProgram; /** * Returns true if the stack @a s has at least @a n items, false otherwise. * @param s The stack to check. * @param n The number of items the stack must have. * @return True if @a s has at least @a n items, false otherwise. */ #define BC_PROG_STACK(s, n) ((s)->len >= ((size_t) (n))) /** * Get a pointer to the top value in a global value stack. * @param v The global value stack. * @return A pointer to the top value in @a v. */ #define BC_PROG_GLOBAL_PTR(v) (bc_vec_top(v)) /** * Get the top value in a global value stack. * @param v The global value stack. * @return The top value in @a v. */ #define BC_PROG_GLOBAL(v) (*((BcBigDig*) BC_PROG_GLOBAL_PTR(v))) /** * Returns the current value of ibase. * @param p The program. * @return The current ibase. */ #define BC_PROG_IBASE(p) ((p)->globals[BC_PROG_GLOBALS_IBASE]) /** * Returns the current value of obase. * @param p The program. * @return The current obase. */ #define BC_PROG_OBASE(p) ((p)->globals[BC_PROG_GLOBALS_OBASE]) /** * Returns the current value of scale. * @param p The program. * @return The current scale. */ #define BC_PROG_SCALE(p) ((p)->globals[BC_PROG_GLOBALS_SCALE]) /// The index for the main function in the functions array.// #define BC_PROG_MAIN (0) /// The index for the read function in the functions array. #define BC_PROG_READ (1) /** * Retires (completes the execution of) an instruction. Some instructions * require special retirement, but most can use this. This basically pops the * operands while preserving the result (which we assumed was pushed before the * actual operation). * @param p The program. * @param nres The number of results returned by the instruction. * @param nops The number of operands used by the instruction. */ #define bc_program_retire(p, nres, nops) \ (bc_vec_npopAt(&(p)->results, (nops), (p)->results.len - (nres + nops))) #if DC_ENABLED /// A constant that tells how many functions are required in dc. #define BC_PROG_REQ_FUNCS (2) #if !BC_ENABLED /// Returns true if the calculator should pop after printing. #define BC_PROGRAM_POP(pop) (pop) #else // !BC_ENABLED /// Returns true if the calculator should pop after printing. #define BC_PROGRAM_POP(pop) (BC_IS_BC || (pop)) #endif // !BC_ENABLED // This is here to satisfy a clang warning about recursive macros. #define bc_program_pushVar(p, code, bgn, pop, copy) \ bc_program_pushVar_impl(p, code, bgn, pop, copy) #else // DC_ENABLED // This define disappears pop and copy because for bc, 'pop' and 'copy' are // always false. #define bc_program_pushVar(p, code, bgn, pop, copy) \ bc_program_pushVar_impl(p, code, bgn) /// Returns true if the calculator should pop after printing. #define BC_PROGRAM_POP(pop) (BC_IS_BC) // In debug mode, we want bc to check the stack, but otherwise, we don't because // the bc language implicitly mandates that the stack should always have enough // items. #ifdef BC_DEBUG #define BC_PROG_NO_STACK_CHECK #endif // BC_DEBUG #endif // DC_ENABLED /** * Returns true if the BcNum @a n is acting as a string. * @param n The BcNum to test. * @return True if @a n is acting as a string, false otherwise. */ #define BC_PROG_STR(n) ((n)->num == NULL && !(n)->cap) #if BC_ENABLED /** * Returns true if the result @a r and @a n is a number. * @param r The result. * @param n The number corresponding to the result. * @return True if the result holds a number, false otherwise. */ #define BC_PROG_NUM(r, n) \ ((r)->t != BC_RESULT_ARRAY && (r)->t != BC_RESULT_STR && !BC_PROG_STR(n)) #else // BC_ENABLED /** * Returns true if the result @a r and @a n is a number. * @param r The result. * @param n The number corresponding to the result. * @return True if the result holds a number, false otherwise. */ #define BC_PROG_NUM(r, n) ((r)->t != BC_RESULT_STR && !BC_PROG_STR(n)) #endif // BC_ENABLED /** * This is a function type for unary operations. Currently, these include * boolean not, negation, and truncation with extra math. * @param r The BcResult to store the result into. * @param n The parameter to the unary operation. */ typedef void (*BcProgramUnary)(BcResult* r, BcNum* n); /** * Initializes the BcProgram. * @param p The program to initialize. */ void bc_program_init(BcProgram* p); #if BC_DEBUG /** * Frees a BcProgram. This is only used in debug builds because a BcProgram is * only freed on program exit, and we don't care about freeing resources on * exit. * @param p The program to initialize. */ void bc_program_free(BcProgram* p); #endif // BC_DEBUG /** * Prints a stack trace of the bc functions or dc strings currently executing. * @param p The program. */ void bc_program_printStackTrace(BcProgram* p); #if BC_DEBUG_CODE #if BC_ENABLED && DC_ENABLED /** * Prints the bytecode in a function. This is a debug-only function. * @param p The program. */ void bc_program_code(const BcProgram* p); /** * Prints an instruction. This is a debug-only function. * @param p The program. * @param code The bytecode array. * @param bgn A pointer to the current index. It is also updated to the next * index. */ void bc_program_printInst(const BcProgram* p, const char* code, size_t* restrict bgn); /** * Prints the stack. This is a debug-only function. * @param p The program. */ void bc_program_printStackDebug(BcProgram* p); #endif // BC_ENABLED && DC_ENABLED #endif // BC_DEBUG_CODE /** * Returns the index of the variable or array in their respective arrays. * @param p The program. * @param name The name of the variable or array. * @param var True if the search should be for a variable, false for an array. * @return The index of the variable or array in the correct array. */ size_t bc_program_search(BcProgram* p, const char* name, bool var); /** * Adds a string to the program and returns the string's index in the program. * @param p The program. * @param str The string to add. * @return The string's index in the program. */ size_t bc_program_addString(BcProgram* p, const char* str); /** * Inserts a function into the program and returns the index of the function in * the fns array. * @param p The program. * @param name The name of the function. * @return The index of the function after insertion. */ size_t bc_program_insertFunc(BcProgram* p, const char* name); /** * Resets a program, usually because of resetting after an error. * @param p The program to reset. */ void bc_program_reset(BcProgram* p); /** * Executes bc or dc code in the BcProgram. * @param p The program. */ void bc_program_exec(BcProgram* p); /** * Negates a copy of a BcNum. This is a BcProgramUnary function. * @param r The BcResult to store the result into. * @param n The parameter to the unary operation. */ void bc_program_negate(BcResult* r, BcNum* n); /** * Returns a boolean not of a BcNum. This is a BcProgramUnary function. * @param r The BcResult to store the result into. * @param n The parameter to the unary operation. */ void bc_program_not(BcResult* r, BcNum* n); #if BC_ENABLE_EXTRA_MATH /** * Truncates a copy of a BcNum. This is a BcProgramUnary function. * @param r The BcResult to store the result into. * @param n The parameter to the unary operation. */ void bc_program_trunc(BcResult* r, BcNum* n); /** * Assigns a value to the seed builtin variable. * @param p The program. * @param val The value to assign to the seed. */ void bc_program_assignSeed(BcProgram* p, BcNum* val); #endif // BC_ENABLE_EXTRA_MATH /** * Assigns a value to a builtin value that is not seed. * @param p The program. * @param scale True if the builtin is scale. * @param obase True if the builtin is obase. This cannot be true at the same * time @a scale is. * @param val The value to assign to the builtin. */ void bc_program_assignBuiltin(BcProgram* p, bool scale, bool obase, BcBigDig val); /// A reference to an array of binary operator functions. extern const BcNumBinaryOp bc_program_ops[]; /// A reference to an array of binary operator allocation request functions. extern const BcNumBinaryOpReq bc_program_opReqs[]; /// A reference to an array of unary operator functions. extern const BcProgramUnary bc_program_unarys[]; /// A reference to a filename for command-line expressions. extern const char bc_program_exprs_name[]; /// A reference to a filename for stdin. extern const char bc_program_stdin_name[]; /// A reference to the ready message printed on SIGINT. extern const char bc_program_ready_msg[]; /// A reference to the length of the ready message. extern const size_t bc_program_ready_msg_len; /// A reference to an array of escape characters for the print statement. extern const char bc_program_esc_chars[]; /// A reference to an array of the characters corresponding to the escape /// characters in bc_program_esc_chars. extern const char bc_program_esc_seqs[]; #if BC_HAS_COMPUTED_GOTO #if BC_DEBUG_CODE // clang-format off #define BC_PROG_JUMP(inst, code, ip) \ do \ { \ inst = (uchar) (code)[(ip)->idx++]; \ bc_file_printf(&vm->ferr, "inst: %s\n", bc_inst_names[inst]); \ bc_file_flush(&vm->ferr, bc_flush_none); \ goto *bc_program_inst_lbls[inst]; \ } \ while (0) // clang-format on #else // BC_DEBUG_CODE // clang-format off #define BC_PROG_JUMP(inst, code, ip) \ do \ { \ inst = (uchar) (code)[(ip)->idx++]; \ goto *bc_program_inst_lbls[inst]; \ } \ while (0) // clang-format on #endif // BC_DEBUG_CODE #define BC_PROG_DIRECT_JUMP(l) goto lbl_##l; #define BC_PROG_LBL(l) lbl_##l #define BC_PROG_FALLTHROUGH #if BC_C11 #define BC_PROG_LBLS_SIZE (sizeof(bc_program_inst_lbls) / sizeof(void*)) #define BC_PROG_LBLS_ASSERT \ _Static_assert(BC_PROG_LBLS_SIZE == BC_INST_INVALID + 1, \ "bc_program_inst_lbls[] mismatches the instructions") #else // BC_C11 #define BC_PROG_LBLS_ASSERT #endif // BC_C11 #if BC_ENABLED #if DC_ENABLED #if BC_ENABLE_EXTRA_MATH #define BC_PROG_LBLS \ static const void* const bc_program_inst_lbls[] = { \ &&lbl_BC_INST_INC, \ &&lbl_BC_INST_DEC, \ &&lbl_BC_INST_NEG, \ &&lbl_BC_INST_BOOL_NOT, \ &&lbl_BC_INST_TRUNC, \ &&lbl_BC_INST_POWER, \ &&lbl_BC_INST_MULTIPLY, \ &&lbl_BC_INST_DIVIDE, \ &&lbl_BC_INST_MODULUS, \ &&lbl_BC_INST_PLUS, \ &&lbl_BC_INST_MINUS, \ &&lbl_BC_INST_PLACES, \ &&lbl_BC_INST_LSHIFT, \ &&lbl_BC_INST_RSHIFT, \ &&lbl_BC_INST_REL_EQ, \ &&lbl_BC_INST_REL_LE, \ &&lbl_BC_INST_REL_GE, \ &&lbl_BC_INST_REL_NE, \ &&lbl_BC_INST_REL_LT, \ &&lbl_BC_INST_REL_GT, \ &&lbl_BC_INST_BOOL_OR, \ &&lbl_BC_INST_BOOL_AND, \ &&lbl_BC_INST_ASSIGN_POWER, \ &&lbl_BC_INST_ASSIGN_MULTIPLY, \ &&lbl_BC_INST_ASSIGN_DIVIDE, \ &&lbl_BC_INST_ASSIGN_MODULUS, \ &&lbl_BC_INST_ASSIGN_PLUS, \ &&lbl_BC_INST_ASSIGN_MINUS, \ &&lbl_BC_INST_ASSIGN_PLACES, \ &&lbl_BC_INST_ASSIGN_LSHIFT, \ &&lbl_BC_INST_ASSIGN_RSHIFT, \ &&lbl_BC_INST_ASSIGN, \ &&lbl_BC_INST_ASSIGN_POWER_NO_VAL, \ &&lbl_BC_INST_ASSIGN_MULTIPLY_NO_VAL, \ &&lbl_BC_INST_ASSIGN_DIVIDE_NO_VAL, \ &&lbl_BC_INST_ASSIGN_MODULUS_NO_VAL, \ &&lbl_BC_INST_ASSIGN_PLUS_NO_VAL, \ &&lbl_BC_INST_ASSIGN_MINUS_NO_VAL, \ &&lbl_BC_INST_ASSIGN_PLACES_NO_VAL, \ &&lbl_BC_INST_ASSIGN_LSHIFT_NO_VAL, \ &&lbl_BC_INST_ASSIGN_RSHIFT_NO_VAL, \ &&lbl_BC_INST_ASSIGN_NO_VAL, \ &&lbl_BC_INST_NUM, \ &&lbl_BC_INST_VAR, \ &&lbl_BC_INST_ARRAY_ELEM, \ &&lbl_BC_INST_ARRAY, \ &&lbl_BC_INST_ZERO, \ &&lbl_BC_INST_ONE, \ &&lbl_BC_INST_LAST, \ &&lbl_BC_INST_IBASE, \ &&lbl_BC_INST_OBASE, \ &&lbl_BC_INST_SCALE, \ &&lbl_BC_INST_SEED, \ &&lbl_BC_INST_LENGTH, \ &&lbl_BC_INST_SCALE_FUNC, \ &&lbl_BC_INST_SQRT, \ &&lbl_BC_INST_ABS, \ &&lbl_BC_INST_IS_NUMBER, \ &&lbl_BC_INST_IS_STRING, \ &&lbl_BC_INST_IRAND, \ &&lbl_BC_INST_ASCIIFY, \ &&lbl_BC_INST_READ, \ &&lbl_BC_INST_RAND, \ &&lbl_BC_INST_MAXIBASE, \ &&lbl_BC_INST_MAXOBASE, \ &&lbl_BC_INST_MAXSCALE, \ &&lbl_BC_INST_MAXRAND, \ &&lbl_BC_INST_LINE_LENGTH, \ &&lbl_BC_INST_GLOBAL_STACKS, \ &&lbl_BC_INST_LEADING_ZERO, \ &&lbl_BC_INST_PRINT, \ &&lbl_BC_INST_PRINT_POP, \ &&lbl_BC_INST_STR, \ &&lbl_BC_INST_PRINT_STR, \ &&lbl_BC_INST_JUMP, \ &&lbl_BC_INST_JUMP_ZERO, \ &&lbl_BC_INST_CALL, \ &&lbl_BC_INST_RET, \ &&lbl_BC_INST_RET0, \ &&lbl_BC_INST_RET_VOID, \ &&lbl_BC_INST_HALT, \ &&lbl_BC_INST_POP, \ &&lbl_BC_INST_SWAP, \ &&lbl_BC_INST_MODEXP, \ &&lbl_BC_INST_DIVMOD, \ &&lbl_BC_INST_PRINT_STREAM, \ &&lbl_BC_INST_EXTENDED_REGISTERS, \ &&lbl_BC_INST_POP_EXEC, \ &&lbl_BC_INST_EXECUTE, \ &&lbl_BC_INST_EXEC_COND, \ &&lbl_BC_INST_PRINT_STACK, \ &&lbl_BC_INST_CLEAR_STACK, \ &&lbl_BC_INST_REG_STACK_LEN, \ &&lbl_BC_INST_STACK_LEN, \ &&lbl_BC_INST_DUPLICATE, \ &&lbl_BC_INST_LOAD, \ &&lbl_BC_INST_PUSH_VAR, \ &&lbl_BC_INST_PUSH_TO_VAR, \ &&lbl_BC_INST_QUIT, \ &&lbl_BC_INST_NQUIT, \ &&lbl_BC_INST_EXEC_STACK_LEN, \ &&lbl_BC_INST_INVALID, \ } #else // BC_ENABLE_EXTRA_MATH #define BC_PROG_LBLS \ static const void* const bc_program_inst_lbls[] = { \ &&lbl_BC_INST_INC, \ &&lbl_BC_INST_DEC, \ &&lbl_BC_INST_NEG, \ &&lbl_BC_INST_BOOL_NOT, \ &&lbl_BC_INST_POWER, \ &&lbl_BC_INST_MULTIPLY, \ &&lbl_BC_INST_DIVIDE, \ &&lbl_BC_INST_MODULUS, \ &&lbl_BC_INST_PLUS, \ &&lbl_BC_INST_MINUS, \ &&lbl_BC_INST_REL_EQ, \ &&lbl_BC_INST_REL_LE, \ &&lbl_BC_INST_REL_GE, \ &&lbl_BC_INST_REL_NE, \ &&lbl_BC_INST_REL_LT, \ &&lbl_BC_INST_REL_GT, \ &&lbl_BC_INST_BOOL_OR, \ &&lbl_BC_INST_BOOL_AND, \ &&lbl_BC_INST_ASSIGN_POWER, \ &&lbl_BC_INST_ASSIGN_MULTIPLY, \ &&lbl_BC_INST_ASSIGN_DIVIDE, \ &&lbl_BC_INST_ASSIGN_MODULUS, \ &&lbl_BC_INST_ASSIGN_PLUS, \ &&lbl_BC_INST_ASSIGN_MINUS, \ &&lbl_BC_INST_ASSIGN, \ &&lbl_BC_INST_ASSIGN_POWER_NO_VAL, \ &&lbl_BC_INST_ASSIGN_MULTIPLY_NO_VAL, \ &&lbl_BC_INST_ASSIGN_DIVIDE_NO_VAL, \ &&lbl_BC_INST_ASSIGN_MODULUS_NO_VAL, \ &&lbl_BC_INST_ASSIGN_PLUS_NO_VAL, \ &&lbl_BC_INST_ASSIGN_MINUS_NO_VAL, \ &&lbl_BC_INST_ASSIGN_NO_VAL, \ &&lbl_BC_INST_NUM, \ &&lbl_BC_INST_VAR, \ &&lbl_BC_INST_ARRAY_ELEM, \ &&lbl_BC_INST_ARRAY, \ &&lbl_BC_INST_ZERO, \ &&lbl_BC_INST_ONE, \ &&lbl_BC_INST_LAST, \ &&lbl_BC_INST_IBASE, \ &&lbl_BC_INST_OBASE, \ &&lbl_BC_INST_SCALE, \ &&lbl_BC_INST_LENGTH, \ &&lbl_BC_INST_SCALE_FUNC, \ &&lbl_BC_INST_SQRT, \ &&lbl_BC_INST_ABS, \ &&lbl_BC_INST_IS_NUMBER, \ &&lbl_BC_INST_IS_STRING, \ &&lbl_BC_INST_ASCIIFY, \ &&lbl_BC_INST_READ, \ &&lbl_BC_INST_MAXIBASE, \ &&lbl_BC_INST_MAXOBASE, \ &&lbl_BC_INST_MAXSCALE, \ &&lbl_BC_INST_LINE_LENGTH, \ &&lbl_BC_INST_GLOBAL_STACKS, \ &&lbl_BC_INST_LEADING_ZERO, \ &&lbl_BC_INST_PRINT, \ &&lbl_BC_INST_PRINT_POP, \ &&lbl_BC_INST_STR, \ &&lbl_BC_INST_PRINT_STR, \ &&lbl_BC_INST_JUMP, \ &&lbl_BC_INST_JUMP_ZERO, \ &&lbl_BC_INST_CALL, \ &&lbl_BC_INST_RET, \ &&lbl_BC_INST_RET0, \ &&lbl_BC_INST_RET_VOID, \ &&lbl_BC_INST_HALT, \ &&lbl_BC_INST_POP, \ &&lbl_BC_INST_SWAP, \ &&lbl_BC_INST_MODEXP, \ &&lbl_BC_INST_DIVMOD, \ &&lbl_BC_INST_PRINT_STREAM, \ &&lbl_BC_INST_EXTENDED_REGISTERS, \ &&lbl_BC_INST_POP_EXEC, \ &&lbl_BC_INST_EXECUTE, \ &&lbl_BC_INST_EXEC_COND, \ &&lbl_BC_INST_PRINT_STACK, \ &&lbl_BC_INST_CLEAR_STACK, \ &&lbl_BC_INST_REG_STACK_LEN, \ &&lbl_BC_INST_STACK_LEN, \ &&lbl_BC_INST_DUPLICATE, \ &&lbl_BC_INST_LOAD, \ &&lbl_BC_INST_PUSH_VAR, \ &&lbl_BC_INST_PUSH_TO_VAR, \ &&lbl_BC_INST_QUIT, \ &&lbl_BC_INST_NQUIT, \ &&lbl_BC_INST_EXEC_STACK_LEN, \ &&lbl_BC_INST_INVALID, \ } #endif // BC_ENABLE_EXTRA_MATH #else // DC_ENABLED #if BC_ENABLE_EXTRA_MATH #define BC_PROG_LBLS \ static const void* const bc_program_inst_lbls[] = { \ &&lbl_BC_INST_INC, \ &&lbl_BC_INST_DEC, \ &&lbl_BC_INST_NEG, \ &&lbl_BC_INST_BOOL_NOT, \ &&lbl_BC_INST_TRUNC, \ &&lbl_BC_INST_POWER, \ &&lbl_BC_INST_MULTIPLY, \ &&lbl_BC_INST_DIVIDE, \ &&lbl_BC_INST_MODULUS, \ &&lbl_BC_INST_PLUS, \ &&lbl_BC_INST_MINUS, \ &&lbl_BC_INST_PLACES, \ &&lbl_BC_INST_LSHIFT, \ &&lbl_BC_INST_RSHIFT, \ &&lbl_BC_INST_REL_EQ, \ &&lbl_BC_INST_REL_LE, \ &&lbl_BC_INST_REL_GE, \ &&lbl_BC_INST_REL_NE, \ &&lbl_BC_INST_REL_LT, \ &&lbl_BC_INST_REL_GT, \ &&lbl_BC_INST_BOOL_OR, \ &&lbl_BC_INST_BOOL_AND, \ &&lbl_BC_INST_ASSIGN_POWER, \ &&lbl_BC_INST_ASSIGN_MULTIPLY, \ &&lbl_BC_INST_ASSIGN_DIVIDE, \ &&lbl_BC_INST_ASSIGN_MODULUS, \ &&lbl_BC_INST_ASSIGN_PLUS, \ &&lbl_BC_INST_ASSIGN_MINUS, \ &&lbl_BC_INST_ASSIGN_PLACES, \ &&lbl_BC_INST_ASSIGN_LSHIFT, \ &&lbl_BC_INST_ASSIGN_RSHIFT, \ &&lbl_BC_INST_ASSIGN, \ &&lbl_BC_INST_ASSIGN_POWER_NO_VAL, \ &&lbl_BC_INST_ASSIGN_MULTIPLY_NO_VAL, \ &&lbl_BC_INST_ASSIGN_DIVIDE_NO_VAL, \ &&lbl_BC_INST_ASSIGN_MODULUS_NO_VAL, \ &&lbl_BC_INST_ASSIGN_PLUS_NO_VAL, \ &&lbl_BC_INST_ASSIGN_MINUS_NO_VAL, \ &&lbl_BC_INST_ASSIGN_PLACES_NO_VAL, \ &&lbl_BC_INST_ASSIGN_LSHIFT_NO_VAL, \ &&lbl_BC_INST_ASSIGN_RSHIFT_NO_VAL, \ &&lbl_BC_INST_ASSIGN_NO_VAL, \ &&lbl_BC_INST_NUM, \ &&lbl_BC_INST_VAR, \ &&lbl_BC_INST_ARRAY_ELEM, \ &&lbl_BC_INST_ARRAY, \ &&lbl_BC_INST_ZERO, \ &&lbl_BC_INST_ONE, \ &&lbl_BC_INST_LAST, \ &&lbl_BC_INST_IBASE, \ &&lbl_BC_INST_OBASE, \ &&lbl_BC_INST_SCALE, \ &&lbl_BC_INST_SEED, \ &&lbl_BC_INST_LENGTH, \ &&lbl_BC_INST_SCALE_FUNC, \ &&lbl_BC_INST_SQRT, \ &&lbl_BC_INST_ABS, \ &&lbl_BC_INST_IS_NUMBER, \ &&lbl_BC_INST_IS_STRING, \ &&lbl_BC_INST_IRAND, \ &&lbl_BC_INST_ASCIIFY, \ &&lbl_BC_INST_READ, \ &&lbl_BC_INST_RAND, \ &&lbl_BC_INST_MAXIBASE, \ &&lbl_BC_INST_MAXOBASE, \ &&lbl_BC_INST_MAXSCALE, \ &&lbl_BC_INST_MAXRAND, \ &&lbl_BC_INST_LINE_LENGTH, \ &&lbl_BC_INST_GLOBAL_STACKS, \ &&lbl_BC_INST_LEADING_ZERO, \ &&lbl_BC_INST_PRINT, \ &&lbl_BC_INST_PRINT_POP, \ &&lbl_BC_INST_STR, \ &&lbl_BC_INST_PRINT_STR, \ &&lbl_BC_INST_JUMP, \ &&lbl_BC_INST_JUMP_ZERO, \ &&lbl_BC_INST_CALL, \ &&lbl_BC_INST_RET, \ &&lbl_BC_INST_RET0, \ &&lbl_BC_INST_RET_VOID, \ &&lbl_BC_INST_HALT, \ &&lbl_BC_INST_POP, \ &&lbl_BC_INST_SWAP, \ &&lbl_BC_INST_MODEXP, \ &&lbl_BC_INST_DIVMOD, \ &&lbl_BC_INST_PRINT_STREAM, \ &&lbl_BC_INST_INVALID, \ } #else // BC_ENABLE_EXTRA_MATH #define BC_PROG_LBLS \ static const void* const bc_program_inst_lbls[] = { \ &&lbl_BC_INST_INC, \ &&lbl_BC_INST_DEC, \ &&lbl_BC_INST_NEG, \ &&lbl_BC_INST_BOOL_NOT, \ &&lbl_BC_INST_POWER, \ &&lbl_BC_INST_MULTIPLY, \ &&lbl_BC_INST_DIVIDE, \ &&lbl_BC_INST_MODULUS, \ &&lbl_BC_INST_PLUS, \ &&lbl_BC_INST_MINUS, \ &&lbl_BC_INST_REL_EQ, \ &&lbl_BC_INST_REL_LE, \ &&lbl_BC_INST_REL_GE, \ &&lbl_BC_INST_REL_NE, \ &&lbl_BC_INST_REL_LT, \ &&lbl_BC_INST_REL_GT, \ &&lbl_BC_INST_BOOL_OR, \ &&lbl_BC_INST_BOOL_AND, \ &&lbl_BC_INST_ASSIGN_POWER, \ &&lbl_BC_INST_ASSIGN_MULTIPLY, \ &&lbl_BC_INST_ASSIGN_DIVIDE, \ &&lbl_BC_INST_ASSIGN_MODULUS, \ &&lbl_BC_INST_ASSIGN_PLUS, \ &&lbl_BC_INST_ASSIGN_MINUS, \ &&lbl_BC_INST_ASSIGN, \ &&lbl_BC_INST_ASSIGN_POWER_NO_VAL, \ &&lbl_BC_INST_ASSIGN_MULTIPLY_NO_VAL, \ &&lbl_BC_INST_ASSIGN_DIVIDE_NO_VAL, \ &&lbl_BC_INST_ASSIGN_MODULUS_NO_VAL, \ &&lbl_BC_INST_ASSIGN_PLUS_NO_VAL, \ &&lbl_BC_INST_ASSIGN_MINUS_NO_VAL, \ &&lbl_BC_INST_ASSIGN_NO_VAL, \ &&lbl_BC_INST_NUM, \ &&lbl_BC_INST_VAR, \ &&lbl_BC_INST_ARRAY_ELEM, \ &&lbl_BC_INST_ARRAY, \ &&lbl_BC_INST_ZERO, \ &&lbl_BC_INST_ONE, \ &&lbl_BC_INST_LAST, \ &&lbl_BC_INST_IBASE, \ &&lbl_BC_INST_OBASE, \ &&lbl_BC_INST_SCALE, \ &&lbl_BC_INST_LENGTH, \ &&lbl_BC_INST_SCALE_FUNC, \ &&lbl_BC_INST_SQRT, \ &&lbl_BC_INST_ABS, \ &&lbl_BC_INST_IS_NUMBER, \ &&lbl_BC_INST_IS_STRING, \ &&lbl_BC_INST_ASCIIFY, \ &&lbl_BC_INST_READ, \ &&lbl_BC_INST_MAXIBASE, \ &&lbl_BC_INST_MAXOBASE, \ &&lbl_BC_INST_MAXSCALE, \ &&lbl_BC_INST_LINE_LENGTH, \ &&lbl_BC_INST_GLOBAL_STACKS, \ &&lbl_BC_INST_LEADING_ZERO, \ &&lbl_BC_INST_PRINT, \ &&lbl_BC_INST_PRINT_POP, \ &&lbl_BC_INST_STR, \ &&lbl_BC_INST_PRINT_STR, \ &&lbl_BC_INST_JUMP, \ &&lbl_BC_INST_JUMP_ZERO, \ &&lbl_BC_INST_CALL, \ &&lbl_BC_INST_RET, \ &&lbl_BC_INST_RET0, \ &&lbl_BC_INST_RET_VOID, \ &&lbl_BC_INST_HALT, \ &&lbl_BC_INST_POP, \ &&lbl_BC_INST_SWAP, \ &&lbl_BC_INST_MODEXP, \ &&lbl_BC_INST_DIVMOD, \ &&lbl_BC_INST_PRINT_STREAM, \ &&lbl_BC_INST_INVALID, \ } #endif // BC_ENABLE_EXTRA_MATH #endif // DC_ENABLED #else // BC_ENABLED #if BC_ENABLE_EXTRA_MATH -#define BC_PROG_LBLS \ - static const void* const bc_program_inst_lbls[] = { \ - &&lbl_BC_INST_NEG, \ - &&lbl_BC_INST_BOOL_NOT, \ - &&lbl_BC_INST_TRUNC, \ - &&lbl_BC_INST_POWER, \ - &&lbl_BC_INST_MULTIPLY, \ - &&lbl_BC_INST_DIVIDE, \ - &&lbl_BC_INST_MODULUS, \ - &&lbl_BC_INST_PLUS, \ - &&lbl_BC_INST_MINUS, \ - &&lbl_BC_INST_PLACES, \ - &&lbl_BC_INST_LSHIFT, \ - &&lbl_BC_INST_RSHIFT, \ - &&lbl_BC_INST_REL_EQ, \ - &&lbl_BC_INST_REL_LE, \ - &&lbl_BC_INST_REL_GE, \ - &&lbl_BC_INST_REL_NE, \ - &&lbl_BC_INST_REL_LT, \ - &&lbl_BC_INST_REL_GT, \ - &&lbl_BC_INST_BOOL_OR, \ - &&lbl_BC_INST_BOOL_AND, \ - &&lbl_BC_INST_ASSIGN_NO_VAL, \ - &&lbl_BC_INST_NUM, \ - &&lbl_BC_INST_VAR, \ - &&lbl_BC_INST_ARRAY_ELEM, \ - &&lbl_BC_INST_ARRAY, \ - &&lbl_BC_INST_ZERO, \ - &&lbl_BC_INST_ONE, \ - &&lbl_BC_INST_IBASE, \ - &&lbl_BC_INST_OBASE, \ - &&lbl_BC_INST_SCALE, \ - &&lbl_BC_INST_SEED, \ - &&lbl_BC_INST_LENGTH, \ - &&lbl_BC_INST_SCALE_FUNC, \ - &&lbl_BC_INST_SQRT, \ - &&lbl_BC_INST_ABS, \ - &&lbl_BC_INST_IS_NUMBER, \ - &&lbl_BC_INST_IS_STRING, \ - &&lbl_BC_INST_IRAND, \ - &&lbl_BC_INST_ASCIIFY, \ - &&lbl_BC_INST_READ, \ - &&lbl_BC_INST_RAND, \ - &&lbl_BC_INST_MAXIBASE, \ - &&lbl_BC_INST_MAXOBASE, \ - &&lbl_BC_INST_MAXSCALE, \ - &&lbl_BC_INST_MAXRAND, \ - &&lbl_BC_INST_LINE_LENGTH, \ - &&lbl_BC_INST_LEADING_ZERO, \ - &&lbl_BC_INST_PRINT, \ - &&lbl_BC_INST_PRINT_POP, \ - &&lbl_BC_INST_STR, \ - &&lbl_BC_INST_POP, \ - &&lbl_BC_INST_SWAP, \ - &&lbl_BC_INST_MODEXP, \ - &&lbl_BC_INST_DIVMOD, \ - &&lbl_BC_INST_PRINT_STREAM, \ - &&lbl_BC_INST_EXTENDED_REGISTERS, \ - &&lbl_BC_INST_POP_EXEC, \ - &&lbl_BC_INST_EXECUTE, \ - &&lbl_BC_INST_EXEC_COND, \ - &&lbl_BC_INST_PRINT_STACK, \ - &&lbl_BC_INST_CLEAR_STACK, \ - &&lbl_BC_INST_REG_STACK_LEN, \ - &&lbl_BC_INST_STACK_LEN, \ - &&lbl_BC_INST_DUPLICATE, \ - &&lbl_BC_INST_LOAD, \ - &&lbl_BC_INST_PUSH_VAR, \ - &&lbl_BC_INST_PUSH_TO_VAR, \ - &&lbl_BC_INST_QUIT, \ - &&lbl_BC_INST_NQUIT, \ - &&lbl_BC_INST_EXEC_STACK_LEN, \ - &&lbl_BC_INST_INVALID, \ +#define BC_PROG_LBLS \ + static const void* const bc_program_inst_lbls[] = { \ + &&lbl_BC_INST_NEG, &&lbl_BC_INST_BOOL_NOT, \ + &&lbl_BC_INST_TRUNC, &&lbl_BC_INST_POWER, \ + &&lbl_BC_INST_MULTIPLY, &&lbl_BC_INST_DIVIDE, \ + &&lbl_BC_INST_MODULUS, &&lbl_BC_INST_PLUS, \ + &&lbl_BC_INST_MINUS, &&lbl_BC_INST_PLACES, \ + &&lbl_BC_INST_LSHIFT, &&lbl_BC_INST_RSHIFT, \ + &&lbl_BC_INST_REL_EQ, &&lbl_BC_INST_REL_LE, \ + &&lbl_BC_INST_REL_GE, &&lbl_BC_INST_REL_NE, \ + &&lbl_BC_INST_REL_LT, &&lbl_BC_INST_REL_GT, \ + &&lbl_BC_INST_BOOL_OR, &&lbl_BC_INST_BOOL_AND, \ + &&lbl_BC_INST_ASSIGN_NO_VAL, &&lbl_BC_INST_NUM, \ + &&lbl_BC_INST_VAR, &&lbl_BC_INST_ARRAY_ELEM, \ + &&lbl_BC_INST_ARRAY, &&lbl_BC_INST_ZERO, \ + &&lbl_BC_INST_ONE, &&lbl_BC_INST_IBASE, \ + &&lbl_BC_INST_OBASE, &&lbl_BC_INST_SCALE, \ + &&lbl_BC_INST_SEED, &&lbl_BC_INST_LENGTH, \ + &&lbl_BC_INST_SCALE_FUNC, &&lbl_BC_INST_SQRT, \ + &&lbl_BC_INST_ABS, &&lbl_BC_INST_IS_NUMBER, \ + &&lbl_BC_INST_IS_STRING, &&lbl_BC_INST_IRAND, \ + &&lbl_BC_INST_ASCIIFY, &&lbl_BC_INST_READ, \ + &&lbl_BC_INST_RAND, &&lbl_BC_INST_MAXIBASE, \ + &&lbl_BC_INST_MAXOBASE, &&lbl_BC_INST_MAXSCALE, \ + &&lbl_BC_INST_MAXRAND, &&lbl_BC_INST_LINE_LENGTH, \ + &&lbl_BC_INST_LEADING_ZERO, &&lbl_BC_INST_PRINT, \ + &&lbl_BC_INST_PRINT_POP, &&lbl_BC_INST_STR, \ + &&lbl_BC_INST_POP, &&lbl_BC_INST_SWAP, \ + &&lbl_BC_INST_MODEXP, &&lbl_BC_INST_DIVMOD, \ + &&lbl_BC_INST_PRINT_STREAM, &&lbl_BC_INST_EXTENDED_REGISTERS, \ + &&lbl_BC_INST_POP_EXEC, &&lbl_BC_INST_EXECUTE, \ + &&lbl_BC_INST_EXEC_COND, &&lbl_BC_INST_PRINT_STACK, \ + &&lbl_BC_INST_CLEAR_STACK, &&lbl_BC_INST_REG_STACK_LEN, \ + &&lbl_BC_INST_STACK_LEN, &&lbl_BC_INST_DUPLICATE, \ + &&lbl_BC_INST_LOAD, &&lbl_BC_INST_PUSH_VAR, \ + &&lbl_BC_INST_PUSH_TO_VAR, &&lbl_BC_INST_QUIT, \ + &&lbl_BC_INST_NQUIT, &&lbl_BC_INST_EXEC_STACK_LEN, \ + &&lbl_BC_INST_INVALID, \ } #else // BC_ENABLE_EXTRA_MATH -#define BC_PROG_LBLS \ - static const void* const bc_program_inst_lbls[] = { \ - &&lbl_BC_INST_NEG, \ - &&lbl_BC_INST_BOOL_NOT, \ - &&lbl_BC_INST_POWER, \ - &&lbl_BC_INST_MULTIPLY, \ - &&lbl_BC_INST_DIVIDE, \ - &&lbl_BC_INST_MODULUS, \ - &&lbl_BC_INST_PLUS, \ - &&lbl_BC_INST_MINUS, \ - &&lbl_BC_INST_REL_EQ, \ - &&lbl_BC_INST_REL_LE, \ - &&lbl_BC_INST_REL_GE, \ - &&lbl_BC_INST_REL_NE, \ - &&lbl_BC_INST_REL_LT, \ - &&lbl_BC_INST_REL_GT, \ - &&lbl_BC_INST_BOOL_OR, \ - &&lbl_BC_INST_BOOL_AND, \ - &&lbl_BC_INST_ASSIGN_NO_VAL, \ - &&lbl_BC_INST_NUM, \ - &&lbl_BC_INST_VAR, \ - &&lbl_BC_INST_ARRAY_ELEM, \ - &&lbl_BC_INST_ARRAY, \ - &&lbl_BC_INST_ZERO, \ - &&lbl_BC_INST_ONE, \ - &&lbl_BC_INST_IBASE, \ - &&lbl_BC_INST_OBASE, \ - &&lbl_BC_INST_SCALE, \ - &&lbl_BC_INST_LENGTH, \ - &&lbl_BC_INST_SCALE_FUNC, \ - &&lbl_BC_INST_SQRT, \ - &&lbl_BC_INST_ABS, \ - &&lbl_BC_INST_IS_NUMBER, \ - &&lbl_BC_INST_IS_STRING, \ - &&lbl_BC_INST_ASCIIFY, \ - &&lbl_BC_INST_READ, \ - &&lbl_BC_INST_MAXIBASE, \ - &&lbl_BC_INST_MAXOBASE, \ - &&lbl_BC_INST_MAXSCALE, \ - &&lbl_BC_INST_LINE_LENGTH, \ - &&lbl_BC_INST_LEADING_ZERO, \ - &&lbl_BC_INST_PRINT, \ - &&lbl_BC_INST_PRINT_POP, \ - &&lbl_BC_INST_STR, \ - &&lbl_BC_INST_POP, \ - &&lbl_BC_INST_SWAP, \ - &&lbl_BC_INST_MODEXP, \ - &&lbl_BC_INST_DIVMOD, \ - &&lbl_BC_INST_PRINT_STREAM, \ - &&lbl_BC_INST_EXTENDED_REGISTERS, \ - &&lbl_BC_INST_POP_EXEC, \ - &&lbl_BC_INST_EXECUTE, \ - &&lbl_BC_INST_EXEC_COND, \ - &&lbl_BC_INST_PRINT_STACK, \ - &&lbl_BC_INST_CLEAR_STACK, \ - &&lbl_BC_INST_REG_STACK_LEN, \ - &&lbl_BC_INST_STACK_LEN, \ - &&lbl_BC_INST_DUPLICATE, \ - &&lbl_BC_INST_LOAD, \ - &&lbl_BC_INST_PUSH_VAR, \ - &&lbl_BC_INST_PUSH_TO_VAR, \ - &&lbl_BC_INST_QUIT, \ - &&lbl_BC_INST_NQUIT, \ - &&lbl_BC_INST_EXEC_STACK_LEN, \ - &&lbl_BC_INST_INVALID, \ +#define BC_PROG_LBLS \ + static const void* const bc_program_inst_lbls[] = { \ + &&lbl_BC_INST_NEG, &&lbl_BC_INST_BOOL_NOT, \ + &&lbl_BC_INST_POWER, &&lbl_BC_INST_MULTIPLY, \ + &&lbl_BC_INST_DIVIDE, &&lbl_BC_INST_MODULUS, \ + &&lbl_BC_INST_PLUS, &&lbl_BC_INST_MINUS, \ + &&lbl_BC_INST_REL_EQ, &&lbl_BC_INST_REL_LE, \ + &&lbl_BC_INST_REL_GE, &&lbl_BC_INST_REL_NE, \ + &&lbl_BC_INST_REL_LT, &&lbl_BC_INST_REL_GT, \ + &&lbl_BC_INST_BOOL_OR, &&lbl_BC_INST_BOOL_AND, \ + &&lbl_BC_INST_ASSIGN_NO_VAL, &&lbl_BC_INST_NUM, \ + &&lbl_BC_INST_VAR, &&lbl_BC_INST_ARRAY_ELEM, \ + &&lbl_BC_INST_ARRAY, &&lbl_BC_INST_ZERO, \ + &&lbl_BC_INST_ONE, &&lbl_BC_INST_IBASE, \ + &&lbl_BC_INST_OBASE, &&lbl_BC_INST_SCALE, \ + &&lbl_BC_INST_LENGTH, &&lbl_BC_INST_SCALE_FUNC, \ + &&lbl_BC_INST_SQRT, &&lbl_BC_INST_ABS, \ + &&lbl_BC_INST_IS_NUMBER, &&lbl_BC_INST_IS_STRING, \ + &&lbl_BC_INST_ASCIIFY, &&lbl_BC_INST_READ, \ + &&lbl_BC_INST_MAXIBASE, &&lbl_BC_INST_MAXOBASE, \ + &&lbl_BC_INST_MAXSCALE, &&lbl_BC_INST_LINE_LENGTH, \ + &&lbl_BC_INST_LEADING_ZERO, &&lbl_BC_INST_PRINT, \ + &&lbl_BC_INST_PRINT_POP, &&lbl_BC_INST_STR, \ + &&lbl_BC_INST_POP, &&lbl_BC_INST_SWAP, \ + &&lbl_BC_INST_MODEXP, &&lbl_BC_INST_DIVMOD, \ + &&lbl_BC_INST_PRINT_STREAM, &&lbl_BC_INST_EXTENDED_REGISTERS, \ + &&lbl_BC_INST_POP_EXEC, &&lbl_BC_INST_EXECUTE, \ + &&lbl_BC_INST_EXEC_COND, &&lbl_BC_INST_PRINT_STACK, \ + &&lbl_BC_INST_CLEAR_STACK, &&lbl_BC_INST_REG_STACK_LEN, \ + &&lbl_BC_INST_STACK_LEN, &&lbl_BC_INST_DUPLICATE, \ + &&lbl_BC_INST_LOAD, &&lbl_BC_INST_PUSH_VAR, \ + &&lbl_BC_INST_PUSH_TO_VAR, &&lbl_BC_INST_QUIT, \ + &&lbl_BC_INST_NQUIT, &&lbl_BC_INST_EXEC_STACK_LEN, \ + &&lbl_BC_INST_INVALID, \ } #endif // BC_ENABLE_EXTRA_MATH #endif // BC_ENABLED #else // BC_HAS_COMPUTED_GOTO #define BC_PROG_JUMP(inst, code, ip) break #define BC_PROG_DIRECT_JUMP(l) #define BC_PROG_LBL(l) case l #define BC_PROG_FALLTHROUGH BC_FALLTHROUGH #define BC_PROG_LBLS #endif // BC_HAS_COMPUTED_GOTO #endif // BC_PROGRAM_H diff --git a/contrib/bc/include/version.h b/contrib/bc/include/version.h index f5e345b3b189..3745ed9b5f74 100644 --- a/contrib/bc/include/version.h +++ b/contrib/bc/include/version.h @@ -1,42 +1,42 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2023 Gavin D. Howard and contributors. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * ***************************************************************************** * * The version of bc. * */ #ifndef BC_VERSION_H #define BC_VERSION_H /// The current version. -#define VERSION 6.3.1 +#define VERSION 6.4.0 #endif // BC_VERSION_H diff --git a/contrib/bc/include/vm.h b/contrib/bc/include/vm.h index dd21d43f5260..c56cc8e7370a 100644 --- a/contrib/bc/include/vm.h +++ b/contrib/bc/include/vm.h @@ -1,1086 +1,1090 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2023 Gavin D. Howard and contributors. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * ***************************************************************************** * * Definitions for bc's VM. * */ #ifndef BC_VM_H #define BC_VM_H #include #include #include #include #if BC_ENABLE_NLS #ifdef _WIN32 #error NLS is not supported on Windows. #endif // _WIN32 #include #endif // BC_ENABLE_NLS #include #include #include #include #include #include #include #include // We don't want to include this file for the library because it's unused. #if !BC_ENABLE_LIBRARY #include #endif // !BC_ENABLE_LIBRARY // This should be obvious. If neither calculator is enabled, barf. #if !BC_ENABLED && !DC_ENABLED #error Must define BC_ENABLED, DC_ENABLED, or both #endif // CHAR_BIT must be at least 6, for various reasons. I might want to bump this // to 8 in the future. #if CHAR_BIT < 6 #error CHAR_BIT must be at least 6. #endif // Set defaults. #ifndef MAINEXEC #define MAINEXEC bc #endif // MAINEXEC #ifndef _WIN32 #ifndef EXECPREFIX #define EXECPREFIX #endif // EXECPREFIX #else // _WIN32 #undef EXECPREFIX #endif // _WIN32 /** * Generate a string from text. * @parm V The text to generate a string for. */ #define GEN_STR(V) #V /** * Help generate a string from text. The preprocessor requires this two-step * process. Trust me. * @parm V The text to generate a string for. */ #define GEN_STR2(V) GEN_STR(V) /// The version as a string. VERSION must be defined previously, usually by the /// build system. #define BC_VERSION GEN_STR2(VERSION) /// The main executable name as a string. MAINEXEC must be defined previously, /// usually by the build system. #define BC_MAINEXEC GEN_STR2(MAINEXEC) /// The build type as a string. BUILD_TYPE must be defined previously, usually /// by the build system. #define BC_BUILD_TYPE GEN_STR2(BUILD_TYPE) // We only allow an empty executable prefix on Windows. #ifndef _WIN32 #define BC_EXECPREFIX GEN_STR2(EXECPREFIX) #else // _WIN32 #define BC_EXECPREFIX "" #endif // _WIN32 #if !BC_ENABLE_LIBRARY #if DC_ENABLED /// The flag for the extended register option. #define DC_FLAG_X (UINTMAX_C(1) << 0) #endif // DC_ENABLED #if BC_ENABLED /// The flag for the POSIX warning option. #define BC_FLAG_W (UINTMAX_C(1) << 1) /// The flag for the POSIX error option. #define BC_FLAG_S (UINTMAX_C(1) << 2) /// The flag for the math library option. #define BC_FLAG_L (UINTMAX_C(1) << 3) /// The flag for the global stacks option. #define BC_FLAG_G (UINTMAX_C(1) << 4) #endif // BC_ENABLED /// The flag for quiet, though this one is reversed; the option clears the flag. #define BC_FLAG_Q (UINTMAX_C(1) << 5) /// The flag for interactive. #define BC_FLAG_I (UINTMAX_C(1) << 6) /// The flag for prompt. This is also reversed; the option clears the flag. #define BC_FLAG_P (UINTMAX_C(1) << 7) /// The flag for read prompt. This is also reversed; the option clears the flag. #define BC_FLAG_R (UINTMAX_C(1) << 8) /// The flag for a leading zero. #define BC_FLAG_Z (UINTMAX_C(1) << 9) /// The flag for stdin being a TTY. #define BC_FLAG_TTYIN (UINTMAX_C(1) << 10) /// The flag for TTY mode. #define BC_FLAG_TTY (UINTMAX_C(1) << 11) /// The flag for reset on SIGINT. #define BC_FLAG_SIGINT (UINTMAX_C(1) << 12) /// The flag for exiting with expressions. #define BC_FLAG_EXPR_EXIT (UINTMAX_C(1) << 13) /// The flag for digit clamping. #define BC_FLAG_DIGIT_CLAMP (UINTMAX_C(1) << 14) /// A convenience macro for getting the TTYIN flag. #define BC_TTYIN (vm->flags & BC_FLAG_TTYIN) /// A convenience macro for getting the TTY flag. #define BC_TTY (vm->flags & BC_FLAG_TTY) /// A convenience macro for getting the SIGINT flag. #define BC_SIGINT (vm->flags & BC_FLAG_SIGINT) #if BC_ENABLED /// A convenience macro for getting the POSIX error flag. #define BC_S (vm->flags & BC_FLAG_S) /// A convenience macro for getting the POSIX warning flag. #define BC_W (vm->flags & BC_FLAG_W) /// A convenience macro for getting the math library flag. #define BC_L (vm->flags & BC_FLAG_L) /// A convenience macro for getting the global stacks flag. #define BC_G (vm->flags & BC_FLAG_G) #endif // BC_ENABLED #if DC_ENABLED /// A convenience macro for getting the extended register flag. #define DC_X (vm->flags & DC_FLAG_X) #endif // DC_ENABLED /// A convenience macro for getting the interactive flag. #define BC_I (vm->flags & BC_FLAG_I) /// A convenience macro for getting the prompt flag. #define BC_P (vm->flags & BC_FLAG_P) /// A convenience macro for getting the read prompt flag. #define BC_R (vm->flags & BC_FLAG_R) /// A convenience macro for getting the leading zero flag. #define BC_Z (vm->flags & BC_FLAG_Z) /// A convenience macro for getting the expression exit flag. #define BC_EXPR_EXIT (vm->flags & BC_FLAG_EXPR_EXIT) /// A convenience macro for getting the digit clamp flag. #define BC_DIGIT_CLAMP (vm->flags & BC_FLAG_DIGIT_CLAMP) #if BC_ENABLED /// A convenience macro for checking if bc is in POSIX mode. #define BC_IS_POSIX (BC_S || BC_W) #if DC_ENABLED /// Returns true if bc is running. #define BC_IS_BC (vm->name[0] != 'd') /// Returns true if dc is running. #define BC_IS_DC (vm->name[0] == 'd') /// Returns the correct read prompt. #define BC_VM_READ_PROMPT (BC_IS_BC ? "read> " : "?> ") /// Returns the string for the line length environment variable. #define BC_VM_LINE_LENGTH_STR (BC_IS_BC ? "BC_LINE_LENGTH" : "DC_LINE_LENGTH") /// Returns the string for the environment args environment variable. #define BC_VM_ENV_ARGS_STR (BC_IS_BC ? "BC_ENV_ARGS" : "DC_ENV_ARGS") /// Returns the string for the expression exit environment variable. #define BC_VM_EXPR_EXIT_STR (BC_IS_BC ? "BC_EXPR_EXIT" : "DC_EXPR_EXIT") /// Returns the default for the expression exit environment variable. #define BC_VM_EXPR_EXIT_DEF \ (BC_IS_BC ? BC_DEFAULT_EXPR_EXIT : DC_DEFAULT_EXPR_EXIT) /// Returns the string for the digit clamp environment variable. #define BC_VM_DIGIT_CLAMP_STR (BC_IS_BC ? "BC_DIGIT_CLAMP" : "DC_DIGIT_CLAMP") /// Returns the default for the digit clamp environment variable. #define BC_VM_DIGIT_CLAMP_DEF \ (BC_IS_BC ? BC_DEFAULT_DIGIT_CLAMP : DC_DEFAULT_DIGIT_CLAMP) /// Returns the string for the TTY mode environment variable. #define BC_VM_TTY_MODE_STR (BC_IS_BC ? "BC_TTY_MODE" : "DC_TTY_MODE") /// Returns the default for the TTY mode environment variable. #define BC_VM_TTY_MODE_DEF \ (BC_IS_BC ? BC_DEFAULT_TTY_MODE : DC_DEFAULT_TTY_MODE) /// Returns the string for the prompt environment variable. #define BC_VM_PROMPT_STR (BC_IS_BC ? "BC_PROMPT" : "DC_PROMPT") /// Returns the default for the prompt environment variable. #define BC_VM_PROMPT_DEF (BC_IS_BC ? BC_DEFAULT_PROMPT : DC_DEFAULT_PROMPT) /// Returns the string for the SIGINT reset environment variable. #define BC_VM_SIGINT_RESET_STR \ (BC_IS_BC ? "BC_SIGINT_RESET" : "DC_SIGINT_RESET") /// Returns the string for the SIGINT reset environment variable. #define BC_VM_SIGINT_RESET_DEF \ (BC_IS_BC ? BC_DEFAULT_SIGINT_RESET : DC_DEFAULT_SIGINT_RESET) /// Returns true if the calculator should run stdin. #define BC_VM_RUN_STDIN(has_file) (BC_IS_BC || !(has_file)) #else // DC_ENABLED /// Returns true if bc is running. #define BC_IS_BC (1) /// Returns true if dc is running. #define BC_IS_DC (0) /// Returns the correct read prompt. #define BC_VM_READ_PROMPT ("read> ") /// Returns the string for the line length environment variable. #define BC_VM_LINE_LENGTH_STR ("BC_LINE_LENGTH") /// Returns the string for the environment args environment variable. #define BC_VM_ENV_ARGS_STR ("BC_ENV_ARGS") /// Returns the string for the expression exit environment variable. #define BC_VM_EXPR_EXIT_STR ("BC_EXPR_EXIT") /// Returns the default for the expression exit environment variable. #define BC_VM_EXPR_EXIT_DEF (BC_DEFAULT_EXPR_EXIT) /// Returns the string for the digit clamp environment variable. #define BC_VM_DIGIT_CLAMP_STR ("BC_DIGIT_CLAMP") /// Returns the default for the digit clamp environment variable. #define BC_VM_DIGIT_CLAMP_DEF (BC_DEFAULT_DIGIT_CLAMP) /// Returns the string for the TTY mode environment variable. #define BC_VM_TTY_MODE_STR ("BC_TTY_MODE") /// Returns the default for the TTY mode environment variable. #define BC_VM_TTY_MODE_DEF (BC_DEFAULT_TTY_MODE) /// Returns the string for the prompt environment variable. #define BC_VM_PROMPT_STR ("BC_PROMPT") /// Returns the default for the SIGINT reset environment variable. #define BC_VM_PROMPT_DEF (BC_DEFAULT_PROMPT) /// Returns the string for the SIGINT reset environment variable. #define BC_VM_SIGINT_RESET_STR ("BC_SIGINT_RESET") /// Returns the string for the SIGINT reset environment variable. #define BC_VM_SIGINT_RESET_DEF (BC_DEFAULT_SIGINT_RESET) /// Returns true if the calculator should run stdin. #define BC_VM_RUN_STDIN(has_file) (BC_IS_BC) #endif // DC_ENABLED #else // BC_ENABLED /// A convenience macro for checking if bc is in POSIX mode. #define BC_IS_POSIX (0) /// Returns true if bc is running. #define BC_IS_BC (0) /// Returns true if dc is running. #define BC_IS_DC (1) /// Returns the correct read prompt. #define BC_VM_READ_PROMPT ("?> ") /// Returns the string for the line length environment variable. #define BC_VM_LINE_LENGTH_STR ("DC_LINE_LENGTH") /// Returns the string for the environment args environment variable. #define BC_VM_ENV_ARGS_STR ("DC_ENV_ARGS") /// Returns the string for the expression exit environment variable. #define BC_VM_EXPR_EXIT_STR ("DC_EXPR_EXIT") /// Returns the default for the expression exit environment variable. #define BC_VM_EXPR_EXIT_DEF (DC_DEFAULT_EXPR_EXIT) /// Returns the string for the digit clamp environment variable. #define BC_VM_DIGIT_CLAMP_STR ("DC_DIGIT_CLAMP") /// Returns the default for the digit clamp environment variable. #define BC_VM_DIGIT_CLAMP_DEF (DC_DEFAULT_DIGIT_CLAMP) /// Returns the string for the TTY mode environment variable. #define BC_VM_TTY_MODE_STR ("DC_TTY_MODE") /// Returns the default for the TTY mode environment variable. #define BC_VM_TTY_MODE_DEF (DC_DEFAULT_TTY_MODE) /// Returns the string for the prompt environment variable. #define BC_VM_PROMPT_STR ("DC_PROMPT") /// Returns the default for the SIGINT reset environment variable. #define BC_VM_PROMPT_DEF (DC_DEFAULT_PROMPT) /// Returns the string for the SIGINT reset environment variable. #define BC_VM_SIGINT_RESET_STR ("DC_SIGINT_RESET") /// Returns the string for the SIGINT reset environment variable. #define BC_VM_SIGINT_RESET_DEF (DC_DEFAULT_SIGINT_RESET) /// Returns true if the calculator should run stdin. #define BC_VM_RUN_STDIN(has_file) (!(has_file)) #endif // BC_ENABLED /// A convenience macro for checking if the prompt is enabled. #define BC_PROMPT (BC_P) #else // !BC_ENABLE_LIBRARY #define BC_Z (vm->leading_zeroes) #define BC_DIGIT_CLAMP (vm->digit_clamp) #endif // !BC_ENABLE_LIBRARY /** * Returns the max of its two arguments. This evaluates arguments twice, so be * careful what args you give it. * @param a The first argument. * @param b The second argument. * @return The max of the two arguments. */ #define BC_MAX(a, b) ((a) > (b) ? (a) : (b)) /** * Returns the min of its two arguments. This evaluates arguments twice, so be * careful what args you give it. * @param a The first argument. * @param b The second argument. * @return The min of the two arguments. */ #define BC_MIN(a, b) ((a) < (b) ? (a) : (b)) /// Returns the max obase that is allowed. #define BC_MAX_OBASE ((BcBigDig) (BC_BASE_POW)) /// Returns the max array size that is allowed. #define BC_MAX_DIM ((BcBigDig) (SIZE_MAX - 1)) /// Returns the max scale that is allowed. #define BC_MAX_SCALE ((BcBigDig) (BC_NUM_BIGDIG_MAX - 1)) /// Returns the max string length that is allowed. #define BC_MAX_STRING ((BcBigDig) (BC_NUM_BIGDIG_MAX - 1)) /// Returns the max identifier length that is allowed. #define BC_MAX_NAME BC_MAX_STRING /// Returns the max number size that is allowed. #define BC_MAX_NUM BC_MAX_SCALE #if BC_ENABLE_EXTRA_MATH /// Returns the max random integer that can be returned. #define BC_MAX_RAND ((BcBigDig) (((BcRand) 0) - 1)) #endif // BC_ENABLE_EXTRA_MATH /// Returns the max exponent that is allowed. #define BC_MAX_EXP ((ulong) (BC_NUM_BIGDIG_MAX)) /// Returns the max number of variables that is allowed. #define BC_MAX_VARS ((ulong) (SIZE_MAX - 1)) #if BC_ENABLE_LINE_LIB /// The size of the global buffer. #define BC_VM_BUF_SIZE (1 << 10) /// The amount of the global buffer allocated to stdin. #define BC_VM_STDIN_BUF_SIZE (BC_VM_BUF_SIZE - 1) #else // BC_ENABLE_LINE_LIB /// The size of the global buffer. #define BC_VM_BUF_SIZE (1 << 12) /// The amount of the global buffer allocated to stdout. #define BC_VM_STDOUT_BUF_SIZE (1 << 11) /// The amount of the global buffer allocated to stderr. #define BC_VM_STDERR_BUF_SIZE (1 << 10) /// The amount of the global buffer allocated to stdin. #define BC_VM_STDIN_BUF_SIZE (BC_VM_STDERR_BUF_SIZE - 1) #endif // BC_ENABLE_LINE_LIB /// The max number of temporary BcNums that can be kept. #define BC_VM_MAX_TEMPS (1 << 9) /// The capacity of the one BcNum, which is a constant. #define BC_VM_ONE_CAP (1) /** * Returns true if a BcResult is safe for garbage collection. * @param r The BcResult to test. * @return True if @a r is safe to garbage collect. */ #define BC_VM_SAFE_RESULT(r) ((r)->t >= BC_RESULT_TEMP) /// The invalid locale catalog return value. #define BC_VM_INVALID_CATALOG ((nl_catd) -1) /** * Returns true if the *unsigned* multiplication overflows. * @param a The first operand. * @param b The second operand. * @param r The product. * @return True if the multiplication of @a a and @a b overflows. */ #define BC_VM_MUL_OVERFLOW(a, b, r) \ ((r) >= SIZE_MAX || ((a) != 0 && (r) / (a) != (b))) /// The global vm struct. This holds all of the global data besides the file /// buffers. typedef struct BcVm { /// The current status. This is volatile sig_atomic_t because it is also /// used in the signal handler. See the development manual /// (manuals/development.md#async-signal-safe-signal-handling) for more /// information. volatile sig_atomic_t status; /// Non-zero if a jump series is in progress and items should be popped off /// the jmp_bufs vector. This is volatile sig_atomic_t because it is also /// used in the signal handler. See the development manual /// (manuals/development.md#async-signal-safe-signal-handling) for more /// information. volatile sig_atomic_t sig_pop; #if !BC_ENABLE_LIBRARY /// The parser. BcParse prs; /// The program. BcProgram prog; /// A buffer for lines for stdin. BcVec line_buf; /// A buffer to hold a series of lines from stdin. Sometimes, multiple lines /// are necessary for parsing, such as a comment that spans multiple lines. BcVec buffer; /// A parser to parse read expressions. BcParse read_prs; /// A buffer for read expressions. BcVec read_buf; #endif // !BC_ENABLE_LIBRARY /// A vector of jmp_bufs for doing a jump series. This allows exception-type /// error handling, while allowing me to do cleanup on the way. BcVec jmp_bufs; /// The number of temps in the temps array. size_t temps_len; #if BC_ENABLE_LIBRARY /// The vector of contexts for the library. BcVec ctxts; /// The vector for creating strings to pass to the client. BcVec out; +#if BC_ENABLE_EXTRA_MATH + /// The PRNG. BcRNG rng; +#endif // BC_ENABLE_EXTRA_MATH + /// The current error. BclError err; /// Whether or not bcl should abort on fatal errors. bool abrt; /// Whether or not to print leading zeros. bool leading_zeroes; /// Whether or not to clamp digits that are greater than or equal to the /// current ibase. bool digit_clamp; /// The number of "references," or times that the library was initialized. unsigned int refs; #else // BC_ENABLE_LIBRARY /// A pointer to the filename of the current file. This is not owned by the /// BcVm struct. const char* file; /// The message printed when SIGINT happens. const char* sigmsg; /// Non-zero when signals are "locked." This is volatile sig_atomic_t /// because it is also used in the signal handler. See the development /// manual (manuals/development.md#async-signal-safe-signal-handling) for /// more information. volatile sig_atomic_t sig_lock; /// Non-zero when a signal has been received, but not acted on. This is /// volatile sig_atomic_t because it is also used in the signal handler. See /// the development manual /// (manuals/development.md#async-signal-safe-signal-handling) for more /// information. volatile sig_atomic_t sig; /// The length of sigmsg. uchar siglen; /// The instruction used for returning from a read() call. uchar read_ret; /// The flags field used by most macros above. uint16_t flags; /// The number of characters printed in the current line. This is used /// because bc has a limit of the number of characters it can print per /// line. uint16_t nchars; /// The length of the line we can print. The user can set this if they wish. uint16_t line_len; /// True if bc should error if expressions are encountered during option /// parsing, false otherwise. bool no_exprs; /// True if bc should exit if expresions are encountered. bool exit_exprs; /// True if EOF was encountered. bool eof; /// The mode that the program is in. uchar mode; #if BC_ENABLED /// True if keywords should not be redefined. This is only true for the /// builtin math libraries for bc. bool no_redefine; #endif // BC_ENABLED /// A vector of filenames to process. BcVec files; /// A vector of expressions to process. BcVec exprs; /// The name of the calculator under use. This is used by BC_IS_BC and /// BC_IS_DC. const char* name; /// The help text for the calculator. const char* help; #if BC_ENABLE_HISTORY /// The history data. BcHistory history; #endif // BC_ENABLE_HISTORY /// The function to call to get the next lex token. BcLexNext next; /// The function to call to parse. BcParseParse parse; /// The function to call to parse expressions. BcParseExpr expr; /// The names of the categories of errors. const char* err_ids[BC_ERR_IDX_NELEMS + BC_ENABLED]; /// The messages for each error. const char* err_msgs[BC_ERR_NELEMS]; #if BC_ENABLE_NLS /// The locale. const char* locale; #endif // BC_ENABLE_NLS #endif // BC_ENABLE_LIBRARY /// An array of maxes for the globals. BcBigDig maxes[BC_PROG_GLOBALS_LEN + BC_ENABLE_EXTRA_MATH]; /// The last base used to parse. BcBigDig last_base; /// The last power of last_base used to parse. BcBigDig last_pow; /// The last exponent of base that equals last_pow. BcBigDig last_exp; /// BC_BASE_POW - last_pow. BcBigDig last_rem; #if !BC_ENABLE_LIBRARY /// A buffer of environment arguments. This is the actual value of the /// environment variable. char* env_args_buffer; /// A vector for environment arguments after parsing. BcVec env_args; /// A BcNum set to constant 0. BcNum zero; #endif // !BC_ENABLE_LIBRARY /// A BcNum set to constant 1. BcNum one; /// A BcNum holding the max number held by a BcBigDig plus 1. BcNum max; /// A BcNum holding the max number held by a BcBigDig times 2 plus 1. BcNum max2; /// The BcDig array for max. BcDig max_num[BC_NUM_BIGDIG_LOG10]; /// The BcDig array for max2. BcDig max2_num[BC_NUM_BIGDIG_LOG10]; // The BcDig array for the one BcNum. BcDig one_num[BC_VM_ONE_CAP]; #if !BC_ENABLE_LIBRARY // The BcDig array for the zero BcNum. BcDig zero_num[BC_VM_ONE_CAP]; /// The stdout file. BcFile fout; /// The stderr file. BcFile ferr; #if BC_ENABLE_NLS /// The locale catalog. nl_catd catalog; #endif // BC_ENABLE_NLS /// A pointer to the stdin buffer. char* buf; /// The number of items in the input buffer. size_t buf_len; /// The slabs vector for constants, strings, function names, and other /// string-like things. BcVec slabs; #if BC_ENABLED /// An array of booleans for which bc keywords have been redefined if /// BC_REDEFINE_KEYWORDS is non-zero. bool redefined_kws[BC_LEX_NKWS]; #endif // BC_ENABLED #endif // !BC_ENABLE_LIBRARY BcDig* temps_buf[BC_VM_MAX_TEMPS]; #if BC_DEBUG_CODE /// The depth for BC_FUNC_ENTER and BC_FUNC_EXIT. size_t func_depth; #endif // BC_DEBUG_CODE } BcVm; /** * Print the copyright banner and help if it's non-NULL. * @param help The help message to print if it's non-NULL. */ void bc_vm_info(const char* const help); /** * The entrance point for bc/dc together. * @param argc The count of arguments. * @param argv The argument array. */ void bc_vm_boot(int argc, char* argv[]); /** * Initializes some of the BcVm global. This is separate to make things easier * on the library code. */ void bc_vm_init(void); /** * Frees the BcVm global. */ void bc_vm_shutdown(void); /** * Add a temp to the temp array. * @param num The BcDig array to add to the temp array. */ void bc_vm_addTemp(BcDig* num); /** * Return the temp on the top of the temp stack, or NULL if there are none. * @return A temp, or NULL if none exist. */ BcDig* bc_vm_takeTemp(void); /** * Gets the top temp of the temp stack. This is separate from bc_vm_takeTemp() * to quiet a GCC warning about longjmp() clobbering in bc_num_init(). * @return A temp, or NULL if none exist. */ BcDig* bc_vm_getTemp(void); /** * Frees all temporaries. */ void bc_vm_freeTemps(void); #if !BC_ENABLE_HISTORY || BC_ENABLE_LINE_LIB || BC_ENABLE_LIBRARY /** * Erases the flush argument if history does not exist because it does not * matter if history does not exist. */ #define bc_vm_putchar(c, t) bc_vm_putchar_impl(c) #else // !BC_ENABLE_HISTORY || BC_ENABLE_LINE_LIB || BC_ENABLE_LIBRARY // This is here to satisfy a clang warning about recursive macros. #define bc_vm_putchar(c, t) bc_vm_putchar_impl(c, t) #endif // !BC_ENABLE_HISTORY || BC_ENABLE_LINE_LIB || BC_ENABLE_LIBRARY /** * Print to stdout with limited formating. * @param fmt The format string. */ void bc_vm_printf(const char* fmt, ...); /** * Puts a char into the stdout buffer. * @param c The character to put on the stdout buffer. * @param type The flush type. */ void bc_vm_putchar(int c, BcFlushType type); /** * Multiplies @a n and @a size and throws an allocation error if overflow * occurs. * @param n The number of elements. * @param size The size of each element. * @return The product of @a n and @a size. */ size_t bc_vm_arraySize(size_t n, size_t size); /** * Adds @a a and @a b and throws an error if overflow occurs. * @param a The first operand. * @param b The second operand. * @return The sum of @a a and @a b. */ size_t bc_vm_growSize(size_t a, size_t b); /** * Allocate @a n bytes and throw an allocation error if allocation fails. * @param n The bytes to allocate. * @return A pointer to the allocated memory. */ void* bc_vm_malloc(size_t n); /** * Reallocate @a ptr to be @a n bytes and throw an allocation error if * reallocation fails. * @param ptr The pointer to a memory allocation to reallocate. * @param n The bytes to allocate. * @return A pointer to the reallocated memory. */ void* bc_vm_realloc(void* ptr, size_t n); /** * Allocates space for, and duplicates, @a str. * @param str The string to allocate. * @return The allocated string. */ char* bc_vm_strdup(const char* str); /** * Reads a line from stdin into BcVm's buffer field. * @param clear True if the buffer should be cleared first, false otherwise. * @return True if a line was read, false otherwise. */ bool bc_vm_readLine(bool clear); /** * Reads a line from the command-line expressions into BcVm's buffer field. * @param clear True if the buffer should be cleared first, false otherwise. * @return True if a line was read, false otherwise. */ bool bc_vm_readBuf(bool clear); /** * A convenience and portability function for OpenBSD's pledge(). * @param promises The promises to pledge(). * @param execpromises The exec promises to pledge(). */ void bc_pledge(const char* promises, const char* execpromises); /** * Returns the value of an environment variable. * @param var The environment variable. * @return The value of the environment variable. */ char* bc_vm_getenv(const char* var); /** * Frees an environment variable value. * @param val The value to free. */ void bc_vm_getenvFree(char* val); #if BC_DEBUG_CODE /** * Start executing a jump series. * @param f The name of the function that started the jump series. */ void bc_vm_jmp(const char* f); #else // BC_DEBUG_CODE /** * Start executing a jump series. */ void bc_vm_jmp(void); #endif // BC_DEBUG_CODE #if BC_ENABLE_LIBRARY /** * Handle an error. This is the true error handler. It will start a jump series * if an error occurred. POSIX errors will not cause jumps when warnings are on * or no POSIX errors are enabled. * @param e The error. */ void bc_vm_handleError(BcErr e); /** * Handle a fatal error. * @param e The error. */ void bc_vm_fatalError(BcErr e); /** * A function to call at exit. */ void bc_vm_atexit(void); #else // BC_ENABLE_LIBRARY /** * Calculates the number of decimal digits in the argument. * @param val The value to calculate the number of decimal digits in. * @return The number of decimal digits in @a val. */ size_t bc_vm_numDigits(size_t val); #if BC_DEBUG /** * Handle an error. This is the true error handler. It will start a jump series * if an error occurred. POSIX errors will not cause jumps when warnings are on * or no POSIX errors are enabled. * @param e The error. * @param file The source file where the error occurred. * @param fline The line in the source file where the error occurred. * @param line The bc source line where the error occurred. */ void bc_vm_handleError(BcErr e, const char* file, int fline, size_t line, ...); #else // BC_DEBUG /** * Handle an error. This is the true error handler. It will start a jump series * if an error occurred. POSIX errors will not cause jumps when warnings are on * or no POSIX errors are enabled. * @param e The error. * @param line The bc source line where the error occurred. */ void bc_vm_handleError(BcErr e, size_t line, ...); #endif // BC_DEBUG /** * Handle a fatal error. * @param e The error. */ #if !BC_ENABLE_MEMCHECK BC_NORETURN #endif // !BC_ENABLE_MEMCHECK void bc_vm_fatalError(BcErr e); /** * A function to call at exit. * @param status The exit status. */ int bc_vm_atexit(int status); #endif // BC_ENABLE_LIBRARY /// A reference to the copyright header. extern const char bc_copyright[]; /// A reference to the array of default error category names. extern const char* bc_errs[]; /// A reference to the array of error category indices for each error. extern const uchar bc_err_ids[]; /// A reference to the array of default error messages. extern const char* const bc_err_msgs[]; /// A reference to the pledge() promises at start. extern const char bc_pledge_start[]; #if BC_ENABLE_HISTORY /// A reference to the end pledge() promises when using history. extern const char bc_pledge_end_history[]; #endif // BC_ENABLE_HISTORY /// A reference to the end pledge() promises when *not* using history. extern const char bc_pledge_end[]; #if !BC_ENABLE_LIBRARY /// A reference to the global data. extern BcVm* vm; /// The global data. extern BcVm vm_data; /// A reference to the global output buffers. extern char output_bufs[BC_VM_BUF_SIZE]; #endif // !BC_ENABLE_LIBRARY #endif // BC_VM_H diff --git a/contrib/bc/manuals/bcl.3 b/contrib/bc/manuals/bcl.3 index 5c3731a141eb..cb65a2b8b991 100644 --- a/contrib/bc/manuals/bcl.3 +++ b/contrib/bc/manuals/bcl.3 @@ -1,1453 +1,1867 @@ .\" .\" SPDX-License-Identifier: BSD-2-Clause .\" .\" Copyright (c) 2018-2023 Gavin D. Howard and contributors. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions are met: .\" .\" * Redistributions of source code must retain the above copyright notice, .\" this list of conditions and the following disclaimer. .\" .\" * Redistributions in binary form must reproduce the above copyright notice, .\" this list of conditions and the following disclaimer in the documentation .\" and/or other materials provided with the distribution. .\" .\" THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" .\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE .\" LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR .\" CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF .\" SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS .\" INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN .\" CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) .\" ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE .\" POSSIBILITY OF SUCH DAMAGE. .\" .TH "BCL" "3" "February 2023" "Gavin D. Howard" "Libraries Manual" .nh .ad l .SH NAME .PP bcl - library of arbitrary precision decimal arithmetic .SH SYNOPSIS .SS Use .PP \f[I]#include \f[R] .PP Link with \f[I]-lbcl\f[R], and on POSIX systems, \f[I]-lpthread\f[R] is also required. .SS Setup .PP These items allow clients to set up bcl(3). .PP \f[B]BclError bcl_start(\f[R]\f[I]void\f[R]\f[B]);\f[R] .PP \f[B]void bcl_end(\f[R]\f[I]void\f[R]\f[B]);\f[R] .PP \f[B]BclError bcl_init(\f[R]\f[I]void\f[R]\f[B]);\f[R] .PP \f[B]void bcl_free(\f[R]\f[I]void\f[R]\f[B]);\f[R] .PP \f[B]bool bcl_abortOnFatalError(\f[R]\f[I]void\f[R]\f[B]);\f[R] .PP \f[B]void bcl_setAbortOnFatalError(bool\f[R] \f[I]abrt\f[R]\f[B]);\f[R] .PP \f[B]bool bcl_leadingZeroes(\f[R]\f[I]void\f[R]\f[B]);\f[R] .PP \f[B]void bcl_setLeadingZeroes(bool\f[R] \f[I]leadingZeroes\f[R]\f[B]);\f[R] .PP \f[B]void bcl_gc(\f[R]\f[I]void\f[R]\f[B]);\f[R] .PP \f[B]bool bcl_digitClamp(\f[R]\f[I]void\f[R]\f[B]);\f[R] .PP \f[B]void bcl_setDigitClamp(bool\f[R] \f[I]digitClamp\f[R]\f[B]);\f[R] .SS Contexts .PP These items will allow clients to handle contexts, which are isolated from each other. This allows more than one client to use bcl(3) in the same program. .PP \f[B]struct BclCtxt;\f[R] .PP \f[B]typedef struct BclCtxt* BclContext;\f[R] .PP \f[B]BclContext bcl_ctxt_create(\f[R]\f[I]void\f[R]\f[B]);\f[R] .PP \f[B]void bcl_ctxt_free(BclContext\f[R] \f[I]ctxt\f[R]\f[B]);\f[R] .PP \f[B]BclError bcl_pushContext(BclContext\f[R] \f[I]ctxt\f[R]\f[B]);\f[R] .PP \f[B]void bcl_popContext(\f[R]\f[I]void\f[R]\f[B]);\f[R] .PP \f[B]BclContext bcl_context(\f[R]\f[I]void\f[R]\f[B]);\f[R] .PP \f[B]void bcl_ctxt_freeNums(BclContext\f[R] \f[I]ctxt\f[R]\f[B]);\f[R] .PP \f[B]size_t bcl_ctxt_scale(BclContext\f[R] \f[I]ctxt\f[R]\f[B]);\f[R] .PP \f[B]void bcl_ctxt_setScale(BclContext\f[R] \f[I]ctxt\f[R]\f[B], size_t\f[R] \f[I]scale\f[R]\f[B]);\f[R] .PP \f[B]size_t bcl_ctxt_ibase(BclContext\f[R] \f[I]ctxt\f[R]\f[B]);\f[R] .PP \f[B]void bcl_ctxt_setIbase(BclContext\f[R] \f[I]ctxt\f[R]\f[B], size_t\f[R] \f[I]ibase\f[R]\f[B]);\f[R] .PP \f[B]size_t bcl_ctxt_obase(BclContext\f[R] \f[I]ctxt\f[R]\f[B]);\f[R] .PP \f[B]void bcl_ctxt_setObase(BclContext\f[R] \f[I]ctxt\f[R]\f[B], size_t\f[R] \f[I]obase\f[R]\f[B]);\f[R] .SS Errors .PP These items allow clients to handle errors. .PP \f[B]typedef enum BclError BclError;\f[R] .PP \f[B]BclError bcl_err(BclNumber\f[R] \f[I]n\f[R]\f[B]);\f[R] .SS Numbers .PP These items allow clients to manipulate and query the arbitrary-precision numbers managed by bcl(3). .PP \f[B]typedef struct { size_t i; } BclNumber;\f[R] .PP \f[B]BclNumber bcl_num_create(\f[R]\f[I]void\f[R]\f[B]);\f[R] .PP \f[B]void bcl_num_free(BclNumber\f[R] \f[I]n\f[R]\f[B]);\f[R] .PP \f[B]bool bcl_num_neg(BclNumber\f[R] \f[I]n\f[R]\f[B]);\f[R] .PP \f[B]void bcl_num_setNeg(BclNumber\f[R] \f[I]n\f[R]\f[B], bool\f[R] \f[I]neg\f[R]\f[B]);\f[R] .PP \f[B]size_t bcl_num_scale(BclNumber\f[R] \f[I]n\f[R]\f[B]);\f[R] .PP \f[B]BclError bcl_num_setScale(BclNumber\f[R] \f[I]n\f[R]\f[B], size_t\f[R] \f[I]scale\f[R]\f[B]);\f[R] .PP \f[B]size_t bcl_num_len(BclNumber\f[R] \f[I]n\f[R]\f[B]);\f[R] .SS Conversion .PP These items allow clients to convert numbers into and from strings and integers. .PP \f[B]BclNumber bcl_parse(const char *restrict\f[R] \f[I]val\f[R]\f[B]);\f[R] .PP \f[B]char* bcl_string(BclNumber\f[R] \f[I]n\f[R]\f[B]);\f[R] .PP +\f[B]char* bcl_string_keep(BclNumber\f[R] \f[I]n\f[R]\f[B]);\f[R] +.PP \f[B]BclError bcl_bigdig(BclNumber\f[R] \f[I]n\f[R]\f[B], BclBigDig *\f[R]\f[I]result\f[R]\f[B]);\f[R] .PP +\f[B]BclError bcl_bigdig_keep(BclNumber\f[R] \f[I]n\f[R]\f[B], BclBigDig +*\f[R]\f[I]result\f[R]\f[B]);\f[R] +.PP \f[B]BclNumber bcl_bigdig2num(BclBigDig\f[R] \f[I]val\f[R]\f[B]);\f[R] .SS Math .PP These items allow clients to run math on numbers. .PP \f[B]BclNumber bcl_add(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B]);\f[R] .PP +\f[B]BclNumber bcl_add_keep(BclNumber\f[R] \f[I]a\f[R]\f[B], +BclNumber\f[R] \f[I]b\f[R]\f[B]);\f[R] +.PP \f[B]BclNumber bcl_sub(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B]);\f[R] .PP +\f[B]BclNumber bcl_sub_keep(BclNumber\f[R] \f[I]a\f[R]\f[B], +BclNumber\f[R] \f[I]b\f[R]\f[B]);\f[R] +.PP \f[B]BclNumber bcl_mul(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B]);\f[R] .PP +\f[B]BclNumber bcl_mul_keep(BclNumber\f[R] \f[I]a\f[R]\f[B], +BclNumber\f[R] \f[I]b\f[R]\f[B]);\f[R] +.PP \f[B]BclNumber bcl_div(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B]);\f[R] .PP +\f[B]BclNumber bcl_div_keep(BclNumber\f[R] \f[I]a\f[R]\f[B], +BclNumber\f[R] \f[I]b\f[R]\f[B]);\f[R] +.PP \f[B]BclNumber bcl_mod(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B]);\f[R] .PP +\f[B]BclNumber bcl_mod_keep(BclNumber\f[R] \f[I]a\f[R]\f[B], +BclNumber\f[R] \f[I]b\f[R]\f[B]);\f[R] +.PP \f[B]BclNumber bcl_pow(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B]);\f[R] .PP +\f[B]BclNumber bcl_pow_keep(BclNumber\f[R] \f[I]a\f[R]\f[B], +BclNumber\f[R] \f[I]b\f[R]\f[B]);\f[R] +.PP \f[B]BclNumber bcl_lshift(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B]);\f[R] .PP +\f[B]BclNumber bcl_lshift_keep(BclNumber\f[R] \f[I]a\f[R]\f[B], +BclNumber\f[R] \f[I]b\f[R]\f[B]);\f[R] +.PP \f[B]BclNumber bcl_rshift(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B]);\f[R] .PP +\f[B]BclNumber bcl_rshift_keep(BclNumber\f[R] \f[I]a\f[R]\f[B], +BclNumber\f[R] \f[I]b\f[R]\f[B]);\f[R] +.PP \f[B]BclNumber bcl_sqrt(BclNumber\f[R] \f[I]a\f[R]\f[B]);\f[R] .PP +\f[B]BclNumber bcl_sqrt_keep(BclNumber\f[R] \f[I]a\f[R]\f[B]);\f[R] +.PP \f[B]BclError bcl_divmod(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B], BclNumber *\f[R]\f[I]c\f[R]\f[B], BclNumber *\f[R]\f[I]d\f[R]\f[B]);\f[R] .PP +\f[B]BclError bcl_divmod_keep(BclNumber\f[R] \f[I]a\f[R]\f[B], +BclNumber\f[R] \f[I]b\f[R]\f[B], BclNumber *\f[R]\f[I]c\f[R]\f[B], +BclNumber *\f[R]\f[I]d\f[R]\f[B]);\f[R] +.PP \f[B]BclNumber bcl_modexp(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B], BclNumber\f[R] \f[I]c\f[R]\f[B]);\f[R] +.PP +\f[B]BclNumber bcl_modexp_keep(BclNumber\f[R] \f[I]a\f[R]\f[B], +BclNumber\f[R] \f[I]b\f[R]\f[B], BclNumber\f[R] \f[I]c\f[R]\f[B]);\f[R] .SS Miscellaneous .PP These items are miscellaneous. .PP \f[B]void bcl_zero(BclNumber\f[R] \f[I]n\f[R]\f[B]);\f[R] .PP \f[B]void bcl_one(BclNumber\f[R] \f[I]n\f[R]\f[B]);\f[R] .PP \f[B]ssize_t bcl_cmp(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B]);\f[R] .PP \f[B]BclError bcl_copy(BclNumber\f[R] \f[I]d\f[R]\f[B], BclNumber\f[R] \f[I]s\f[R]\f[B]);\f[R] .PP \f[B]BclNumber bcl_dup(BclNumber\f[R] \f[I]s\f[R]\f[B]);\f[R] .SS Pseudo-Random Number Generator .PP These items allow clients to manipulate the seeded pseudo-random number generator in bcl(3). .PP \f[B]#define BCL_SEED_ULONGS\f[R] .PP \f[B]#define BCL_SEED_SIZE\f[R] .PP \f[B]typedef unsigned long BclBigDig;\f[R] .PP \f[B]typedef unsigned long BclRandInt;\f[R] .PP \f[B]BclNumber bcl_irand(BclNumber\f[R] \f[I]a\f[R]\f[B]);\f[R] .PP +\f[B]BclNumber bcl_irand_keep(BclNumber\f[R] \f[I]a\f[R]\f[B]);\f[R] +.PP \f[B]BclNumber bcl_frand(size_t\f[R] \f[I]places\f[R]\f[B]);\f[R] .PP \f[B]BclNumber bcl_ifrand(BclNumber\f[R] \f[I]a\f[R]\f[B], size_t\f[R] \f[I]places\f[R]\f[B]);\f[R] .PP +\f[B]BclNumber bcl_ifrand_keep(BclNumber\f[R] \f[I]a\f[R]\f[B], +size_t\f[R] \f[I]places\f[R]\f[B]);\f[R] +.PP \f[B]BclError bcl_rand_seedWithNum(BclNumber\f[R] \f[I]n\f[R]\f[B]);\f[R] .PP +\f[B]BclError bcl_rand_seedWithNum_keep(BclNumber\f[R] +\f[I]n\f[R]\f[B]);\f[R] +.PP \f[B]BclError bcl_rand_seed(unsigned char\f[R] \f[I]seed\f[R]\f[B][\f[R]\f[I]BCL_SEED_SIZE\f[R]\f[B]]);\f[R] .PP \f[B]void bcl_rand_reseed(\f[R]\f[I]void\f[R]\f[B]);\f[R] .PP \f[B]BclNumber bcl_rand_seed2num(\f[R]\f[I]void\f[R]\f[B]);\f[R] .PP \f[B]BclRandInt bcl_rand_int(\f[R]\f[I]void\f[R]\f[B]);\f[R] .PP \f[B]BclRandInt bcl_rand_bounded(BclRandInt\f[R] \f[I]bound\f[R]\f[B]);\f[R] .SH DESCRIPTION .PP bcl(3) is a library that implements arbitrary-precision decimal math, as standardized by POSIX (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) in bc(1). .PP bcl(3) assumes that it is allowed to use the \f[B]bcl\f[R], \f[B]Bcl\f[R], \f[B]bc\f[R], and \f[B]Bc\f[R] prefixes for symbol names without collision. .PP All of the items in its interface are described below. See the documentation for each function for what each function can return. .SS Setup .TP \f[B]BclError bcl_start(\f[R]\f[I]void\f[R]\f[B])\f[R] Initializes this library. This function can be called multiple times, but \f[B]bcl_end()\f[R] must only be called \f[I]once\f[R]. This is to make it possible for multiple libraries and applications to initialize bcl(3) without problem. .RS .PP It is suggested that client libraries call this function, but do not call \f[B]bcl_end()\f[R], and client applications should call both. .PP If there was no error, \f[B]BCL_ERROR_NONE\f[R] is returned. Otherwise, this function can return: .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .PP This function must be the first one clients call. Calling any other function without calling this one first is undefined behavior. .RE .TP \f[B]void bcl_end(\f[R]\f[I]void\f[R]\f[B])\f[R] Deinitializes this library. This function must only be called \f[I]once\f[R]. .RS .PP All data must have been freed before calling this function. .PP This function must be the last one clients call. Calling this function before calling any other function is undefined behavior. .RE .TP \f[B]BclError bcl_init(\f[R]\f[I]void\f[R]\f[B])\f[R] Initializes the library for the current thread. This function can be called multiple times, but each call must be matched by a call to \f[B]bcl_free(\f[R]\f[I]void\f[R]\f[B])\f[R]. This is to make it possible for multiple libraries and applications to initialize threads for bcl(3) without problem. .RS .PP This function \f[I]must\f[R] be called from the thread that it is supposed to initialize. .PP If there was no error, \f[B]BCL_ERROR_NONE\f[R] is returned. Otherwise, this function can return: .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .PP This function must be the second one clients call. Calling any other function without calling \f[B]bcl_start()\f[R] and then this one first is undefined behavior, except in the case of new threads. New threads can safely call this function without calling \f[B]bcl_start()\f[R] if another thread has previously called \f[B]bcl_start()\f[R]. But this function must still be the first function in bcl(3) called by that new thread. .RE .TP \f[B]void bcl_free(\f[R]\f[I]void\f[R]\f[B])\f[R] Decrements bcl(3)\[cq]s reference count and frees the data associated with it if the reference count is \f[B]0\f[R]. .RS .PP This function \f[I]must\f[R] be called from the thread that it is supposed to deinitialize. .PP This function must be the second to last one clients call. Calling this function before calling any other function besides \f[B]bcl_end()\f[R] is undefined behavior. .RE .TP \f[B]bool bcl_abortOnFatalError(\f[R]\f[I]void\f[R]\f[B])\f[R] Queries and returns the current state of calling \f[B]abort()\f[R] on fatal errors. If \f[B]true\f[R] is returned, bcl(3) will cause a \f[B]SIGABRT\f[R] if a fatal error occurs. .RS .PP If activated, clients do not need to check for fatal errors. .PP This value is \f[I]thread-local\f[R]; it applies to just the thread it is read on. .PP The default is \f[B]false\f[R]. .RE .TP \f[B]void bcl_setAbortOnFatalError(bool\f[R] \f[I]abrt\f[R]\f[B])\f[R] Sets the state of calling \f[B]abort()\f[R] on fatal errors. If \f[I]abrt\f[R] is \f[B]false\f[R], bcl(3) will not cause a \f[B]SIGABRT\f[R] on fatal errors after the call. If \f[I]abrt\f[R] is \f[B]true\f[R], bcl(3) will cause a \f[B]SIGABRT\f[R] on fatal errors after the call. .RS .PP This value is \f[I]thread-local\f[R]; it applies to just the thread it is set on. .PP If activated, clients do not need to check for fatal errors. .RE .TP \f[B]bool bcl_leadingZeroes(\f[R]\f[I]void\f[R]\f[B])\f[R] Queries and returns the state of whether leading zeroes are added to strings returned by \f[B]bcl_string()\f[R] when numbers are greater than \f[B]-1\f[R], less than \f[B]1\f[R], and not equal to \f[B]0\f[R]. If \f[B]true\f[R] is returned, then leading zeroes will be added. .RS .PP This value is \f[I]thread-local\f[R]; it applies to just the thread it is read on. .PP The default is \f[B]false\f[R]. .RE .TP \f[B]void bcl_setLeadingZeroes(bool\f[R] \f[I]leadingZeroes\f[R]\f[B])\f[R] Sets the state of whether leading zeroes are added to strings returned by \f[B]bcl_string()\f[R] when numbers are greater than \f[B]-1\f[R], less than \f[B]1\f[R], and not equal to \f[B]0\f[R]. If \f[I]leadingZeroes\f[R] is \f[B]true\f[R], leading zeroes will be added to strings returned by \f[B]bcl_string()\f[R]. .RS .PP This value is \f[I]thread-local\f[R]; it applies to just the thread it is set on. .RE .TP \f[B]bool bcl_digitClamp(\f[R]\f[I]void\f[R]\f[B])\f[R] Queries and returns the state of whether digits in number strings that are greater than or equal to the current \f[B]ibase\f[R] are clamped or not. .RS .PP If \f[B]true\f[R] is returned, then digits are treated as though they are equal to the value of \f[B]ibase\f[R] minus \f[B]1\f[R]. If this is \f[I]not\f[R] true, then digits are treated as though they are equal to the value they would have if \f[B]ibase\f[R] was large enough. They are then multiplied by the appropriate power of \f[B]ibase\f[R]. .PP For example, with clamping off and an \f[B]ibase\f[R] of \f[B]3\f[R], the string \[lq]AB\[rq] would equal \f[B]3\[ha]1*A+3\[ha]0*B\f[R], which is \f[B]3\f[R] times \f[B]10\f[R] plus \f[B]11\f[R], or \f[B]41\f[R], while with clamping on and an \f[B]ibase\f[R] of \f[B]3\f[R], the string \[lq]AB\[rq] would be equal to \f[B]3\[ha]1*2+3\[ha]0*2\f[R], which is \f[B]3\f[R] times \f[B]2\f[R] plus \f[B]2\f[R], or \f[B]8\f[R]. .PP This value is \f[I]thread-local\f[R]; it applies to just the thread it is read on. .PP The default is \f[B]true\f[R]. .RE .TP \f[B]void bcl_setDigitClamp(bool\f[R] \f[I]digitClamp\f[R]\f[B])\f[R] Sets the state of whether digits in number strings that are greater than or equal to the current \f[B]ibase\f[R] are clamped or not. For more information, see the \f[B]bcl_digitClamp(\f[R]\f[I]void\f[R]\f[B])\f[R] function. .RS .PP This value is \f[I]thread-local\f[R]; it applies to just the thread it is set on. .RE .TP \f[B]void bcl_gc(\f[R]\f[I]void\f[R]\f[B])\f[R] Garbage collects cached instances of arbitrary-precision numbers. This only frees the memory of numbers that are \f[I]not\f[R] in use, so it is safe to call at any time. .SS Contexts .PP All procedures that take a \f[B]BclContext\f[R] parameter a require a valid context as an argument. .TP \f[B]struct BclCtxt\f[R] A forward declaration for a hidden \f[B]struct\f[R] type. Clients cannot access the internals of the \f[B]struct\f[R] type directly. All interactions with the type are done through pointers. See \f[B]BclContext\f[R] below. .TP \f[B]BclContext\f[R] A typedef to a pointer of \f[B]struct BclCtxt\f[R]. This is the only handle clients can get to \f[B]struct BclCtxt\f[R]. .RS .PP A \f[B]BclContext\f[R] contains the values \f[B]scale\f[R], \f[B]ibase\f[R], and \f[B]obase\f[R], as well as a list of numbers. .PP \f[B]scale\f[R] is a value used to control how many decimal places calculations should use. A value of \f[B]0\f[R] means that calculations are done on integers only, where applicable, and a value of 20, for example, means that all applicable calculations return results with 20 decimal places. The default is \f[B]0\f[R]. .PP \f[B]ibase\f[R] is a value used to control the input base. The minimum \f[B]ibase\f[R] is \f[B]2\f[R], and the maximum is \f[B]36\f[R]. If \f[B]ibase\f[R] is \f[B]2\f[R], numbers are parsed as though they are in binary, and any digits larger than \f[B]1\f[R] are clamped. Likewise, a value of \f[B]10\f[R] means that numbers are parsed as though they are decimal, and any larger digits are clamped. The default is \f[B]10\f[R]. .PP \f[B]obase\f[R] is a value used to control the output base. The minimum \f[B]obase\f[R] is \f[B]0\f[R] and the maximum is \f[B]BC_BASE_MAX\f[R] (see the \f[B]LIMITS\f[R] section). .PP Numbers created in one context are not valid in another context. It is undefined behavior to use a number created in a different context. Contexts are meant to isolate the numbers used by different clients in the same application. .PP Different threads also have different contexts, so any numbers created in one thread are not valid in another thread. To pass values between contexts and threads, use \f[B]bcl_string()\f[R] to produce a string to pass around, and use \f[B]bcl_parse()\f[R] to parse the string. It is suggested that the \f[B]obase\f[R] used to create the string be passed around with the string and used as the \f[B]ibase\f[R] for \f[B]bcl_parse()\f[R] to ensure that the number will be the same. .RE .TP \f[B]BclContext bcl_ctxt_create(\f[R]\f[I]void\f[R]\f[B])\f[R] Creates a context and returns it. Returns \f[B]NULL\f[R] if there was an error. .TP \f[B]void bcl_ctxt_free(BclContext\f[R] \f[I]ctxt\f[R]\f[B])\f[R] Frees \f[I]ctxt\f[R], after which it is no longer valid. It is undefined behavior to attempt to use an invalid context. .TP \f[B]BclError bcl_pushContext(BclContext\f[R] \f[I]ctxt\f[R]\f[B])\f[R] Pushes \f[I]ctxt\f[R] onto bcl(3)\[cq]s stack of contexts. \f[I]ctxt\f[R] must have been created with \f[B]bcl_ctxt_create(\f[R]\f[I]void\f[R]\f[B])\f[R]. .RS .PP If there was no error, \f[B]BCL_ERROR_NONE\f[R] is returned. Otherwise, this function can return: .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .PP There \f[I]must\f[R] be a valid context to do any arithmetic. .RE .TP \f[B]void bcl_popContext(\f[R]\f[I]void\f[R]\f[B])\f[R] Pops the current context off of the stack, if one exists. .TP \f[B]BclContext bcl_context(\f[R]\f[I]void\f[R]\f[B])\f[R] Returns the current context, or \f[B]NULL\f[R] if no context exists. .TP \f[B]void bcl_ctxt_freeNums(BclContext\f[R] \f[I]ctxt\f[R]\f[B])\f[R] Frees all numbers in use that are associated with \f[I]ctxt\f[R]. It is undefined behavior to attempt to use a number associated with \f[I]ctxt\f[R] after calling this procedure unless such numbers have been created with \f[B]bcl_num_create(\f[R]\f[I]void\f[R]\f[B])\f[R] after calling this procedure. .TP \f[B]size_t bcl_ctxt_scale(BclContext\f[R] \f[I]ctxt\f[R]\f[B])\f[R] Returns the \f[B]scale\f[R] for given context. .TP \f[B]void bcl_ctxt_setScale(BclContext\f[R] \f[I]ctxt\f[R]\f[B], size_t\f[R] \f[I]scale\f[R]\f[B])\f[R] Sets the \f[B]scale\f[R] for the given context to the argument \f[I]scale\f[R]. .TP \f[B]size_t bcl_ctxt_ibase(BclContext\f[R] \f[I]ctxt\f[R]\f[B])\f[R] Returns the \f[B]ibase\f[R] for the given context. .TP \f[B]void bcl_ctxt_setIbase(BclContext\f[R] \f[I]ctxt\f[R]\f[B], size_t\f[R] \f[I]ibase\f[R]\f[B])\f[R] Sets the \f[B]ibase\f[R] for the given context to the argument \f[I]ibase\f[R]. If the argument \f[I]ibase\f[R] is invalid, it clamped, so an \f[I]ibase\f[R] of \f[B]0\f[R] or \f[B]1\f[R] is clamped to \f[B]2\f[R], and any values above \f[B]36\f[R] are clamped to \f[B]36\f[R]. .TP \f[B]size_t bcl_ctxt_obase(BclContext\f[R] \f[I]ctxt\f[R]\f[B])\f[R] Returns the \f[B]obase\f[R] for the given context. .TP \f[B]void bcl_ctxt_setObase(BclContext\f[R] \f[I]ctxt\f[R]\f[B], size_t\f[R] \f[I]obase\f[R]\f[B])\f[R] Sets the \f[B]obase\f[R] for the given context to the argument \f[I]obase\f[R]. .SS Errors .TP \f[B]BclError\f[R] An \f[B]enum\f[R] of possible error codes. See the \f[B]ERRORS\f[R] section for a complete listing the codes. .TP \f[B]BclError bcl_err(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R] Checks for errors in a \f[B]BclNumber\f[R]. All functions that can return a \f[B]BclNumber\f[R] can encode an error in the number, and this function will return the error, if any. If there was no error, it will return \f[B]BCL_ERROR_NONE\f[R]. .RS .PP There must be a valid current context. .RE .SS Numbers .PP All procedures in this section require a valid current context. .TP \f[B]BclNumber\f[R] A handle to an arbitrary-precision number. The actual number type is not exposed; the \f[B]BclNumber\f[R] handle is the only way clients can refer to instances of arbitrary-precision numbers. .TP \f[B]BclNumber bcl_num_create(\f[R]\f[I]void\f[R]\f[B])\f[R] Creates and returns a \f[B]BclNumber\f[R]. .RS .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP \f[B]void bcl_num_free(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R] Frees \f[I]n\f[R]. It is undefined behavior to use \f[I]n\f[R] after calling this function. .TP \f[B]bool bcl_num_neg(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R] Returns \f[B]true\f[R] if \f[I]n\f[R] is negative, \f[B]false\f[R] otherwise. .TP \f[B]void bcl_num_setNeg(BclNumber\f[R] \f[I]n\f[R]\f[B], bool\f[R] \f[I]neg\f[R]\f[B])\f[R] Sets \f[I]n\f[R]\[cq]s sign to \f[I]neg\f[R], where \f[B]true\f[R] is negative, and \f[B]false\f[R] is positive. .TP \f[B]size_t bcl_num_scale(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R] Returns the \f[I]scale\f[R] of \f[I]n\f[R]. .RS .PP The \f[I]scale\f[R] of a number is the number of decimal places it has after the radix (decimal point). .RE .TP \f[B]BclError bcl_num_setScale(BclNumber\f[R] \f[I]n\f[R]\f[B], size_t\f[R] \f[I]scale\f[R]\f[B])\f[R] Sets the \f[I]scale\f[R] of \f[I]n\f[R] to the argument \f[I]scale\f[R]. If the argument \f[I]scale\f[R] is greater than the \f[I]scale\f[R] of \f[I]n\f[R], \f[I]n\f[R] is extended. If the argument \f[I]scale\f[R] is less than the \f[I]scale\f[R] of \f[I]n\f[R], \f[I]n\f[R] is truncated. .RS .PP If there was no error, \f[B]BCL_ERROR_NONE\f[R] is returned. Otherwise, this function can return: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP \f[B]size_t bcl_num_len(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R] Returns the number of \f[I]significant decimal digits\f[R] in \f[I]n\f[R]. .SS Conversion .PP All procedures in this section require a valid current context. .PP -All procedures in this section consume the given \f[B]BclNumber\f[R] -arguments that are not given to pointer arguments. +All procedures in this section without the \f[B]_keep\f[R] suffix in +their name consume the given \f[B]BclNumber\f[R] arguments that are not +given to pointer arguments. See the \f[B]Consumption and Propagation\f[R] subsection below. .TP \f[B]BclNumber bcl_parse(const char *restrict\f[R] \f[I]val\f[R]\f[B])\f[R] Parses a number string according to the current context\[cq]s \f[B]ibase\f[R] and returns the resulting number. .RS .PP \f[I]val\f[R] must be non-\f[B]NULL\f[R] and a valid string. See \f[B]BCL_ERROR_PARSE_INVALID_STR\f[R] in the \f[B]ERRORS\f[R] section for more information. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_PARSE_INVALID_STR\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP \f[B]char* bcl_string(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R] Returns a string representation of \f[I]n\f[R] according the the current context\[cq]s \f[B]ibase\f[R]. The string is dynamically allocated and must be freed by the caller. .RS .PP \f[I]n\f[R] is consumed; it cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .RE .TP +\f[B]char* bcl_string_keep(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R] +Returns a string representation of \f[I]n\f[R] according the the current +context\[cq]s \f[B]ibase\f[R]. +The string is dynamically allocated and must be freed by the caller. +.TP \f[B]BclError bcl_bigdig(BclNumber\f[R] \f[I]n\f[R]\f[B], BclBigDig *\f[R]\f[I]result\f[R]\f[B])\f[R] Converts \f[I]n\f[R] into a \f[B]BclBigDig\f[R] and returns the result in the space pointed to by \f[I]result\f[R]. .RS .PP \f[I]a\f[R] must be smaller than \f[B]BC_OVERFLOW_MAX\f[R]. See the \f[B]LIMITS\f[R] section. .PP If there was no error, \f[B]BCL_ERROR_NONE\f[R] is returned. Otherwise, this function can return: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_OVERFLOW\f[R] .PP \f[I]n\f[R] is consumed; it cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .RE .TP +\f[B]BclError bcl_bigdig_keep(BclNumber\f[R] \f[I]n\f[R]\f[B], BclBigDig *\f[R]\f[I]result\f[R]\f[B])\f[R] +Converts \f[I]n\f[R] into a \f[B]BclBigDig\f[R] and returns the result +in the space pointed to by \f[I]result\f[R]. +.RS +.PP +\f[I]a\f[R] must be smaller than \f[B]BC_OVERFLOW_MAX\f[R]. +See the \f[B]LIMITS\f[R] section. +.PP +If there was no error, \f[B]BCL_ERROR_NONE\f[R] is returned. +Otherwise, this function can return: +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_NUM\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_CONTEXT\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_MATH_OVERFLOW\f[R] +.RE +.TP \f[B]BclNumber bcl_bigdig2num(BclBigDig\f[R] \f[I]val\f[R]\f[B])\f[R] Creates a \f[B]BclNumber\f[R] from \f[I]val\f[R]. .RS .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .SS Math .PP All procedures in this section require a valid current context. .PP +All procedures in this section without the \f[B]_keep\f[R] suffix in +their name consume the given \f[B]BclNumber\f[R] arguments that are not +given to pointer arguments. +See the \f[B]Consumption and Propagation\f[R] subsection below. +.PP All procedures in this section can return the following errors: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .TP \f[B]BclNumber bcl_add(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R] Adds \f[I]a\f[R] and \f[I]b\f[R] and returns the result. The \f[I]scale\f[R] of the result is the max of the \f[I]scale\f[R]s of \f[I]a\f[R] and \f[I]b\f[R]. .RS .PP \f[I]a\f[R] and \f[I]b\f[R] are consumed; they cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .PP \f[I]a\f[R] and \f[I]b\f[R] can be the same number. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP +\f[B]BclNumber bcl_add_keep(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R] +Adds \f[I]a\f[R] and \f[I]b\f[R] and returns the result. +The \f[I]scale\f[R] of the result is the max of the \f[I]scale\f[R]s of +\f[I]a\f[R] and \f[I]b\f[R]. +.RS +.PP +\f[I]a\f[R] and \f[I]b\f[R] can be the same number. +.PP +bcl(3) will encode an error in the return value, if there was one. +The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. +Possible errors include: +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_NUM\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_CONTEXT\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] +.RE +.TP \f[B]BclNumber bcl_sub(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R] Subtracts \f[I]b\f[R] from \f[I]a\f[R] and returns the result. The \f[I]scale\f[R] of the result is the max of the \f[I]scale\f[R]s of \f[I]a\f[R] and \f[I]b\f[R]. .RS .PP \f[I]a\f[R] and \f[I]b\f[R] are consumed; they cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .PP \f[I]a\f[R] and \f[I]b\f[R] can be the same number. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP +\f[B]BclNumber bcl_sub_keep(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R] +Subtracts \f[I]b\f[R] from \f[I]a\f[R] and returns the result. +The \f[I]scale\f[R] of the result is the max of the \f[I]scale\f[R]s of +\f[I]a\f[R] and \f[I]b\f[R]. +.RS +.PP +\f[I]a\f[R] and \f[I]b\f[R] can be the same number. +.PP +bcl(3) will encode an error in the return value, if there was one. +The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. +Possible errors include: +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_NUM\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_CONTEXT\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] +.RE +.TP \f[B]BclNumber bcl_mul(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R] Multiplies \f[I]a\f[R] and \f[I]b\f[R] and returns the result. If \f[I]ascale\f[R] is the \f[I]scale\f[R] of \f[I]a\f[R] and \f[I]bscale\f[R] is the \f[I]scale\f[R] of \f[I]b\f[R], the \f[I]scale\f[R] of the result is equal to \f[B]min(ascale+bscale,max(scale,ascale,bscale))\f[R], where \f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. .RS .PP \f[I]a\f[R] and \f[I]b\f[R] are consumed; they cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .PP \f[I]a\f[R] and \f[I]b\f[R] can be the same number. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP +\f[B]BclNumber bcl_mul_keep(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R] +Multiplies \f[I]a\f[R] and \f[I]b\f[R] and returns the result. +If \f[I]ascale\f[R] is the \f[I]scale\f[R] of \f[I]a\f[R] and +\f[I]bscale\f[R] is the \f[I]scale\f[R] of \f[I]b\f[R], the +\f[I]scale\f[R] of the result is equal to +\f[B]min(ascale+bscale,max(scale,ascale,bscale))\f[R], where +\f[B]min()\f[R] and \f[B]max()\f[R] return the obvious values. +.RS +.PP +\f[I]a\f[R] and \f[I]b\f[R] can be the same number. +.PP +bcl(3) will encode an error in the return value, if there was one. +The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. +Possible errors include: +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_NUM\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_CONTEXT\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] +.RE +.TP \f[B]BclNumber bcl_div(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R] Divides \f[I]a\f[R] by \f[I]b\f[R] and returns the result. The \f[I]scale\f[R] of the result is the \f[I]scale\f[R] of the current context. .RS .PP \f[I]b\f[R] cannot be \f[B]0\f[R]. .PP \f[I]a\f[R] and \f[I]b\f[R] are consumed; they cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .PP \f[I]a\f[R] and \f[I]b\f[R] can be the same number. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_DIVIDE_BY_ZERO\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP +\f[B]BclNumber bcl_div_keep(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R] +Divides \f[I]a\f[R] by \f[I]b\f[R] and returns the result. +The \f[I]scale\f[R] of the result is the \f[I]scale\f[R] of the current +context. +.RS +.PP +\f[I]b\f[R] cannot be \f[B]0\f[R]. +.PP +\f[I]a\f[R] and \f[I]b\f[R] can be the same number. +.PP +bcl(3) will encode an error in the return value, if there was one. +The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. +Possible errors include: +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_NUM\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_CONTEXT\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_MATH_DIVIDE_BY_ZERO\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] +.RE +.TP \f[B]BclNumber bcl_mod(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R] Divides \f[I]a\f[R] by \f[I]b\f[R] to the \f[I]scale\f[R] of the current context, computes the modulus \f[B]a-(a/b)*b\f[R], and returns the modulus. .RS .PP \f[I]b\f[R] cannot be \f[B]0\f[R]. .PP \f[I]a\f[R] and \f[I]b\f[R] are consumed; they cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .PP \f[I]a\f[R] and \f[I]b\f[R] can be the same number. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_DIVIDE_BY_ZERO\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP +\f[B]BclNumber bcl_mod_keep(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R] +Divides \f[I]a\f[R] by \f[I]b\f[R] to the \f[I]scale\f[R] of the current +context, computes the modulus \f[B]a-(a/b)*b\f[R], and returns the +modulus. +.RS +.PP +\f[I]b\f[R] cannot be \f[B]0\f[R]. +.PP +\f[I]a\f[R] and \f[I]b\f[R] can be the same number. +.PP +bcl(3) will encode an error in the return value, if there was one. +The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. +Possible errors include: +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_NUM\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_CONTEXT\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_MATH_DIVIDE_BY_ZERO\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] +.RE +.TP \f[B]BclNumber bcl_pow(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R] Calculates \f[I]a\f[R] to the power of \f[I]b\f[R] to the \f[I]scale\f[R] of the current context. \f[I]b\f[R] must be an integer, but can be negative. If it is negative, \f[I]a\f[R] must be non-zero. .RS .PP \f[I]b\f[R] must be an integer. If \f[I]b\f[R] is negative, \f[I]a\f[R] must not be \f[B]0\f[R]. .PP \f[I]a\f[R] must be smaller than \f[B]BC_OVERFLOW_MAX\f[R]. See the \f[B]LIMITS\f[R] section. .PP \f[I]a\f[R] and \f[I]b\f[R] are consumed; they cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .PP \f[I]a\f[R] and \f[I]b\f[R] can be the same number. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_NON_INTEGER\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_OVERFLOW\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_DIVIDE_BY_ZERO\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP +\f[B]BclNumber bcl_pow_keep(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R] +Calculates \f[I]a\f[R] to the power of \f[I]b\f[R] to the +\f[I]scale\f[R] of the current context. +\f[I]b\f[R] must be an integer, but can be negative. +If it is negative, \f[I]a\f[R] must be non-zero. +.RS +.PP +\f[I]b\f[R] must be an integer. +If \f[I]b\f[R] is negative, \f[I]a\f[R] must not be \f[B]0\f[R]. +.PP +\f[I]a\f[R] must be smaller than \f[B]BC_OVERFLOW_MAX\f[R]. +See the \f[B]LIMITS\f[R] section. +.PP +\f[I]a\f[R] and \f[I]b\f[R] can be the same number. +.PP +bcl(3) will encode an error in the return value, if there was one. +The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. +Possible errors include: +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_NUM\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_CONTEXT\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_MATH_NON_INTEGER\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_MATH_OVERFLOW\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_MATH_DIVIDE_BY_ZERO\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] +.RE +.TP \f[B]BclNumber bcl_lshift(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R] Shifts \f[I]a\f[R] left (moves the radix right) by \f[I]b\f[R] places and returns the result. This is done in decimal. \f[I]b\f[R] must be an integer. .RS .PP \f[I]b\f[R] must be an integer. .PP \f[I]a\f[R] and \f[I]b\f[R] are consumed; they cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .PP \f[I]a\f[R] and \f[I]b\f[R] can be the same number. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_NON_INTEGER\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP +\f[B]BclNumber bcl_lshift_keep(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R] +Shifts \f[I]a\f[R] left (moves the radix right) by \f[I]b\f[R] places +and returns the result. +This is done in decimal. +\f[I]b\f[R] must be an integer. +.RS +.PP +\f[I]b\f[R] must be an integer. +.PP +\f[I]a\f[R] and \f[I]b\f[R] can be the same number. +.PP +bcl(3) will encode an error in the return value, if there was one. +The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. +Possible errors include: +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_NUM\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_CONTEXT\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_MATH_NON_INTEGER\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] +.RE +.TP \f[B]BclNumber bcl_rshift(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R] Shifts \f[I]a\f[R] right (moves the radix left) by \f[I]b\f[R] places and returns the result. This is done in decimal. \f[I]b\f[R] must be an integer. .RS .PP \f[I]b\f[R] must be an integer. .PP \f[I]a\f[R] and \f[I]b\f[R] are consumed; they cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .PP \f[I]a\f[R] and \f[I]b\f[R] can be the same number. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_NON_INTEGER\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP +\f[B]BclNumber bcl_rshift_keep(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R] +Shifts \f[I]a\f[R] right (moves the radix left) by \f[I]b\f[R] places +and returns the result. +This is done in decimal. +\f[I]b\f[R] must be an integer. +.RS +.PP +\f[I]b\f[R] must be an integer. +.PP +\f[I]a\f[R] and \f[I]b\f[R] can be the same number. +.PP +bcl(3) will encode an error in the return value, if there was one. +The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. +Possible errors include: +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_NUM\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_CONTEXT\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_MATH_NON_INTEGER\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] +.RE +.TP \f[B]BclNumber bcl_sqrt(BclNumber\f[R] \f[I]a\f[R]\f[B])\f[R] Calculates the square root of \f[I]a\f[R] and returns the result. The \f[I]scale\f[R] of the result is equal to the \f[B]scale\f[R] of the current context. .RS .PP \f[I]a\f[R] cannot be negative. .PP \f[I]a\f[R] is consumed; it cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_NEGATIVE\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP +\f[B]BclNumber bcl_sqrt_keep(BclNumber\f[R] \f[I]a\f[R]\f[B])\f[R] +Calculates the square root of \f[I]a\f[R] and returns the result. +The \f[I]scale\f[R] of the result is equal to the \f[B]scale\f[R] of the +current context. +.RS +.PP +\f[I]a\f[R] cannot be negative. +.PP +bcl(3) will encode an error in the return value, if there was one. +The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. +Possible errors include: +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_NUM\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_CONTEXT\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_MATH_NEGATIVE\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] +.RE +.TP \f[B]BclError bcl_divmod(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B], BclNumber *\f[R]\f[I]c\f[R]\f[B], BclNumber *\f[R]\f[I]d\f[R]\f[B])\f[R] Divides \f[I]a\f[R] by \f[I]b\f[R] and returns the quotient in a new number which is put into the space pointed to by \f[I]c\f[R], and puts the modulus in a new number which is put into the space pointed to by \f[I]d\f[R]. .RS .PP \f[I]b\f[R] cannot be \f[B]0\f[R]. .PP \f[I]a\f[R] and \f[I]b\f[R] are consumed; they cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .PP \f[I]c\f[R] and \f[I]d\f[R] cannot point to the same place, nor can they point to the space occupied by \f[I]a\f[R] or \f[I]b\f[R]. .PP If there was no error, \f[B]BCL_ERROR_NONE\f[R] is returned. Otherwise, this function can return: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_DIVIDE_BY_ZERO\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP +\f[B]BclError bcl_divmod_keep(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B], BclNumber *\f[R]\f[I]c\f[R]\f[B], BclNumber *\f[R]\f[I]d\f[R]\f[B])\f[R] +Divides \f[I]a\f[R] by \f[I]b\f[R] and returns the quotient in a new +number which is put into the space pointed to by \f[I]c\f[R], and puts +the modulus in a new number which is put into the space pointed to by +\f[I]d\f[R]. +.RS +.PP +\f[I]b\f[R] cannot be \f[B]0\f[R]. +.PP +\f[I]c\f[R] and \f[I]d\f[R] cannot point to the same place, nor can they +point to the space occupied by \f[I]a\f[R] or \f[I]b\f[R]. +.PP +If there was no error, \f[B]BCL_ERROR_NONE\f[R] is returned. +Otherwise, this function can return: +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_NUM\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_CONTEXT\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_MATH_DIVIDE_BY_ZERO\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] +.RE +.TP \f[B]BclNumber bcl_modexp(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B], BclNumber\f[R] \f[I]c\f[R]\f[B])\f[R] Computes a modular exponentiation where \f[I]a\f[R] is the base, \f[I]b\f[R] is the exponent, and \f[I]c\f[R] is the modulus, and returns the result. The \f[I]scale\f[R] of the result is equal to the \f[B]scale\f[R] of the current context. .RS .PP \f[I]a\f[R], \f[I]b\f[R], and \f[I]c\f[R] must be integers. \f[I]c\f[R] must not be \f[B]0\f[R]. \f[I]b\f[R] must not be negative. .PP \f[I]a\f[R], \f[I]b\f[R], and \f[I]c\f[R] are consumed; they cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_NEGATIVE\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_NON_INTEGER\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_DIVIDE_BY_ZERO\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE +.TP +\f[B]BclNumber bcl_modexp_keep(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B], BclNumber\f[R] \f[I]c\f[R]\f[B])\f[R] +Computes a modular exponentiation where \f[I]a\f[R] is the base, +\f[I]b\f[R] is the exponent, and \f[I]c\f[R] is the modulus, and returns +the result. +The \f[I]scale\f[R] of the result is equal to the \f[B]scale\f[R] of the +current context. +.RS +.PP +\f[I]a\f[R], \f[I]b\f[R], and \f[I]c\f[R] must be integers. +\f[I]c\f[R] must not be \f[B]0\f[R]. +\f[I]b\f[R] must not be negative. +.PP +bcl(3) will encode an error in the return value, if there was one. +The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. +Possible errors include: +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_NUM\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_CONTEXT\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_MATH_NEGATIVE\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_MATH_NON_INTEGER\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_MATH_DIVIDE_BY_ZERO\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] +.RE .SS Miscellaneous .TP \f[B]void bcl_zero(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R] Sets \f[I]n\f[R] to \f[B]0\f[R]. .TP \f[B]void bcl_one(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R] Sets \f[I]n\f[R] to \f[B]1\f[R]. .TP \f[B]ssize_t bcl_cmp(BclNumber\f[R] \f[I]a\f[R]\f[B], BclNumber\f[R] \f[I]b\f[R]\f[B])\f[R] Compares \f[I]a\f[R] and \f[I]b\f[R] and returns \f[B]0\f[R] if \f[I]a\f[R] and \f[I]b\f[R] are equal, \f[B]<0\f[R] if \f[I]a\f[R] is less than \f[I]b\f[R], and \f[B]>0\f[R] if \f[I]a\f[R] is greater than \f[I]b\f[R]. .TP \f[B]BclError bcl_copy(BclNumber\f[R] \f[I]d\f[R]\f[B], BclNumber\f[R] \f[I]s\f[R]\f[B])\f[R] Copies \f[I]s\f[R] into \f[I]d\f[R]. .RS .PP If there was no error, \f[B]BCL_ERROR_NONE\f[R] is returned. Otherwise, this function can return: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP \f[B]BclNumber bcl_dup(BclNumber\f[R] \f[I]s\f[R]\f[B])\f[R] Creates and returns a new \f[B]BclNumber\f[R] that is a copy of \f[I]s\f[R]. .RS .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .SS Pseudo-Random Number Generator .PP The pseudo-random number generator in bcl(3) is a \f[I]seeded\f[R] PRNG. Given the same seed twice, it will produce the same sequence of pseudo-random numbers twice. .PP By default, bcl(3) attempts to seed the PRNG with data from \f[B]/dev/urandom\f[R]. If that fails, it seeds itself with by calling \f[B]libc\f[R]\[cq]s \f[B]srand(time(NULL))\f[R] and then calling \f[B]rand()\f[R] for each byte, since \f[B]rand()\f[R] is only guaranteed to return \f[B]15\f[R] bits. .PP This should provide fairly good seeding in the standard case while also remaining fairly portable. .PP If necessary, the PRNG can be reseeded with one of the following functions: .IP \[bu] 2 \f[B]bcl_rand_seedWithNum(BclNumber)\f[R] .IP \[bu] 2 \f[B]bcl_rand_seed(unsigned char[\f[R]\f[I]BCL_SEED_SIZE\f[R]\f[B]])\f[R] .IP \[bu] 2 \f[B]bcl_rand_reseed(\f[R]\f[I]void\f[R]\f[B])\f[R] .PP +All procedures in this section without the \f[B]_keep\f[R] suffix in +their name consume the given \f[B]BclNumber\f[R] arguments that are not +given to pointer arguments. +See the \f[B]Consumption and Propagation\f[R] subsection below. +.PP The following items allow clients to use the pseudo-random number generator. All procedures require a valid current context. .TP \f[B]BCL_SEED_ULONGS\f[R] The number of \f[B]unsigned long\f[R]\[cq]s in a seed for bcl(3)\[cq]s random number generator. .TP \f[B]BCL_SEED_SIZE\f[R] The size, in \f[B]char\f[R]\[cq]s, of a seed for bcl(3)\[cq]s random number generator. .TP \f[B]BclBigDig\f[R] bcl(3)\[cq]s overflow type (see the \f[B]PERFORMANCE\f[R] section). .TP \f[B]BclRandInt\f[R] An unsigned integer type returned by bcl(3)\[cq]s random number generator. .TP \f[B]BclNumber bcl_irand(BclNumber\f[R] \f[I]a\f[R]\f[B])\f[R] Returns a random number that is not larger than \f[I]a\f[R] in a new number. If \f[I]a\f[R] is \f[B]0\f[R] or \f[B]1\f[R], the new number is equal to \f[B]0\f[R]. The bound is unlimited, so it is not bound to the size of \f[B]BclRandInt\f[R]. This is done by generating as many random numbers as necessary, multiplying them by certain exponents, and adding them all together. .RS .PP \f[I]a\f[R] must be an integer and non-negative. .PP \f[I]a\f[R] is consumed; it cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .PP This procedure requires a valid current context. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_NEGATIVE\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_NON_INTEGER\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP +\f[B]BclNumber bcl_irand_keep(BclNumber\f[R] \f[I]a\f[R]\f[B])\f[R] +Returns a random number that is not larger than \f[I]a\f[R] in a new +number. +If \f[I]a\f[R] is \f[B]0\f[R] or \f[B]1\f[R], the new number is equal to +\f[B]0\f[R]. +The bound is unlimited, so it is not bound to the size of +\f[B]BclRandInt\f[R]. +This is done by generating as many random numbers as necessary, +multiplying them by certain exponents, and adding them all together. +.RS +.PP +\f[I]a\f[R] must be an integer and non-negative. +.PP +This procedure requires a valid current context. +.PP +bcl(3) will encode an error in the return value, if there was one. +The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. +Possible errors include: +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_NUM\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_CONTEXT\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_MATH_NEGATIVE\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_MATH_NON_INTEGER\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] +.RE +.TP \f[B]BclNumber bcl_frand(size_t\f[R] \f[I]places\f[R]\f[B])\f[R] Returns a random number between \f[B]0\f[R] (inclusive) and \f[B]1\f[R] (exclusive) that has \f[I]places\f[R] decimal digits after the radix (decimal point). There are no limits on \f[I]places\f[R]. .RS .PP This procedure requires a valid current context. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP \f[B]BclNumber bcl_ifrand(BclNumber\f[R] \f[I]a\f[R]\f[B], size_t\f[R] \f[I]places\f[R]\f[B])\f[R] Returns a random number less than \f[I]a\f[R] with \f[I]places\f[R] decimal digits after the radix (decimal point). There are no limits on \f[I]a\f[R] or \f[I]places\f[R]. .RS .PP \f[I]a\f[R] must be an integer and non-negative. .PP \f[I]a\f[R] is consumed; it cannot be used after the call. See the \f[B]Consumption and Propagation\f[R] subsection below. .PP This procedure requires a valid current context. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_NEGATIVE\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_MATH_NON_INTEGER\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP +\f[B]BclNumber bcl_ifrand_keep(BclNumber\f[R] \f[I]a\f[R]\f[B], size_t\f[R] \f[I]places\f[R]\f[B])\f[R] +Returns a random number less than \f[I]a\f[R] with \f[I]places\f[R] +decimal digits after the radix (decimal point). +There are no limits on \f[I]a\f[R] or \f[I]places\f[R]. +.RS +.PP +\f[I]a\f[R] must be an integer and non-negative. +.PP +This procedure requires a valid current context. +.PP +bcl(3) will encode an error in the return value, if there was one. +The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. +Possible errors include: +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_NUM\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_CONTEXT\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_MATH_NEGATIVE\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_MATH_NON_INTEGER\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] +.RE +.TP \f[B]BclError bcl_rand_seedWithNum(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R] Seeds the PRNG with \f[I]n\f[R]. .RS .PP -\f[I]n\f[R] is \f[I]not\f[R] consumed. +\f[I]n\f[R] is consumed. +.PP +This procedure requires a valid current context. +.PP +If there was no error, \f[B]BCL_ERROR_NONE\f[R] is returned. +Otherwise, this function can return: +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_NUM\f[R] +.IP \[bu] 2 +\f[B]BCL_ERROR_INVALID_CONTEXT\f[R] +.PP +Note that if \f[B]bcl_rand_seed2num(\f[R]\f[I]void\f[R]\f[B])\f[R] or +\f[B]bcl_rand_seed2num_err(BclNumber)\f[R] are called right after this +function, they are not guaranteed to return a number equal to +\f[I]n\f[R]. +.RE +.TP +\f[B]BclError bcl_rand_seedWithNum_keep(BclNumber\f[R] \f[I]n\f[R]\f[B])\f[R] +Seeds the PRNG with \f[I]n\f[R]. +.RS .PP This procedure requires a valid current context. .PP If there was no error, \f[B]BCL_ERROR_NONE\f[R] is returned. Otherwise, this function can return: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_NUM\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .PP Note that if \f[B]bcl_rand_seed2num(\f[R]\f[I]void\f[R]\f[B])\f[R] or \f[B]bcl_rand_seed2num_err(BclNumber)\f[R] are called right after this function, they are not guaranteed to return a number equal to \f[I]n\f[R]. .RE .TP \f[B]BclError bcl_rand_seed(unsigned char\f[R] \f[I]seed\f[R]\f[B][\f[R]\f[I]BCL_SEED_SIZE\f[R]\f[B]])\f[R] Seeds the PRNG with the bytes in \f[I]seed\f[R]. .RS .PP If there was no error, \f[B]BCL_ERROR_NONE\f[R] is returned. Otherwise, this function can return: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .RE .TP \f[B]void bcl_rand_reseed(\f[R]\f[I]void\f[R]\f[B])\f[R] Reseeds the PRNG with the default reseeding behavior. First, it attempts to read data from \f[B]/dev/urandom\f[R] and falls back to \f[B]libc\f[R]\[cq]s \f[B]rand()\f[R]. .RS .PP This procedure cannot fail. .RE .TP \f[B]BclNumber bcl_rand_seed2num(\f[R]\f[I]void\f[R]\f[B])\f[R] Returns the current seed of the PRNG as a \f[B]BclNumber\f[R]. .RS .PP This procedure requires a valid current context. .PP bcl(3) will encode an error in the return value, if there was one. The error can be queried with \f[B]bcl_err(BclNumber)\f[R]. Possible errors include: .IP \[bu] 2 \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] .IP \[bu] 2 \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] .RE .TP \f[B]BclRandInt bcl_rand_int(\f[R]\f[I]void\f[R]\f[B])\f[R] Returns a random integer between \f[B]0\f[R] and \f[B]BC_RAND_MAX\f[R] (inclusive). .RS .PP This procedure cannot fail. .RE .TP \f[B]BclRandInt bcl_rand_bounded(BclRandInt\f[R] \f[I]bound\f[R]\f[B])\f[R] Returns a random integer between \f[B]0\f[R] and \f[I]bound\f[R] (exclusive). Bias is removed before returning the integer. .RS .PP This procedure cannot fail. .RE .SS Consumption and Propagation .PP Some functions are listed as consuming some or all of their arguments. This means that the arguments are freed, regardless of if there were errors or not. .PP This is to enable compact code like the following: .IP .nf \f[C] BclNumber n = bcl_num_add(bcl_num_mul(a, b), bcl_num_div(c, d)); \f[R] .fi .PP If arguments to those functions were not consumed, memory would be leaked until reclaimed with \f[B]bcl_ctxt_freeNums(BclContext)\f[R]. .PP When errors occur, they are propagated through. The result should always be checked with \f[B]bcl_err(BclNumber)\f[R], so the example above should properly be: .IP .nf \f[C] BclNumber n = bcl_num_add(bcl_num_mul(a, b), bcl_num_div(c, d)); -if (bc_num_err(n) != BCL_ERROR_NONE) { +if (bcl_err(n) != BCL_ERROR_NONE) { // Handle the error. } \f[R] .fi .SH ERRORS .PP Most functions in bcl(3) return, directly or indirectly, any one of the error codes defined in \f[B]BclError\f[R]. The complete list of codes is the following: .TP \f[B]BCL_ERROR_NONE\f[R] Success; no error occurred. .TP \f[B]BCL_ERROR_INVALID_NUM\f[R] An invalid \f[B]BclNumber\f[R] was given as a parameter. .TP \f[B]BCL_ERROR_INVALID_CONTEXT\f[R] An invalid \f[B]BclContext\f[R] is being used. .TP \f[B]BCL_ERROR_MATH_NEGATIVE\f[R] A negative number was given as an argument to a parameter that cannot accept negative numbers, such as for square roots. .TP \f[B]BCL_ERROR_MATH_NON_INTEGER\f[R] A non-integer was given as an argument to a parameter that cannot accept non-integer numbers, such as for the second parameter of \f[B]bcl_num_pow()\f[R]. .TP \f[B]BCL_ERROR_MATH_OVERFLOW\f[R] A number that would overflow its result was given as an argument, such as for converting a \f[B]BclNumber\f[R] to a \f[B]BclBigDig\f[R]. .TP \f[B]BCL_ERROR_MATH_DIVIDE_BY_ZERO\f[R] A divide by zero occurred. .TP \f[B]BCL_ERROR_PARSE_INVALID_STR\f[R] An invalid number string was passed to a parsing function. .RS .PP A valid number string can only be one radix (period). In addition, any lowercase ASCII letters, symbols, or non-ASCII characters are invalid. It is allowed for the first character to be a dash. In that case, the number is considered to be negative. .PP There is one exception to the above: one lowercase \f[B]e\f[R] is allowed in the number, after the radix, if it exists. If the letter \f[B]e\f[R] exists, the number is considered to be in scientific notation, where the part before the \f[B]e\f[R] is the number, and the part after, which must be an integer, is the exponent. There can be a dash right after the \f[B]e\f[R] to indicate a negative exponent. .PP \f[B]WARNING\f[R]: Both the number and the exponent in scientific notation are interpreted according to the current \f[B]ibase\f[R], but the number is still multiplied by \f[B]10\[ha]exponent\f[R] regardless of the current \f[B]ibase\f[R]. For example, if \f[B]ibase\f[R] is \f[B]16\f[R] and bcl(3) is given the number string \f[B]FFeA\f[R], the resulting decimal number will be \f[B]2550000000000\f[R], and if bcl(3) is given the number string \f[B]10e-4\f[R], the resulting decimal number will be \f[B]0.0016\f[R]. .RE .TP \f[B]BCL_ERROR_FATAL_ALLOC_ERR\f[R] bcl(3) failed to allocate memory. .RS .PP If clients call \f[B]bcl_setAbortOnFatalError()\f[R] with an \f[B]true\f[R] argument, this error will cause bcl(3) to throw a \f[B]SIGABRT\f[R]. This behavior can also be turned off later by calling that same function with a \f[B]false\f[R] argument. By default, this behavior is off. .PP It is highly recommended that client libraries do \f[I]not\f[R] activate this behavior. .RE .TP \f[B]BCL_ERROR_FATAL_UNKNOWN_ERR\f[R] An unknown error occurred. .RS .PP If clients call \f[B]bcl_setAbortOnFatalError()\f[R] with an \f[B]true\f[R] argument, this error will cause bcl(3) to throw a \f[B]SIGABRT\f[R]. This behavior can also be turned off later by calling that same function with a \f[B]false\f[R] argument. By default, this behavior is off. .PP It is highly recommended that client libraries do \f[I]not\f[R] activate this behavior. .RE .SH ATTRIBUTES .PP bcl(3) is \f[I]MT-Safe\f[R]: it is safe to call any functions from more than one thread. However, is is \f[I]not\f[R] safe to pass any data between threads except for strings returned by \f[B]bcl_string()\f[R]. .PP bcl(3) is not \f[I]async-signal-safe\f[R]. It was not possible to make bcl(3) safe with signals and also make it safe with multiple threads. If it is necessary to be able to interrupt bcl(3), spawn a separate thread to run the calculation. .SH PERFORMANCE .PP Most bc(1) implementations use \f[B]char\f[R] types to calculate the value of \f[B]1\f[R] decimal digit at a time, but that can be slow. bcl(3) does something different. .PP It uses large integers to calculate more than \f[B]1\f[R] decimal digit at a time. If built in a environment where \f[B]BC_LONG_BIT\f[R] (see the \f[B]LIMITS\f[R] section) is \f[B]64\f[R], then each integer has \f[B]9\f[R] decimal digits. If built in an environment where \f[B]BC_LONG_BIT\f[R] is \f[B]32\f[R] then each integer has \f[B]4\f[R] decimal digits. This value (the number of decimal digits per large integer) is called \f[B]BC_BASE_DIGS\f[R]. .PP In addition, this bcl(3) uses an even larger integer for overflow checking. This integer type depends on the value of \f[B]BC_LONG_BIT\f[R], but is always at least twice as large as the integer type used to store digits. .SH LIMITS .PP The following are the limits on bcl(3): .TP \f[B]BC_LONG_BIT\f[R] The number of bits in the \f[B]long\f[R] type in the environment where bcl(3) was built. This determines how many decimal digits can be stored in a single large integer (see the \f[B]PERFORMANCE\f[R] section). .TP \f[B]BC_BASE_DIGS\f[R] The number of decimal digits per large integer (see the \f[B]PERFORMANCE\f[R] section). Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_POW\f[R] The max decimal number that each large integer can store (see \f[B]BC_BASE_DIGS\f[R]) plus \f[B]1\f[R]. Depends on \f[B]BC_BASE_DIGS\f[R]. .TP \f[B]BC_OVERFLOW_MAX\f[R] The max number that the overflow type (see the \f[B]PERFORMANCE\f[R] section) can hold. Depends on \f[B]BC_LONG_BIT\f[R]. .TP \f[B]BC_BASE_MAX\f[R] The maximum output base. Set at \f[B]BC_BASE_POW\f[R]. .TP \f[B]BC_SCALE_MAX\f[R] The maximum \f[B]scale\f[R]. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_NUM_MAX\f[R] The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at \f[B]BC_OVERFLOW_MAX-1\f[R]. .TP \f[B]BC_RAND_MAX\f[R] The maximum integer (inclusive) returned by the \f[B]bcl_rand_int()\f[R] function. Set at \f[B]2\[ha]BC_LONG_BIT-1\f[R]. .TP Exponent The maximum allowable exponent (positive or negative). Set at \f[B]BC_OVERFLOW_MAX\f[R]. .PP These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. .SH SEE ALSO .PP bc(1) and dc(1) .SH STANDARDS .PP bcl(3) is compliant with the arithmetic defined in the IEEE Std 1003.1-2017 (\[lq]POSIX.1-2017\[rq]) specification at https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html for bc(1). .PP Note that the specification explicitly says that bc(1) only accepts numbers that use a period (\f[B].\f[R]) as a radix point, regardless of the value of \f[B]LC_NUMERIC\f[R]. This is also true of bcl(3). .SH BUGS .PP None are known. Report bugs at https://git.gavinhoward.com/gavin/bc. .SH AUTHORS .PP Gavin D. Howard and contributors. diff --git a/contrib/bc/manuals/bcl.3.md b/contrib/bc/manuals/bcl.3.md index 6c6967b44770..fa566d161c43 100644 --- a/contrib/bc/manuals/bcl.3.md +++ b/contrib/bc/manuals/bcl.3.md @@ -1,1237 +1,1539 @@ # NAME bcl - library of arbitrary precision decimal arithmetic # SYNOPSIS ## Use *#include * Link with *-lbcl*, and on POSIX systems, *-lpthread* is also required. ## Setup These items allow clients to set up bcl(3). **BclError bcl_start(**_void_**);** **void bcl_end(**_void_**);** **BclError bcl_init(**_void_**);** **void bcl_free(**_void_**);** **bool bcl_abortOnFatalError(**_void_**);** **void bcl_setAbortOnFatalError(bool** _abrt_**);** **bool bcl_leadingZeroes(**_void_**);** **void bcl_setLeadingZeroes(bool** _leadingZeroes_**);** **void bcl_gc(**_void_**);** **bool bcl_digitClamp(**_void_**);** **void bcl_setDigitClamp(bool** _digitClamp_**);** ## Contexts These items will allow clients to handle contexts, which are isolated from each other. This allows more than one client to use bcl(3) in the same program. **struct BclCtxt;** **typedef struct BclCtxt\* BclContext;** **BclContext bcl_ctxt_create(**_void_**);** **void bcl_ctxt_free(BclContext** _ctxt_**);** **BclError bcl_pushContext(BclContext** _ctxt_**);** **void bcl_popContext(**_void_**);** **BclContext bcl_context(**_void_**);** **void bcl_ctxt_freeNums(BclContext** _ctxt_**);** **size_t bcl_ctxt_scale(BclContext** _ctxt_**);** **void bcl_ctxt_setScale(BclContext** _ctxt_**, size_t** _scale_**);** **size_t bcl_ctxt_ibase(BclContext** _ctxt_**);** **void bcl_ctxt_setIbase(BclContext** _ctxt_**, size_t** _ibase_**);** **size_t bcl_ctxt_obase(BclContext** _ctxt_**);** **void bcl_ctxt_setObase(BclContext** _ctxt_**, size_t** _obase_**);** ## Errors These items allow clients to handle errors. **typedef enum BclError BclError;** **BclError bcl_err(BclNumber** _n_**);** ## Numbers These items allow clients to manipulate and query the arbitrary-precision numbers managed by bcl(3). **typedef struct { size_t i; } BclNumber;** **BclNumber bcl_num_create(**_void_**);** **void bcl_num_free(BclNumber** _n_**);** **bool bcl_num_neg(BclNumber** _n_**);** **void bcl_num_setNeg(BclNumber** _n_**, bool** _neg_**);** **size_t bcl_num_scale(BclNumber** _n_**);** **BclError bcl_num_setScale(BclNumber** _n_**, size_t** _scale_**);** **size_t bcl_num_len(BclNumber** _n_**);** ## Conversion These items allow clients to convert numbers into and from strings and integers. **BclNumber bcl_parse(const char \*restrict** _val_**);** **char\* bcl_string(BclNumber** _n_**);** +**char\* bcl_string_keep(BclNumber** _n_**);** + **BclError bcl_bigdig(BclNumber** _n_**, BclBigDig \***_result_**);** +**BclError bcl_bigdig_keep(BclNumber** _n_**, BclBigDig \***_result_**);** + **BclNumber bcl_bigdig2num(BclBigDig** _val_**);** ## Math These items allow clients to run math on numbers. **BclNumber bcl_add(BclNumber** _a_**, BclNumber** _b_**);** +**BclNumber bcl_add_keep(BclNumber** _a_**, BclNumber** _b_**);** + **BclNumber bcl_sub(BclNumber** _a_**, BclNumber** _b_**);** +**BclNumber bcl_sub_keep(BclNumber** _a_**, BclNumber** _b_**);** + **BclNumber bcl_mul(BclNumber** _a_**, BclNumber** _b_**);** +**BclNumber bcl_mul_keep(BclNumber** _a_**, BclNumber** _b_**);** + **BclNumber bcl_div(BclNumber** _a_**, BclNumber** _b_**);** +**BclNumber bcl_div_keep(BclNumber** _a_**, BclNumber** _b_**);** + **BclNumber bcl_mod(BclNumber** _a_**, BclNumber** _b_**);** +**BclNumber bcl_mod_keep(BclNumber** _a_**, BclNumber** _b_**);** + **BclNumber bcl_pow(BclNumber** _a_**, BclNumber** _b_**);** +**BclNumber bcl_pow_keep(BclNumber** _a_**, BclNumber** _b_**);** + **BclNumber bcl_lshift(BclNumber** _a_**, BclNumber** _b_**);** +**BclNumber bcl_lshift_keep(BclNumber** _a_**, BclNumber** _b_**);** + **BclNumber bcl_rshift(BclNumber** _a_**, BclNumber** _b_**);** +**BclNumber bcl_rshift_keep(BclNumber** _a_**, BclNumber** _b_**);** + **BclNumber bcl_sqrt(BclNumber** _a_**);** +**BclNumber bcl_sqrt_keep(BclNumber** _a_**);** + **BclError bcl_divmod(BclNumber** _a_**, BclNumber** _b_**, BclNumber \***_c_**, BclNumber \***_d_**);** +**BclError bcl_divmod_keep(BclNumber** _a_**, BclNumber** _b_**, BclNumber \***_c_**, BclNumber \***_d_**);** + **BclNumber bcl_modexp(BclNumber** _a_**, BclNumber** _b_**, BclNumber** _c_**);** +**BclNumber bcl_modexp_keep(BclNumber** _a_**, BclNumber** _b_**, BclNumber** _c_**);** + ## Miscellaneous These items are miscellaneous. **void bcl_zero(BclNumber** _n_**);** **void bcl_one(BclNumber** _n_**);** **ssize_t bcl_cmp(BclNumber** _a_**, BclNumber** _b_**);** **BclError bcl_copy(BclNumber** _d_**, BclNumber** _s_**);** **BclNumber bcl_dup(BclNumber** _s_**);** ## Pseudo-Random Number Generator These items allow clients to manipulate the seeded pseudo-random number generator in bcl(3). **#define BCL_SEED_ULONGS** **#define BCL_SEED_SIZE** **typedef unsigned long BclBigDig;** **typedef unsigned long BclRandInt;** **BclNumber bcl_irand(BclNumber** _a_**);** +**BclNumber bcl_irand_keep(BclNumber** _a_**);** + **BclNumber bcl_frand(size_t** _places_**);** **BclNumber bcl_ifrand(BclNumber** _a_**, size_t** _places_**);** +**BclNumber bcl_ifrand_keep(BclNumber** _a_**, size_t** _places_**);** + **BclError bcl_rand_seedWithNum(BclNumber** _n_**);** +**BclError bcl_rand_seedWithNum_keep(BclNumber** _n_**);** + **BclError bcl_rand_seed(unsigned char** _seed_**[**_BCL_SEED_SIZE_**]);** **void bcl_rand_reseed(**_void_**);** **BclNumber bcl_rand_seed2num(**_void_**);** **BclRandInt bcl_rand_int(**_void_**);** **BclRandInt bcl_rand_bounded(BclRandInt** _bound_**);** # DESCRIPTION bcl(3) is a library that implements arbitrary-precision decimal math, as standardized by POSIX (https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html) in bc(1). bcl(3) assumes that it is allowed to use the **bcl**, **Bcl**, **bc**, and **Bc** prefixes for symbol names without collision. All of the items in its interface are described below. See the documentation for each function for what each function can return. ## Setup **BclError bcl_start(**_void_**)** : Initializes this library. This function can be called multiple times, but **bcl_end()** must only be called *once*. This is to make it possible for multiple libraries and applications to initialize bcl(3) without problem. It is suggested that client libraries call this function, but do not call **bcl_end()**, and client applications should call both. If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this function can return: * **BCL_ERROR_FATAL_ALLOC_ERR** This function must be the first one clients call. Calling any other function without calling this one first is undefined behavior. **void bcl_end(**_void_**)** : Deinitializes this library. This function must only be called *once*. All data must have been freed before calling this function. This function must be the last one clients call. Calling this function before calling any other function is undefined behavior. **BclError bcl_init(**_void_**)** : Initializes the library for the current thread. This function can be called multiple times, but each call must be matched by a call to **bcl_free(**_void_**)**. This is to make it possible for multiple libraries and applications to initialize threads for bcl(3) without problem. This function *must* be called from the thread that it is supposed to initialize. If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this function can return: * **BCL_ERROR_FATAL_ALLOC_ERR** This function must be the second one clients call. Calling any other function without calling **bcl_start()** and then this one first is undefined behavior, except in the case of new threads. New threads can safely call this function without calling **bcl_start()** if another thread has previously called **bcl_start()**. But this function must still be the first function in bcl(3) called by that new thread. **void bcl_free(**_void_**)** : Decrements bcl(3)'s reference count and frees the data associated with it if the reference count is **0**. This function *must* be called from the thread that it is supposed to deinitialize. This function must be the second to last one clients call. Calling this function before calling any other function besides **bcl_end()** is undefined behavior. **bool bcl_abortOnFatalError(**_void_**)** : Queries and returns the current state of calling **abort()** on fatal errors. If **true** is returned, bcl(3) will cause a **SIGABRT** if a fatal error occurs. If activated, clients do not need to check for fatal errors. This value is *thread-local*; it applies to just the thread it is read on. The default is **false**. **void bcl_setAbortOnFatalError(bool** _abrt_**)** : Sets the state of calling **abort()** on fatal errors. If *abrt* is **false**, bcl(3) will not cause a **SIGABRT** on fatal errors after the call. If *abrt* is **true**, bcl(3) will cause a **SIGABRT** on fatal errors after the call. This value is *thread-local*; it applies to just the thread it is set on. If activated, clients do not need to check for fatal errors. **bool bcl_leadingZeroes(**_void_**)** : Queries and returns the state of whether leading zeroes are added to strings returned by **bcl_string()** when numbers are greater than **-1**, less than **1**, and not equal to **0**. If **true** is returned, then leading zeroes will be added. This value is *thread-local*; it applies to just the thread it is read on. The default is **false**. **void bcl_setLeadingZeroes(bool** _leadingZeroes_**)** : Sets the state of whether leading zeroes are added to strings returned by **bcl_string()** when numbers are greater than **-1**, less than **1**, and not equal to **0**. If *leadingZeroes* is **true**, leading zeroes will be added to strings returned by **bcl_string()**. This value is *thread-local*; it applies to just the thread it is set on. **bool bcl_digitClamp(**_void_**)** : Queries and returns the state of whether digits in number strings that are greater than or equal to the current **ibase** are clamped or not. If **true** is returned, then digits are treated as though they are equal to the value of **ibase** minus **1**. If this is *not* true, then digits are treated as though they are equal to the value they would have if **ibase** was large enough. They are then multiplied by the appropriate power of **ibase**. For example, with clamping off and an **ibase** of **3**, the string "AB" would equal **3\^1\*A+3\^0\*B**, which is **3** times **10** plus **11**, or **41**, while with clamping on and an **ibase** of **3**, the string "AB" would be equal to **3\^1\*2+3\^0\*2**, which is **3** times **2** plus **2**, or **8**. This value is *thread-local*; it applies to just the thread it is read on. The default is **true**. **void bcl_setDigitClamp(bool** _digitClamp_**)** : Sets the state of whether digits in number strings that are greater than or equal to the current **ibase** are clamped or not. For more information, see the **bcl_digitClamp(**_void_**)** function. This value is *thread-local*; it applies to just the thread it is set on. **void bcl_gc(**_void_**)** : Garbage collects cached instances of arbitrary-precision numbers. This only frees the memory of numbers that are *not* in use, so it is safe to call at any time. ## Contexts All procedures that take a **BclContext** parameter a require a valid context as an argument. **struct BclCtxt** : A forward declaration for a hidden **struct** type. Clients cannot access the internals of the **struct** type directly. All interactions with the type are done through pointers. See **BclContext** below. **BclContext** : A typedef to a pointer of **struct BclCtxt**. This is the only handle clients can get to **struct BclCtxt**. A **BclContext** contains the values **scale**, **ibase**, and **obase**, as well as a list of numbers. **scale** is a value used to control how many decimal places calculations should use. A value of **0** means that calculations are done on integers only, where applicable, and a value of 20, for example, means that all applicable calculations return results with 20 decimal places. The default is **0**. **ibase** is a value used to control the input base. The minimum **ibase** is **2**, and the maximum is **36**. If **ibase** is **2**, numbers are parsed as though they are in binary, and any digits larger than **1** are clamped. Likewise, a value of **10** means that numbers are parsed as though they are decimal, and any larger digits are clamped. The default is **10**. **obase** is a value used to control the output base. The minimum **obase** is **0** and the maximum is **BC_BASE_MAX** (see the **LIMITS** section). Numbers created in one context are not valid in another context. It is undefined behavior to use a number created in a different context. Contexts are meant to isolate the numbers used by different clients in the same application. Different threads also have different contexts, so any numbers created in one thread are not valid in another thread. To pass values between contexts and threads, use **bcl_string()** to produce a string to pass around, and use **bcl_parse()** to parse the string. It is suggested that the **obase** used to create the string be passed around with the string and used as the **ibase** for **bcl_parse()** to ensure that the number will be the same. **BclContext bcl_ctxt_create(**_void_**)** : Creates a context and returns it. Returns **NULL** if there was an error. **void bcl_ctxt_free(BclContext** _ctxt_**)** : Frees *ctxt*, after which it is no longer valid. It is undefined behavior to attempt to use an invalid context. **BclError bcl_pushContext(BclContext** _ctxt_**)** : Pushes *ctxt* onto bcl(3)'s stack of contexts. *ctxt* must have been created with **bcl_ctxt_create(**_void_**)**. If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this function can return: * **BCL_ERROR_FATAL_ALLOC_ERR** There *must* be a valid context to do any arithmetic. **void bcl_popContext(**_void_**)** : Pops the current context off of the stack, if one exists. **BclContext bcl_context(**_void_**)** : Returns the current context, or **NULL** if no context exists. **void bcl_ctxt_freeNums(BclContext** _ctxt_**)** : Frees all numbers in use that are associated with *ctxt*. It is undefined behavior to attempt to use a number associated with *ctxt* after calling this procedure unless such numbers have been created with **bcl_num_create(**_void_**)** after calling this procedure. **size_t bcl_ctxt_scale(BclContext** _ctxt_**)** : Returns the **scale** for given context. **void bcl_ctxt_setScale(BclContext** _ctxt_**, size_t** _scale_**)** : Sets the **scale** for the given context to the argument *scale*. **size_t bcl_ctxt_ibase(BclContext** _ctxt_**)** : Returns the **ibase** for the given context. **void bcl_ctxt_setIbase(BclContext** _ctxt_**, size_t** _ibase_**)** : Sets the **ibase** for the given context to the argument *ibase*. If the argument *ibase* is invalid, it clamped, so an *ibase* of **0** or **1** is clamped to **2**, and any values above **36** are clamped to **36**. **size_t bcl_ctxt_obase(BclContext** _ctxt_**)** : Returns the **obase** for the given context. **void bcl_ctxt_setObase(BclContext** _ctxt_**, size_t** _obase_**)** : Sets the **obase** for the given context to the argument *obase*. ## Errors **BclError** : An **enum** of possible error codes. See the **ERRORS** section for a complete listing the codes. **BclError bcl_err(BclNumber** _n_**)** : Checks for errors in a **BclNumber**. All functions that can return a **BclNumber** can encode an error in the number, and this function will return the error, if any. If there was no error, it will return **BCL_ERROR_NONE**. There must be a valid current context. ## Numbers All procedures in this section require a valid current context. **BclNumber** : A handle to an arbitrary-precision number. The actual number type is not exposed; the **BclNumber** handle is the only way clients can refer to instances of arbitrary-precision numbers. **BclNumber bcl_num_create(**_void_**)** : Creates and returns a **BclNumber**. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_FATAL_ALLOC_ERR** **void bcl_num_free(BclNumber** _n_**)** : Frees *n*. It is undefined behavior to use *n* after calling this function. **bool bcl_num_neg(BclNumber** _n_**)** : Returns **true** if *n* is negative, **false** otherwise. **void bcl_num_setNeg(BclNumber** _n_**, bool** _neg_**)** : Sets *n*'s sign to *neg*, where **true** is negative, and **false** is positive. **size_t bcl_num_scale(BclNumber** _n_**)** : Returns the *scale* of *n*. The *scale* of a number is the number of decimal places it has after the radix (decimal point). **BclError bcl_num_setScale(BclNumber** _n_**, size_t** _scale_**)** : Sets the *scale* of *n* to the argument *scale*. If the argument *scale* is greater than the *scale* of *n*, *n* is extended. If the argument *scale* is less than the *scale* of *n*, *n* is truncated. If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this function can return: * **BCL_ERROR_INVALID_NUM** * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_FATAL_ALLOC_ERR** **size_t bcl_num_len(BclNumber** _n_**)** : Returns the number of *significant decimal digits* in *n*. ## Conversion All procedures in this section require a valid current context. -All procedures in this section consume the given **BclNumber** arguments that -are not given to pointer arguments. See the **Consumption and Propagation** -subsection below. +All procedures in this section without the **_keep** suffix in their name +consume the given **BclNumber** arguments that are not given to pointer +arguments. See the **Consumption and Propagation** subsection below. **BclNumber bcl_parse(const char \*restrict** _val_**)** : Parses a number string according to the current context's **ibase** and returns the resulting number. *val* must be non-**NULL** and a valid string. See **BCL_ERROR_PARSE_INVALID_STR** in the **ERRORS** section for more information. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_NUM** * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_PARSE_INVALID_STR** * **BCL_ERROR_FATAL_ALLOC_ERR** **char\* bcl_string(BclNumber** _n_**)** : Returns a string representation of *n* according the the current context's **ibase**. The string is dynamically allocated and must be freed by the caller. *n* is consumed; it cannot be used after the call. See the **Consumption and Propagation** subsection below. +**char\* bcl_string_keep(BclNumber** _n_**)** + +: Returns a string representation of *n* according the the current context's + **ibase**. The string is dynamically allocated and must be freed by the + caller. + **BclError bcl_bigdig(BclNumber** _n_**, BclBigDig \***_result_**)** : Converts *n* into a **BclBigDig** and returns the result in the space pointed to by *result*. *a* must be smaller than **BC_OVERFLOW_MAX**. See the **LIMITS** section. If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this function can return: * **BCL_ERROR_INVALID_NUM** * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_MATH_OVERFLOW** *n* is consumed; it cannot be used after the call. See the **Consumption and Propagation** subsection below. +**BclError bcl_bigdig_keep(BclNumber** _n_**, BclBigDig \***_result_**)** + +: Converts *n* into a **BclBigDig** and returns the result in the space + pointed to by *result*. + + *a* must be smaller than **BC_OVERFLOW_MAX**. See the **LIMITS** section. + + If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this + function can return: + + * **BCL_ERROR_INVALID_NUM** + * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_MATH_OVERFLOW** + **BclNumber bcl_bigdig2num(BclBigDig** _val_**)** : Creates a **BclNumber** from *val*. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_FATAL_ALLOC_ERR** ## Math All procedures in this section require a valid current context. +All procedures in this section without the **_keep** suffix in their name +consume the given **BclNumber** arguments that are not given to pointer +arguments. See the **Consumption and Propagation** subsection below. + All procedures in this section can return the following errors: * **BCL_ERROR_INVALID_NUM** * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_FATAL_ALLOC_ERR** **BclNumber bcl_add(BclNumber** _a_**, BclNumber** _b_**)** : Adds *a* and *b* and returns the result. The *scale* of the result is the max of the *scale*s of *a* and *b*. *a* and *b* are consumed; they cannot be used after the call. See the **Consumption and Propagation** subsection below. *a* and *b* can be the same number. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_NUM** * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_FATAL_ALLOC_ERR** +**BclNumber bcl_add_keep(BclNumber** _a_**, BclNumber** _b_**)** + +: Adds *a* and *b* and returns the result. The *scale* of the result is the + max of the *scale*s of *a* and *b*. + + *a* and *b* can be the same number. + + bcl(3) will encode an error in the return value, if there was one. The error + can be queried with **bcl_err(BclNumber)**. Possible errors include: + + * **BCL_ERROR_INVALID_NUM** + * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_FATAL_ALLOC_ERR** + **BclNumber bcl_sub(BclNumber** _a_**, BclNumber** _b_**)** : Subtracts *b* from *a* and returns the result. The *scale* of the result is the max of the *scale*s of *a* and *b*. *a* and *b* are consumed; they cannot be used after the call. See the **Consumption and Propagation** subsection below. *a* and *b* can be the same number. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_NUM** * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_FATAL_ALLOC_ERR** +**BclNumber bcl_sub_keep(BclNumber** _a_**, BclNumber** _b_**)** + +: Subtracts *b* from *a* and returns the result. The *scale* of the result is + the max of the *scale*s of *a* and *b*. + + *a* and *b* can be the same number. + + bcl(3) will encode an error in the return value, if there was one. The error + can be queried with **bcl_err(BclNumber)**. Possible errors include: + + * **BCL_ERROR_INVALID_NUM** + * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_FATAL_ALLOC_ERR** + **BclNumber bcl_mul(BclNumber** _a_**, BclNumber** _b_**)** : Multiplies *a* and *b* and returns the result. If *ascale* is the *scale* of *a* and *bscale* is the *scale* of *b*, the *scale* of the result is equal to **min(ascale+bscale,max(scale,ascale,bscale))**, where **min()** and **max()** return the obvious values. *a* and *b* are consumed; they cannot be used after the call. See the **Consumption and Propagation** subsection below. *a* and *b* can be the same number. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_NUM** * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_FATAL_ALLOC_ERR** +**BclNumber bcl_mul_keep(BclNumber** _a_**, BclNumber** _b_**)** + +: Multiplies *a* and *b* and returns the result. If *ascale* is the *scale* of + *a* and *bscale* is the *scale* of *b*, the *scale* of the result is equal + to **min(ascale+bscale,max(scale,ascale,bscale))**, where **min()** and + **max()** return the obvious values. + + *a* and *b* can be the same number. + + bcl(3) will encode an error in the return value, if there was one. The error + can be queried with **bcl_err(BclNumber)**. Possible errors include: + + * **BCL_ERROR_INVALID_NUM** + * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_FATAL_ALLOC_ERR** + **BclNumber bcl_div(BclNumber** _a_**, BclNumber** _b_**)** : Divides *a* by *b* and returns the result. The *scale* of the result is the *scale* of the current context. *b* cannot be **0**. *a* and *b* are consumed; they cannot be used after the call. See the **Consumption and Propagation** subsection below. *a* and *b* can be the same number. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_NUM** * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_MATH_DIVIDE_BY_ZERO** * **BCL_ERROR_FATAL_ALLOC_ERR** +**BclNumber bcl_div_keep(BclNumber** _a_**, BclNumber** _b_**)** + +: Divides *a* by *b* and returns the result. The *scale* of the result is the + *scale* of the current context. + + *b* cannot be **0**. + + *a* and *b* can be the same number. + + bcl(3) will encode an error in the return value, if there was one. The error + can be queried with **bcl_err(BclNumber)**. Possible errors include: + + * **BCL_ERROR_INVALID_NUM** + * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_MATH_DIVIDE_BY_ZERO** + * **BCL_ERROR_FATAL_ALLOC_ERR** + **BclNumber bcl_mod(BclNumber** _a_**, BclNumber** _b_**)** : Divides *a* by *b* to the *scale* of the current context, computes the modulus **a-(a/b)\*b**, and returns the modulus. *b* cannot be **0**. *a* and *b* are consumed; they cannot be used after the call. See the **Consumption and Propagation** subsection below. *a* and *b* can be the same number. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_NUM** * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_MATH_DIVIDE_BY_ZERO** * **BCL_ERROR_FATAL_ALLOC_ERR** +**BclNumber bcl_mod_keep(BclNumber** _a_**, BclNumber** _b_**)** + +: Divides *a* by *b* to the *scale* of the current context, computes the + modulus **a-(a/b)\*b**, and returns the modulus. + + *b* cannot be **0**. + + *a* and *b* can be the same number. + + bcl(3) will encode an error in the return value, if there was one. The error + can be queried with **bcl_err(BclNumber)**. Possible errors include: + + * **BCL_ERROR_INVALID_NUM** + * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_MATH_DIVIDE_BY_ZERO** + * **BCL_ERROR_FATAL_ALLOC_ERR** + **BclNumber bcl_pow(BclNumber** _a_**, BclNumber** _b_**)** : Calculates *a* to the power of *b* to the *scale* of the current context. *b* must be an integer, but can be negative. If it is negative, *a* must be non-zero. *b* must be an integer. If *b* is negative, *a* must not be **0**. *a* must be smaller than **BC_OVERFLOW_MAX**. See the **LIMITS** section. *a* and *b* are consumed; they cannot be used after the call. See the **Consumption and Propagation** subsection below. *a* and *b* can be the same number. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_NUM** * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_MATH_NON_INTEGER** * **BCL_ERROR_MATH_OVERFLOW** * **BCL_ERROR_MATH_DIVIDE_BY_ZERO** * **BCL_ERROR_FATAL_ALLOC_ERR** +**BclNumber bcl_pow_keep(BclNumber** _a_**, BclNumber** _b_**)** + +: Calculates *a* to the power of *b* to the *scale* of the current context. + *b* must be an integer, but can be negative. If it is negative, *a* must + be non-zero. + + *b* must be an integer. If *b* is negative, *a* must not be **0**. + + *a* must be smaller than **BC_OVERFLOW_MAX**. See the **LIMITS** section. + + *a* and *b* can be the same number. + + bcl(3) will encode an error in the return value, if there was one. The error + can be queried with **bcl_err(BclNumber)**. Possible errors include: + + * **BCL_ERROR_INVALID_NUM** + * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_MATH_NON_INTEGER** + * **BCL_ERROR_MATH_OVERFLOW** + * **BCL_ERROR_MATH_DIVIDE_BY_ZERO** + * **BCL_ERROR_FATAL_ALLOC_ERR** + **BclNumber bcl_lshift(BclNumber** _a_**, BclNumber** _b_**)** : Shifts *a* left (moves the radix right) by *b* places and returns the result. This is done in decimal. *b* must be an integer. *b* must be an integer. *a* and *b* are consumed; they cannot be used after the call. See the **Consumption and Propagation** subsection below. *a* and *b* can be the same number. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_NUM** * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_MATH_NON_INTEGER** * **BCL_ERROR_FATAL_ALLOC_ERR** +**BclNumber bcl_lshift_keep(BclNumber** _a_**, BclNumber** _b_**)** + +: Shifts *a* left (moves the radix right) by *b* places and returns the + result. This is done in decimal. *b* must be an integer. + + *b* must be an integer. + + *a* and *b* can be the same number. + + bcl(3) will encode an error in the return value, if there was one. The error + can be queried with **bcl_err(BclNumber)**. Possible errors include: + + * **BCL_ERROR_INVALID_NUM** + * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_MATH_NON_INTEGER** + * **BCL_ERROR_FATAL_ALLOC_ERR** + **BclNumber bcl_rshift(BclNumber** _a_**, BclNumber** _b_**)** : Shifts *a* right (moves the radix left) by *b* places and returns the result. This is done in decimal. *b* must be an integer. *b* must be an integer. *a* and *b* are consumed; they cannot be used after the call. See the **Consumption and Propagation** subsection below. *a* and *b* can be the same number. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_NUM** * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_MATH_NON_INTEGER** * **BCL_ERROR_FATAL_ALLOC_ERR** +**BclNumber bcl_rshift_keep(BclNumber** _a_**, BclNumber** _b_**)** + +: Shifts *a* right (moves the radix left) by *b* places and returns the + result. This is done in decimal. *b* must be an integer. + + *b* must be an integer. + + *a* and *b* can be the same number. + + bcl(3) will encode an error in the return value, if there was one. The error + can be queried with **bcl_err(BclNumber)**. Possible errors include: + + * **BCL_ERROR_INVALID_NUM** + * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_MATH_NON_INTEGER** + * **BCL_ERROR_FATAL_ALLOC_ERR** + **BclNumber bcl_sqrt(BclNumber** _a_**)** : Calculates the square root of *a* and returns the result. The *scale* of the result is equal to the **scale** of the current context. *a* cannot be negative. *a* is consumed; it cannot be used after the call. See the **Consumption and Propagation** subsection below. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_NUM** * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_MATH_NEGATIVE** * **BCL_ERROR_FATAL_ALLOC_ERR** +**BclNumber bcl_sqrt_keep(BclNumber** _a_**)** + +: Calculates the square root of *a* and returns the result. The *scale* of the + result is equal to the **scale** of the current context. + + *a* cannot be negative. + + bcl(3) will encode an error in the return value, if there was one. The error + can be queried with **bcl_err(BclNumber)**. Possible errors include: + + * **BCL_ERROR_INVALID_NUM** + * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_MATH_NEGATIVE** + * **BCL_ERROR_FATAL_ALLOC_ERR** + **BclError bcl_divmod(BclNumber** _a_**, BclNumber** _b_**, BclNumber \***_c_**, BclNumber \***_d_**)** : Divides *a* by *b* and returns the quotient in a new number which is put into the space pointed to by *c*, and puts the modulus in a new number which is put into the space pointed to by *d*. *b* cannot be **0**. *a* and *b* are consumed; they cannot be used after the call. See the **Consumption and Propagation** subsection below. *c* and *d* cannot point to the same place, nor can they point to the space occupied by *a* or *b*. If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this function can return: * **BCL_ERROR_INVALID_NUM** * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_MATH_DIVIDE_BY_ZERO** * **BCL_ERROR_FATAL_ALLOC_ERR** +**BclError bcl_divmod_keep(BclNumber** _a_**, BclNumber** _b_**, BclNumber \***_c_**, BclNumber \***_d_**)** + +: Divides *a* by *b* and returns the quotient in a new number which is put + into the space pointed to by *c*, and puts the modulus in a new number which + is put into the space pointed to by *d*. + + *b* cannot be **0**. + + *c* and *d* cannot point to the same place, nor can they point to the space + occupied by *a* or *b*. + + If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this + function can return: + + * **BCL_ERROR_INVALID_NUM** + * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_MATH_DIVIDE_BY_ZERO** + * **BCL_ERROR_FATAL_ALLOC_ERR** + **BclNumber bcl_modexp(BclNumber** _a_**, BclNumber** _b_**, BclNumber** _c_**)** : Computes a modular exponentiation where *a* is the base, *b* is the exponent, and *c* is the modulus, and returns the result. The *scale* of the result is equal to the **scale** of the current context. *a*, *b*, and *c* must be integers. *c* must not be **0**. *b* must not be negative. *a*, *b*, and *c* are consumed; they cannot be used after the call. See the **Consumption and Propagation** subsection below. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_NUM** * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_MATH_NEGATIVE** * **BCL_ERROR_MATH_NON_INTEGER** * **BCL_ERROR_MATH_DIVIDE_BY_ZERO** * **BCL_ERROR_FATAL_ALLOC_ERR** +**BclNumber bcl_modexp_keep(BclNumber** _a_**, BclNumber** _b_**, BclNumber** _c_**)** + +: Computes a modular exponentiation where *a* is the base, *b* is the + exponent, and *c* is the modulus, and returns the result. The *scale* of the + result is equal to the **scale** of the current context. + + *a*, *b*, and *c* must be integers. *c* must not be **0**. *b* must not be + negative. + + bcl(3) will encode an error in the return value, if there was one. The error + can be queried with **bcl_err(BclNumber)**. Possible errors include: + + * **BCL_ERROR_INVALID_NUM** + * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_MATH_NEGATIVE** + * **BCL_ERROR_MATH_NON_INTEGER** + * **BCL_ERROR_MATH_DIVIDE_BY_ZERO** + * **BCL_ERROR_FATAL_ALLOC_ERR** + ## Miscellaneous **void bcl_zero(BclNumber** _n_**)** : Sets *n* to **0**. **void bcl_one(BclNumber** _n_**)** : Sets *n* to **1**. **ssize_t bcl_cmp(BclNumber** _a_**, BclNumber** _b_**)** : Compares *a* and *b* and returns **0** if *a* and *b* are equal, **<0** if *a* is less than *b*, and **>0** if *a* is greater than *b*. **BclError bcl_copy(BclNumber** _d_**, BclNumber** _s_**)** : Copies *s* into *d*. If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this function can return: * **BCL_ERROR_INVALID_NUM** * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_FATAL_ALLOC_ERR** **BclNumber bcl_dup(BclNumber** _s_**)** : Creates and returns a new **BclNumber** that is a copy of *s*. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_NUM** * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_FATAL_ALLOC_ERR** ## Pseudo-Random Number Generator The pseudo-random number generator in bcl(3) is a *seeded* PRNG. Given the same seed twice, it will produce the same sequence of pseudo-random numbers twice. By default, bcl(3) attempts to seed the PRNG with data from **/dev/urandom**. If that fails, it seeds itself with by calling **libc**'s **srand(time(NULL))** and then calling **rand()** for each byte, since **rand()** is only guaranteed to return **15** bits. This should provide fairly good seeding in the standard case while also remaining fairly portable. If necessary, the PRNG can be reseeded with one of the following functions: * **bcl_rand_seedWithNum(BclNumber)** * **bcl_rand_seed(unsigned char[**_BCL_SEED_SIZE_**])** * **bcl_rand_reseed(**_void_**)** +All procedures in this section without the **_keep** suffix in their name +consume the given **BclNumber** arguments that are not given to pointer +arguments. See the **Consumption and Propagation** subsection below. + The following items allow clients to use the pseudo-random number generator. All procedures require a valid current context. **BCL_SEED_ULONGS** : The number of **unsigned long**'s in a seed for bcl(3)'s random number generator. **BCL_SEED_SIZE** : The size, in **char**'s, of a seed for bcl(3)'s random number generator. **BclBigDig** : bcl(3)'s overflow type (see the **PERFORMANCE** section). **BclRandInt** : An unsigned integer type returned by bcl(3)'s random number generator. **BclNumber bcl_irand(BclNumber** _a_**)** : Returns a random number that is not larger than *a* in a new number. If *a* is **0** or **1**, the new number is equal to **0**. The bound is unlimited, so it is not bound to the size of **BclRandInt**. This is done by generating as many random numbers as necessary, multiplying them by certain exponents, and adding them all together. *a* must be an integer and non-negative. - *a* is consumed; it cannot be used after the call. See the - **Consumption and Propagation** subsection below. + *a* is consumed; it cannot be used after the call. See the **Consumption and + Propagation** subsection below. + + This procedure requires a valid current context. + + bcl(3) will encode an error in the return value, if there was one. The error + can be queried with **bcl_err(BclNumber)**. Possible errors include: + + * **BCL_ERROR_INVALID_NUM** + * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_MATH_NEGATIVE** + * **BCL_ERROR_MATH_NON_INTEGER** + * **BCL_ERROR_FATAL_ALLOC_ERR** + +**BclNumber bcl_irand_keep(BclNumber** _a_**)** + +: Returns a random number that is not larger than *a* in a new number. If *a* + is **0** or **1**, the new number is equal to **0**. The bound is unlimited, + so it is not bound to the size of **BclRandInt**. This is done by generating + as many random numbers as necessary, multiplying them by certain exponents, + and adding them all together. + + *a* must be an integer and non-negative. This procedure requires a valid current context. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_NUM** * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_MATH_NEGATIVE** * **BCL_ERROR_MATH_NON_INTEGER** * **BCL_ERROR_FATAL_ALLOC_ERR** **BclNumber bcl_frand(size_t** _places_**)** : Returns a random number between **0** (inclusive) and **1** (exclusive) that has *places* decimal digits after the radix (decimal point). There are no limits on *places*. This procedure requires a valid current context. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_FATAL_ALLOC_ERR** **BclNumber bcl_ifrand(BclNumber** _a_**, size_t** _places_**)** : Returns a random number less than *a* with *places* decimal digits after the radix (decimal point). There are no limits on *a* or *places*. *a* must be an integer and non-negative. - *a* is consumed; it cannot be used after the call. See the - **Consumption and Propagation** subsection below. + *a* is consumed; it cannot be used after the call. See the **Consumption and + Propagation** subsection below. + + This procedure requires a valid current context. + + bcl(3) will encode an error in the return value, if there was one. The error + can be queried with **bcl_err(BclNumber)**. Possible errors include: + + * **BCL_ERROR_INVALID_NUM** + * **BCL_ERROR_INVALID_CONTEXT** + * **BCL_ERROR_MATH_NEGATIVE** + * **BCL_ERROR_MATH_NON_INTEGER** + * **BCL_ERROR_FATAL_ALLOC_ERR** + +**BclNumber bcl_ifrand_keep(BclNumber** _a_**, size_t** _places_**)** + +: Returns a random number less than *a* with *places* decimal digits after the + radix (decimal point). There are no limits on *a* or *places*. + + *a* must be an integer and non-negative. This procedure requires a valid current context. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_NUM** * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_MATH_NEGATIVE** * **BCL_ERROR_MATH_NON_INTEGER** * **BCL_ERROR_FATAL_ALLOC_ERR** **BclError bcl_rand_seedWithNum(BclNumber** _n_**)** : Seeds the PRNG with *n*. - *n* is *not* consumed. + *n* is consumed. + + This procedure requires a valid current context. + + If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this + function can return: + + * **BCL_ERROR_INVALID_NUM** + * **BCL_ERROR_INVALID_CONTEXT** + + Note that if **bcl_rand_seed2num(**_void_**)** or + **bcl_rand_seed2num_err(BclNumber)** are called right after this function, + they are not guaranteed to return a number equal to *n*. + +**BclError bcl_rand_seedWithNum_keep(BclNumber** _n_**)** + +: Seeds the PRNG with *n*. This procedure requires a valid current context. If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this function can return: * **BCL_ERROR_INVALID_NUM** * **BCL_ERROR_INVALID_CONTEXT** Note that if **bcl_rand_seed2num(**_void_**)** or **bcl_rand_seed2num_err(BclNumber)** are called right after this function, they are not guaranteed to return a number equal to *n*. **BclError bcl_rand_seed(unsigned char** _seed_**[**_BCL_SEED_SIZE_**])** : Seeds the PRNG with the bytes in *seed*. If there was no error, **BCL_ERROR_NONE** is returned. Otherwise, this function can return: * **BCL_ERROR_INVALID_CONTEXT** **void bcl_rand_reseed(**_void_**)** : Reseeds the PRNG with the default reseeding behavior. First, it attempts to read data from **/dev/urandom** and falls back to **libc**'s **rand()**. This procedure cannot fail. **BclNumber bcl_rand_seed2num(**_void_**)** : Returns the current seed of the PRNG as a **BclNumber**. This procedure requires a valid current context. bcl(3) will encode an error in the return value, if there was one. The error can be queried with **bcl_err(BclNumber)**. Possible errors include: * **BCL_ERROR_INVALID_CONTEXT** * **BCL_ERROR_FATAL_ALLOC_ERR** **BclRandInt bcl_rand_int(**_void_**)** : Returns a random integer between **0** and **BC_RAND_MAX** (inclusive). This procedure cannot fail. **BclRandInt bcl_rand_bounded(BclRandInt** _bound_**)** : Returns a random integer between **0** and *bound* (exclusive). Bias is removed before returning the integer. This procedure cannot fail. ## Consumption and Propagation Some functions are listed as consuming some or all of their arguments. This means that the arguments are freed, regardless of if there were errors or not. This is to enable compact code like the following: BclNumber n = bcl_num_add(bcl_num_mul(a, b), bcl_num_div(c, d)); If arguments to those functions were not consumed, memory would be leaked until reclaimed with **bcl_ctxt_freeNums(BclContext)**. When errors occur, they are propagated through. The result should always be checked with **bcl_err(BclNumber)**, so the example above should properly be: BclNumber n = bcl_num_add(bcl_num_mul(a, b), bcl_num_div(c, d)); - if (bc_num_err(n) != BCL_ERROR_NONE) { + if (bcl_err(n) != BCL_ERROR_NONE) { // Handle the error. } # ERRORS Most functions in bcl(3) return, directly or indirectly, any one of the error codes defined in **BclError**. The complete list of codes is the following: **BCL_ERROR_NONE** : Success; no error occurred. **BCL_ERROR_INVALID_NUM** : An invalid **BclNumber** was given as a parameter. **BCL_ERROR_INVALID_CONTEXT** : An invalid **BclContext** is being used. **BCL_ERROR_MATH_NEGATIVE** : A negative number was given as an argument to a parameter that cannot accept negative numbers, such as for square roots. **BCL_ERROR_MATH_NON_INTEGER** : A non-integer was given as an argument to a parameter that cannot accept non-integer numbers, such as for the second parameter of **bcl_num_pow()**. **BCL_ERROR_MATH_OVERFLOW** : A number that would overflow its result was given as an argument, such as for converting a **BclNumber** to a **BclBigDig**. **BCL_ERROR_MATH_DIVIDE_BY_ZERO** : A divide by zero occurred. **BCL_ERROR_PARSE_INVALID_STR** : An invalid number string was passed to a parsing function. A valid number string can only be one radix (period). In addition, any lowercase ASCII letters, symbols, or non-ASCII characters are invalid. It is allowed for the first character to be a dash. In that case, the number is considered to be negative. There is one exception to the above: one lowercase **e** is allowed in the number, after the radix, if it exists. If the letter **e** exists, the number is considered to be in scientific notation, where the part before the **e** is the number, and the part after, which must be an integer, is the exponent. There can be a dash right after the **e** to indicate a negative exponent. **WARNING**: Both the number and the exponent in scientific notation are interpreted according to the current **ibase**, but the number is still multiplied by **10\^exponent** regardless of the current **ibase**. For example, if **ibase** is **16** and bcl(3) is given the number string **FFeA**, the resulting decimal number will be **2550000000000**, and if bcl(3) is given the number string **10e-4**, the resulting decimal number will be **0.0016**. **BCL_ERROR_FATAL_ALLOC_ERR** : bcl(3) failed to allocate memory. If clients call **bcl_setAbortOnFatalError()** with an **true** argument, this error will cause bcl(3) to throw a **SIGABRT**. This behavior can also be turned off later by calling that same function with a **false** argument. By default, this behavior is off. It is highly recommended that client libraries do *not* activate this behavior. **BCL_ERROR_FATAL_UNKNOWN_ERR** : An unknown error occurred. If clients call **bcl_setAbortOnFatalError()** with an **true** argument, this error will cause bcl(3) to throw a **SIGABRT**. This behavior can also be turned off later by calling that same function with a **false** argument. By default, this behavior is off. It is highly recommended that client libraries do *not* activate this behavior. # ATTRIBUTES bcl(3) is *MT-Safe*: it is safe to call any functions from more than one thread. However, is is *not* safe to pass any data between threads except for strings returned by **bcl_string()**. bcl(3) is not *async-signal-safe*. It was not possible to make bcl(3) safe with signals and also make it safe with multiple threads. If it is necessary to be able to interrupt bcl(3), spawn a separate thread to run the calculation. # PERFORMANCE Most bc(1) implementations use **char** types to calculate the value of **1** decimal digit at a time, but that can be slow. bcl(3) does something different. It uses large integers to calculate more than **1** decimal digit at a time. If built in a environment where **BC_LONG_BIT** (see the **LIMITS** section) is **64**, then each integer has **9** decimal digits. If built in an environment where **BC_LONG_BIT** is **32** then each integer has **4** decimal digits. This value (the number of decimal digits per large integer) is called **BC_BASE_DIGS**. In addition, this bcl(3) uses an even larger integer for overflow checking. This integer type depends on the value of **BC_LONG_BIT**, but is always at least twice as large as the integer type used to store digits. # LIMITS The following are the limits on bcl(3): **BC_LONG_BIT** : The number of bits in the **long** type in the environment where bcl(3) was built. This determines how many decimal digits can be stored in a single large integer (see the **PERFORMANCE** section). **BC_BASE_DIGS** : The number of decimal digits per large integer (see the **PERFORMANCE** section). Depends on **BC_LONG_BIT**. **BC_BASE_POW** : The max decimal number that each large integer can store (see **BC_BASE_DIGS**) plus **1**. Depends on **BC_BASE_DIGS**. **BC_OVERFLOW_MAX** : The max number that the overflow type (see the **PERFORMANCE** section) can hold. Depends on **BC_LONG_BIT**. **BC_BASE_MAX** : The maximum output base. Set at **BC_BASE_POW**. **BC_SCALE_MAX** : The maximum **scale**. Set at **BC_OVERFLOW_MAX-1**. **BC_NUM_MAX** : The maximum length of a number (in decimal digits), which includes digits after the decimal point. Set at **BC_OVERFLOW_MAX-1**. **BC_RAND_MAX** : The maximum integer (inclusive) returned by the **bcl_rand_int()** function. Set at **2\^BC_LONG_BIT-1**. Exponent : The maximum allowable exponent (positive or negative). Set at **BC_OVERFLOW_MAX**. These limits are meant to be effectively non-existent; the limits are so large (at least on 64-bit machines) that there should not be any point at which they become a problem. In fact, memory should be exhausted before these limits should be hit. # SEE ALSO bc(1) and dc(1) # STANDARDS bcl(3) is compliant with the arithmetic defined in the IEEE Std 1003.1-2017 (“POSIX.1-2017”) specification at https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html for bc(1). Note that the specification explicitly says that bc(1) only accepts numbers that use a period (**.**) as a radix point, regardless of the value of **LC_NUMERIC**. This is also true of bcl(3). # BUGS None are known. Report bugs at https://git.gavinhoward.com/gavin/bc. # AUTHORS Gavin D. Howard and contributors. diff --git a/contrib/bc/src/data.c b/contrib/bc/src/data.c index abaf3b8e39ab..b57e1fc4c02d 100644 --- a/contrib/bc/src/data.c +++ b/contrib/bc/src/data.c @@ -1,1347 +1,1364 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2023 Gavin D. Howard and contributors. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * ***************************************************************************** * * Constant data for bc. * */ #include #include #include #include #include #include #include #include #include #include #include #include #include #if !BC_ENABLE_LIBRARY #if BC_ENABLED /// The bc signal message and its length. const char bc_sig_msg[] = "\ninterrupt (type \"quit\" to exit)\n"; const uchar bc_sig_msg_len = (uchar) (sizeof(bc_sig_msg) - 1); #endif // BC_ENABLED #if DC_ENABLED /// The dc signal message and its length. const char dc_sig_msg[] = "\ninterrupt (type \"q\" to exit)\n"; const uchar dc_sig_msg_len = (uchar) (sizeof(dc_sig_msg) - 1); #endif // DC_ENABLED // clang-format off /// The copyright banner. const char bc_copyright[] = "Copyright (c) 2018-2023 Gavin D. Howard and contributors\n" "Report bugs at: https://git.gavinhoward.com/gavin/bc\n\n" "This is free software with ABSOLUTELY NO WARRANTY.\n"; // clang-format on #ifdef __OpenBSD__ #if BC_ENABLE_EXTRA_MATH #if BC_ENABLE_HISTORY /// The pledges for starting bc. const char bc_pledge_start[] = "rpath stdio tty unveil"; /// The final pledges with history enabled. const char bc_pledge_end_history[] = "rpath stdio tty"; #else // BC_ENABLE_HISTORY /// The pledges for starting bc. const char bc_pledge_start[] = "rpath stdio unveil"; #endif // BC_ENABLE_HISTORY /// The final pledges with history history disabled. const char bc_pledge_end[] = "rpath stdio"; #else // BC_ENABLE_EXTRA_MATH #if BC_ENABLE_HISTORY /// The pledges for starting bc. const char bc_pledge_start[] = "rpath stdio tty"; /// The final pledges with history enabled. const char bc_pledge_end_history[] = "stdio tty"; #else // BC_ENABLE_HISTORY /// The pledges for starting bc. const char bc_pledge_start[] = "rpath stdio"; #endif // BC_ENABLE_HISTORY /// The final pledges with history history disabled. const char bc_pledge_end[] = "stdio"; #endif // BC_ENABLE_EXTRA_MATH #else // __OpenBSD__ /// The pledges for starting bc. const char bc_pledge_start[] = ""; #if BC_ENABLE_HISTORY /// The final pledges with history enabled. const char bc_pledge_end_history[] = ""; #endif // BC_ENABLE_HISTORY /// The final pledges with history history disabled. const char bc_pledge_end[] = ""; #endif // __OpenBSD__ /// The list of long options. There is a zero set at the end for detecting the /// end. const BcOptLong bc_args_lopt[] = { { "digit-clamp", BC_OPT_NONE, 'c' }, { "expression", BC_OPT_REQUIRED, 'e' }, { "file", BC_OPT_REQUIRED, 'f' }, { "help", BC_OPT_NONE, 'h' }, { "interactive", BC_OPT_NONE, 'i' }, { "ibase", BC_OPT_REQUIRED, 'I' }, { "leading-zeroes", BC_OPT_NONE, 'z' }, { "no-line-length", BC_OPT_NONE, 'L' }, { "obase", BC_OPT_REQUIRED, 'O' }, { "no-digit-clamp", BC_OPT_NONE, 'C' }, { "no-prompt", BC_OPT_NONE, 'P' }, { "no-read-prompt", BC_OPT_NONE, 'R' }, { "scale", BC_OPT_REQUIRED, 'S' }, #if BC_ENABLE_EXTRA_MATH { "seed", BC_OPT_REQUIRED, 'E' }, #endif // BC_ENABLE_EXTRA_MATH #if BC_ENABLED { "global-stacks", BC_OPT_BC_ONLY, 'g' }, { "mathlib", BC_OPT_BC_ONLY, 'l' }, { "quiet", BC_OPT_BC_ONLY, 'q' }, { "redefine", BC_OPT_REQUIRED_BC_ONLY, 'r' }, { "standard", BC_OPT_BC_ONLY, 's' }, { "warn", BC_OPT_BC_ONLY, 'w' }, #endif // BC_ENABLED { "version", BC_OPT_NONE, 'v' }, { "version", BC_OPT_NONE, 'V' }, #if DC_ENABLED { "extended-register", BC_OPT_DC_ONLY, 'x' }, #endif // DC_ENABLED { NULL, 0, 0 }, }; // clang-format off /// The default error category strings. const char *bc_errs[] = { "Math error:", "Parse error:", "Runtime error:", "Fatal error:", #if BC_ENABLED "Warning:", #endif // BC_ENABLED }; // clang-format on /// The error category for each error. const uchar bc_err_ids[] = { BC_ERR_IDX_MATH, BC_ERR_IDX_MATH, BC_ERR_IDX_MATH, BC_ERR_IDX_MATH, BC_ERR_IDX_FATAL, BC_ERR_IDX_FATAL, BC_ERR_IDX_FATAL, BC_ERR_IDX_FATAL, BC_ERR_IDX_FATAL, BC_ERR_IDX_FATAL, BC_ERR_IDX_FATAL, BC_ERR_IDX_FATAL, BC_ERR_IDX_FATAL, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, #if BC_ENABLED BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, #endif // BC_ENABLED }; /// The default error messages. There are NULL pointers because the positions /// must be preserved for the locales. const char* const bc_err_msgs[] = { "negative number", "non-integer number", "overflow: number cannot fit", "divide by 0", "memory allocation failed", "I/O error", "cannot open file: %s", "file is not text: %s", "path is a directory: %s", "bad command-line option: \"%s\"", "option requires an argument: '%c' (\"%s\")", "option takes no arguments: '%c' (\"%s\")", "bad option argument: \"%s\"", "bad ibase: must be [%lu, %lu]", "bad obase: must be [%lu, %lu]", "bad scale: must be [%lu, %lu]", "bad read() expression", "read() call inside of a read() call", "variable or array element is the wrong type", #if DC_ENABLED "stack has too few elements", "stack for register \"%s\" has too few elements", #else // DC_ENABLED NULL, NULL, #endif // DC_ENABLED #if BC_ENABLED "wrong number of parameters; need %zu, have %zu", "undefined function: %s()", "cannot use a void value in an expression", #else NULL, NULL, NULL, #endif // BC_ENABLED "end of file", "bad character '%c'", "string end cannot be found", "comment end cannot be found", "bad token", #if BC_ENABLED "bad expression", "empty expression", "bad print or stream statement", "bad function definition", ("bad assignment: left side must be scale, ibase, " "obase, seed, last, var, or array element"), "no auto variable found", "function parameter or auto \"%s%s\" already exists", "block end cannot be found", "cannot return a value from void function: %s()", "var cannot be a reference: %s", "POSIX does not allow names longer than 1 character: %s", "POSIX does not allow '#' script comments", "POSIX does not allow the following keyword: %s", "POSIX does not allow a period ('.') as a shortcut for the last result", "POSIX requires parentheses around return expressions", "POSIX does not allow the following operator: %s", "POSIX does not allow comparison operators outside if statements or loops", "POSIX requires 0 or 1 comparison operators per condition", "POSIX requires all 3 parts of a for loop to be non-empty", "POSIX requires a newline between a semicolon and a function definition", #if BC_ENABLE_EXTRA_MATH "POSIX does not allow exponential notation", #else NULL, #endif // BC_ENABLE_EXTRA_MATH "POSIX does not allow array references as function parameters", "POSIX does not allow void functions", "POSIX requires the left brace be on the same line as the function header", "POSIX does not allow strings to be assigned to variables or arrays", #endif // BC_ENABLED }; #endif // !BC_ENABLE_LIBRARY /// The destructors corresponding to BcDtorType enum items. const BcVecFree bc_vec_dtors[] = { NULL, bc_vec_free, bc_num_free, #if !BC_ENABLE_LIBRARY #if BC_DEBUG bc_func_free, #endif // BC_DEBUG bc_slab_free, bc_const_free, bc_result_free, #if BC_ENABLE_HISTORY && !BC_ENABLE_LINE_LIB bc_history_string_free, #endif // BC_ENABLE_HISTORY && !BC_ENABLE_LINE_LIB #else // !BC_ENABLE_LIBRARY bcl_num_destruct, #endif // !BC_ENABLE_LIBRARY }; #if !BC_ENABLE_LIBRARY #if BC_ENABLE_EDITLINE /// The normal path to the editrc. const char bc_history_editrc[] = "/.editrc"; /// The length of the normal path to the editrc. const size_t bc_history_editrc_len = sizeof(bc_history_editrc) - 1; #endif // BC_ENABLE_EDITLINE #if BC_ENABLE_HISTORY && !BC_ENABLE_LINE_LIB /// A flush type for not clearing current extras but not saving new ones either. const BcFlushType bc_flush_none = BC_FLUSH_NO_EXTRAS_NO_CLEAR; /// A flush type for clearing extras and not saving new ones. const BcFlushType bc_flush_err = BC_FLUSH_NO_EXTRAS_CLEAR; /// A flush type for clearing previous extras and saving new ones. const BcFlushType bc_flush_save = BC_FLUSH_SAVE_EXTRAS_CLEAR; /// A list of known bad terminals. const char* bc_history_bad_terms[] = { "dumb", "cons25", "emacs", NULL }; /// A constant for tabs and its length. My tab handling is dumb and always /// outputs the entire thing. const char bc_history_tab[] = "\t"; const size_t bc_history_tab_len = sizeof(bc_history_tab) - 1; /// A list of wide chars. These are listed in ascending order for efficiency. const uint32_t bc_history_wchars[][2] = { { 0x1100, 0x115F }, { 0x231A, 0x231B }, { 0x2329, 0x232A }, { 0x23E9, 0x23EC }, { 0x23F0, 0x23F0 }, { 0x23F3, 0x23F3 }, { 0x25FD, 0x25FE }, { 0x2614, 0x2615 }, { 0x2648, 0x2653 }, { 0x267F, 0x267F }, { 0x2693, 0x2693 }, { 0x26A1, 0x26A1 }, { 0x26AA, 0x26AB }, { 0x26BD, 0x26BE }, { 0x26C4, 0x26C5 }, { 0x26CE, 0x26CE }, { 0x26D4, 0x26D4 }, { 0x26EA, 0x26EA }, { 0x26F2, 0x26F3 }, { 0x26F5, 0x26F5 }, { 0x26FA, 0x26FA }, { 0x26FD, 0x26FD }, { 0x2705, 0x2705 }, { 0x270A, 0x270B }, { 0x2728, 0x2728 }, { 0x274C, 0x274C }, { 0x274E, 0x274E }, { 0x2753, 0x2755 }, { 0x2757, 0x2757 }, { 0x2795, 0x2797 }, { 0x27B0, 0x27B0 }, { 0x27BF, 0x27BF }, { 0x2B1B, 0x2B1C }, { 0x2B50, 0x2B50 }, { 0x2B55, 0x2B55 }, { 0x2E80, 0x2E99 }, { 0x2E9B, 0x2EF3 }, { 0x2F00, 0x2FD5 }, { 0x2FF0, 0x2FFB }, { 0x3001, 0x303E }, { 0x3041, 0x3096 }, { 0x3099, 0x30FF }, { 0x3105, 0x312D }, { 0x3131, 0x318E }, { 0x3190, 0x31BA }, { 0x31C0, 0x31E3 }, { 0x31F0, 0x321E }, { 0x3220, 0x3247 }, { 0x3250, 0x32FE }, { 0x3300, 0x4DBF }, { 0x4E00, 0xA48C }, { 0xA490, 0xA4C6 }, { 0xA960, 0xA97C }, { 0xAC00, 0xD7A3 }, { 0xF900, 0xFAFF }, { 0xFE10, 0xFE19 }, { 0xFE30, 0xFE52 }, { 0xFE54, 0xFE66 }, { 0xFE68, 0xFE6B }, { 0x16FE0, 0x16FE0 }, { 0x17000, 0x187EC }, { 0x18800, 0x18AF2 }, { 0x1B000, 0x1B001 }, { 0x1F004, 0x1F004 }, { 0x1F0CF, 0x1F0CF }, { 0x1F18E, 0x1F18E }, { 0x1F191, 0x1F19A }, { 0x1F200, 0x1F202 }, { 0x1F210, 0x1F23B }, { 0x1F240, 0x1F248 }, { 0x1F250, 0x1F251 }, { 0x1F300, 0x1F320 }, { 0x1F32D, 0x1F335 }, { 0x1F337, 0x1F37C }, { 0x1F37E, 0x1F393 }, { 0x1F3A0, 0x1F3CA }, { 0x1F3CF, 0x1F3D3 }, { 0x1F3E0, 0x1F3F0 }, { 0x1F3F4, 0x1F3F4 }, { 0x1F3F8, 0x1F43E }, { 0x1F440, 0x1F440 }, { 0x1F442, 0x1F4FC }, { 0x1F4FF, 0x1F53D }, { 0x1F54B, 0x1F54E }, { 0x1F550, 0x1F567 }, { 0x1F57A, 0x1F57A }, { 0x1F595, 0x1F596 }, { 0x1F5A4, 0x1F5A4 }, { 0x1F5FB, 0x1F64F }, { 0x1F680, 0x1F6C5 }, { 0x1F6CC, 0x1F6CC }, { 0x1F6D0, 0x1F6D2 }, { 0x1F6EB, 0x1F6EC }, { 0x1F6F4, 0x1F6F6 }, { 0x1F910, 0x1F91E }, { 0x1F920, 0x1F927 }, { 0x1F930, 0x1F930 }, { 0x1F933, 0x1F93E }, { 0x1F940, 0x1F94B }, { 0x1F950, 0x1F95E }, { 0x1F980, 0x1F991 }, { 0x1F9C0, 0x1F9C0 }, { 0x20000, 0x2FFFD }, { 0x30000, 0x3FFFD }, }; /// The length of the wide chars list. const size_t bc_history_wchars_len = sizeof(bc_history_wchars) / sizeof(bc_history_wchars[0]); /// A list of combining characters in Unicode. These are listed in ascending /// order for efficiency. const uint32_t bc_history_combo_chars[] = { 0x0300, 0x0301, 0x0302, 0x0303, 0x0304, 0x0305, 0x0306, 0x0307, 0x0308, 0x0309, 0x030A, 0x030B, 0x030C, 0x030D, 0x030E, 0x030F, 0x0310, 0x0311, 0x0312, 0x0313, 0x0314, 0x0315, 0x0316, 0x0317, 0x0318, 0x0319, 0x031A, 0x031B, 0x031C, 0x031D, 0x031E, 0x031F, 0x0320, 0x0321, 0x0322, 0x0323, 0x0324, 0x0325, 0x0326, 0x0327, 0x0328, 0x0329, 0x032A, 0x032B, 0x032C, 0x032D, 0x032E, 0x032F, 0x0330, 0x0331, 0x0332, 0x0333, 0x0334, 0x0335, 0x0336, 0x0337, 0x0338, 0x0339, 0x033A, 0x033B, 0x033C, 0x033D, 0x033E, 0x033F, 0x0340, 0x0341, 0x0342, 0x0343, 0x0344, 0x0345, 0x0346, 0x0347, 0x0348, 0x0349, 0x034A, 0x034B, 0x034C, 0x034D, 0x034E, 0x034F, 0x0350, 0x0351, 0x0352, 0x0353, 0x0354, 0x0355, 0x0356, 0x0357, 0x0358, 0x0359, 0x035A, 0x035B, 0x035C, 0x035D, 0x035E, 0x035F, 0x0360, 0x0361, 0x0362, 0x0363, 0x0364, 0x0365, 0x0366, 0x0367, 0x0368, 0x0369, 0x036A, 0x036B, 0x036C, 0x036D, 0x036E, 0x036F, 0x0483, 0x0484, 0x0485, 0x0486, 0x0487, 0x0591, 0x0592, 0x0593, 0x0594, 0x0595, 0x0596, 0x0597, 0x0598, 0x0599, 0x059A, 0x059B, 0x059C, 0x059D, 0x059E, 0x059F, 0x05A0, 0x05A1, 0x05A2, 0x05A3, 0x05A4, 0x05A5, 0x05A6, 0x05A7, 0x05A8, 0x05A9, 0x05AA, 0x05AB, 0x05AC, 0x05AD, 0x05AE, 0x05AF, 0x05B0, 0x05B1, 0x05B2, 0x05B3, 0x05B4, 0x05B5, 0x05B6, 0x05B7, 0x05B8, 0x05B9, 0x05BA, 0x05BB, 0x05BC, 0x05BD, 0x05BF, 0x05C1, 0x05C2, 0x05C4, 0x05C5, 0x05C7, 0x0610, 0x0611, 0x0612, 0x0613, 0x0614, 0x0615, 0x0616, 0x0617, 0x0618, 0x0619, 0x061A, 0x064B, 0x064C, 0x064D, 0x064E, 0x064F, 0x0650, 0x0651, 0x0652, 0x0653, 0x0654, 0x0655, 0x0656, 0x0657, 0x0658, 0x0659, 0x065A, 0x065B, 0x065C, 0x065D, 0x065E, 0x065F, 0x0670, 0x06D6, 0x06D7, 0x06D8, 0x06D9, 0x06DA, 0x06DB, 0x06DC, 0x06DF, 0x06E0, 0x06E1, 0x06E2, 0x06E3, 0x06E4, 0x06E7, 0x06E8, 0x06EA, 0x06EB, 0x06EC, 0x06ED, 0x0711, 0x0730, 0x0731, 0x0732, 0x0733, 0x0734, 0x0735, 0x0736, 0x0737, 0x0738, 0x0739, 0x073A, 0x073B, 0x073C, 0x073D, 0x073E, 0x073F, 0x0740, 0x0741, 0x0742, 0x0743, 0x0744, 0x0745, 0x0746, 0x0747, 0x0748, 0x0749, 0x074A, 0x07A6, 0x07A7, 0x07A8, 0x07A9, 0x07AA, 0x07AB, 0x07AC, 0x07AD, 0x07AE, 0x07AF, 0x07B0, 0x07EB, 0x07EC, 0x07ED, 0x07EE, 0x07EF, 0x07F0, 0x07F1, 0x07F2, 0x07F3, 0x0816, 0x0817, 0x0818, 0x0819, 0x081B, 0x081C, 0x081D, 0x081E, 0x081F, 0x0820, 0x0821, 0x0822, 0x0823, 0x0825, 0x0826, 0x0827, 0x0829, 0x082A, 0x082B, 0x082C, 0x082D, 0x0859, 0x085A, 0x085B, 0x08D4, 0x08D5, 0x08D6, 0x08D7, 0x08D8, 0x08D9, 0x08DA, 0x08DB, 0x08DC, 0x08DD, 0x08DE, 0x08DF, 0x08E0, 0x08E1, 0x08E3, 0x08E4, 0x08E5, 0x08E6, 0x08E7, 0x08E8, 0x08E9, 0x08EA, 0x08EB, 0x08EC, 0x08ED, 0x08EE, 0x08EF, 0x08F0, 0x08F1, 0x08F2, 0x08F3, 0x08F4, 0x08F5, 0x08F6, 0x08F7, 0x08F8, 0x08F9, 0x08FA, 0x08FB, 0x08FC, 0x08FD, 0x08FE, 0x08FF, 0x0900, 0x0901, 0x0902, 0x093A, 0x093C, 0x0941, 0x0942, 0x0943, 0x0944, 0x0945, 0x0946, 0x0947, 0x0948, 0x094D, 0x0951, 0x0952, 0x0953, 0x0954, 0x0955, 0x0956, 0x0957, 0x0962, 0x0963, 0x0981, 0x09BC, 0x09C1, 0x09C2, 0x09C3, 0x09C4, 0x09CD, 0x09E2, 0x09E3, 0x0A01, 0x0A02, 0x0A3C, 0x0A41, 0x0A42, 0x0A47, 0x0A48, 0x0A4B, 0x0A4C, 0x0A4D, 0x0A51, 0x0A70, 0x0A71, 0x0A75, 0x0A81, 0x0A82, 0x0ABC, 0x0AC1, 0x0AC2, 0x0AC3, 0x0AC4, 0x0AC5, 0x0AC7, 0x0AC8, 0x0ACD, 0x0AE2, 0x0AE3, 0x0B01, 0x0B3C, 0x0B3F, 0x0B41, 0x0B42, 0x0B43, 0x0B44, 0x0B4D, 0x0B56, 0x0B62, 0x0B63, 0x0B82, 0x0BC0, 0x0BCD, 0x0C00, 0x0C3E, 0x0C3F, 0x0C40, 0x0C46, 0x0C47, 0x0C48, 0x0C4A, 0x0C4B, 0x0C4C, 0x0C4D, 0x0C55, 0x0C56, 0x0C62, 0x0C63, 0x0C81, 0x0CBC, 0x0CBF, 0x0CC6, 0x0CCC, 0x0CCD, 0x0CE2, 0x0CE3, 0x0D01, 0x0D41, 0x0D42, 0x0D43, 0x0D44, 0x0D4D, 0x0D62, 0x0D63, 0x0DCA, 0x0DD2, 0x0DD3, 0x0DD4, 0x0DD6, 0x0E31, 0x0E34, 0x0E35, 0x0E36, 0x0E37, 0x0E38, 0x0E39, 0x0E3A, 0x0E47, 0x0E48, 0x0E49, 0x0E4A, 0x0E4B, 0x0E4C, 0x0E4D, 0x0E4E, 0x0EB1, 0x0EB4, 0x0EB5, 0x0EB6, 0x0EB7, 0x0EB8, 0x0EB9, 0x0EBB, 0x0EBC, 0x0EC8, 0x0EC9, 0x0ECA, 0x0ECB, 0x0ECC, 0x0ECD, 0x0F18, 0x0F19, 0x0F35, 0x0F37, 0x0F39, 0x0F71, 0x0F72, 0x0F73, 0x0F74, 0x0F75, 0x0F76, 0x0F77, 0x0F78, 0x0F79, 0x0F7A, 0x0F7B, 0x0F7C, 0x0F7D, 0x0F7E, 0x0F80, 0x0F81, 0x0F82, 0x0F83, 0x0F84, 0x0F86, 0x0F87, 0x0F8D, 0x0F8E, 0x0F8F, 0x0F90, 0x0F91, 0x0F92, 0x0F93, 0x0F94, 0x0F95, 0x0F96, 0x0F97, 0x0F99, 0x0F9A, 0x0F9B, 0x0F9C, 0x0F9D, 0x0F9E, 0x0F9F, 0x0FA0, 0x0FA1, 0x0FA2, 0x0FA3, 0x0FA4, 0x0FA5, 0x0FA6, 0x0FA7, 0x0FA8, 0x0FA9, 0x0FAA, 0x0FAB, 0x0FAC, 0x0FAD, 0x0FAE, 0x0FAF, 0x0FB0, 0x0FB1, 0x0FB2, 0x0FB3, 0x0FB4, 0x0FB5, 0x0FB6, 0x0FB7, 0x0FB8, 0x0FB9, 0x0FBA, 0x0FBB, 0x0FBC, 0x0FC6, 0x102D, 0x102E, 0x102F, 0x1030, 0x1032, 0x1033, 0x1034, 0x1035, 0x1036, 0x1037, 0x1039, 0x103A, 0x103D, 0x103E, 0x1058, 0x1059, 0x105E, 0x105F, 0x1060, 0x1071, 0x1072, 0x1073, 0x1074, 0x1082, 0x1085, 0x1086, 0x108D, 0x109D, 0x135D, 0x135E, 0x135F, 0x1712, 0x1713, 0x1714, 0x1732, 0x1733, 0x1734, 0x1752, 0x1753, 0x1772, 0x1773, 0x17B4, 0x17B5, 0x17B7, 0x17B8, 0x17B9, 0x17BA, 0x17BB, 0x17BC, 0x17BD, 0x17C6, 0x17C9, 0x17CA, 0x17CB, 0x17CC, 0x17CD, 0x17CE, 0x17CF, 0x17D0, 0x17D1, 0x17D2, 0x17D3, 0x17DD, 0x180B, 0x180C, 0x180D, 0x1885, 0x1886, 0x18A9, 0x1920, 0x1921, 0x1922, 0x1927, 0x1928, 0x1932, 0x1939, 0x193A, 0x193B, 0x1A17, 0x1A18, 0x1A1B, 0x1A56, 0x1A58, 0x1A59, 0x1A5A, 0x1A5B, 0x1A5C, 0x1A5D, 0x1A5E, 0x1A60, 0x1A62, 0x1A65, 0x1A66, 0x1A67, 0x1A68, 0x1A69, 0x1A6A, 0x1A6B, 0x1A6C, 0x1A73, 0x1A74, 0x1A75, 0x1A76, 0x1A77, 0x1A78, 0x1A79, 0x1A7A, 0x1A7B, 0x1A7C, 0x1A7F, 0x1AB0, 0x1AB1, 0x1AB2, 0x1AB3, 0x1AB4, 0x1AB5, 0x1AB6, 0x1AB7, 0x1AB8, 0x1AB9, 0x1ABA, 0x1ABB, 0x1ABC, 0x1ABD, 0x1B00, 0x1B01, 0x1B02, 0x1B03, 0x1B34, 0x1B36, 0x1B37, 0x1B38, 0x1B39, 0x1B3A, 0x1B3C, 0x1B42, 0x1B6B, 0x1B6C, 0x1B6D, 0x1B6E, 0x1B6F, 0x1B70, 0x1B71, 0x1B72, 0x1B73, 0x1B80, 0x1B81, 0x1BA2, 0x1BA3, 0x1BA4, 0x1BA5, 0x1BA8, 0x1BA9, 0x1BAB, 0x1BAC, 0x1BAD, 0x1BE6, 0x1BE8, 0x1BE9, 0x1BED, 0x1BEF, 0x1BF0, 0x1BF1, 0x1C2C, 0x1C2D, 0x1C2E, 0x1C2F, 0x1C30, 0x1C31, 0x1C32, 0x1C33, 0x1C36, 0x1C37, 0x1CD0, 0x1CD1, 0x1CD2, 0x1CD4, 0x1CD5, 0x1CD6, 0x1CD7, 0x1CD8, 0x1CD9, 0x1CDA, 0x1CDB, 0x1CDC, 0x1CDD, 0x1CDE, 0x1CDF, 0x1CE0, 0x1CE2, 0x1CE3, 0x1CE4, 0x1CE5, 0x1CE6, 0x1CE7, 0x1CE8, 0x1CED, 0x1CF4, 0x1CF8, 0x1CF9, 0x1DC0, 0x1DC1, 0x1DC2, 0x1DC3, 0x1DC4, 0x1DC5, 0x1DC6, 0x1DC7, 0x1DC8, 0x1DC9, 0x1DCA, 0x1DCB, 0x1DCC, 0x1DCD, 0x1DCE, 0x1DCF, 0x1DD0, 0x1DD1, 0x1DD2, 0x1DD3, 0x1DD4, 0x1DD5, 0x1DD6, 0x1DD7, 0x1DD8, 0x1DD9, 0x1DDA, 0x1DDB, 0x1DDC, 0x1DDD, 0x1DDE, 0x1DDF, 0x1DE0, 0x1DE1, 0x1DE2, 0x1DE3, 0x1DE4, 0x1DE5, 0x1DE6, 0x1DE7, 0x1DE8, 0x1DE9, 0x1DEA, 0x1DEB, 0x1DEC, 0x1DED, 0x1DEE, 0x1DEF, 0x1DF0, 0x1DF1, 0x1DF2, 0x1DF3, 0x1DF4, 0x1DF5, 0x1DFB, 0x1DFC, 0x1DFD, 0x1DFE, 0x1DFF, 0x20D0, 0x20D1, 0x20D2, 0x20D3, 0x20D4, 0x20D5, 0x20D6, 0x20D7, 0x20D8, 0x20D9, 0x20DA, 0x20DB, 0x20DC, 0x20E1, 0x20E5, 0x20E6, 0x20E7, 0x20E8, 0x20E9, 0x20EA, 0x20EB, 0x20EC, 0x20ED, 0x20EE, 0x20EF, 0x20F0, 0x2CEF, 0x2CF0, 0x2CF1, 0x2D7F, 0x2DE0, 0x2DE1, 0x2DE2, 0x2DE3, 0x2DE4, 0x2DE5, 0x2DE6, 0x2DE7, 0x2DE8, 0x2DE9, 0x2DEA, 0x2DEB, 0x2DEC, 0x2DED, 0x2DEE, 0x2DEF, 0x2DF0, 0x2DF1, 0x2DF2, 0x2DF3, 0x2DF4, 0x2DF5, 0x2DF6, 0x2DF7, 0x2DF8, 0x2DF9, 0x2DFA, 0x2DFB, 0x2DFC, 0x2DFD, 0x2DFE, 0x2DFF, 0x302A, 0x302B, 0x302C, 0x302D, 0x3099, 0x309A, 0xA66F, 0xA674, 0xA675, 0xA676, 0xA677, 0xA678, 0xA679, 0xA67A, 0xA67B, 0xA67C, 0xA67D, 0xA69E, 0xA69F, 0xA6F0, 0xA6F1, 0xA802, 0xA806, 0xA80B, 0xA825, 0xA826, 0xA8C4, 0xA8C5, 0xA8E0, 0xA8E1, 0xA8E2, 0xA8E3, 0xA8E4, 0xA8E5, 0xA8E6, 0xA8E7, 0xA8E8, 0xA8E9, 0xA8EA, 0xA8EB, 0xA8EC, 0xA8ED, 0xA8EE, 0xA8EF, 0xA8F0, 0xA8F1, 0xA926, 0xA927, 0xA928, 0xA929, 0xA92A, 0xA92B, 0xA92C, 0xA92D, 0xA947, 0xA948, 0xA949, 0xA94A, 0xA94B, 0xA94C, 0xA94D, 0xA94E, 0xA94F, 0xA950, 0xA951, 0xA980, 0xA981, 0xA982, 0xA9B3, 0xA9B6, 0xA9B7, 0xA9B8, 0xA9B9, 0xA9BC, 0xA9E5, 0xAA29, 0xAA2A, 0xAA2B, 0xAA2C, 0xAA2D, 0xAA2E, 0xAA31, 0xAA32, 0xAA35, 0xAA36, 0xAA43, 0xAA4C, 0xAA7C, 0xAAB0, 0xAAB2, 0xAAB3, 0xAAB4, 0xAAB7, 0xAAB8, 0xAABE, 0xAABF, 0xAAC1, 0xAAEC, 0xAAED, 0xAAF6, 0xABE5, 0xABE8, 0xABED, 0xFB1E, 0xFE00, 0xFE01, 0xFE02, 0xFE03, 0xFE04, 0xFE05, 0xFE06, 0xFE07, 0xFE08, 0xFE09, 0xFE0A, 0xFE0B, 0xFE0C, 0xFE0D, 0xFE0E, 0xFE0F, 0xFE20, 0xFE21, 0xFE22, 0xFE23, 0xFE24, 0xFE25, 0xFE26, 0xFE27, 0xFE28, 0xFE29, 0xFE2A, 0xFE2B, 0xFE2C, 0xFE2D, 0xFE2E, 0xFE2F, 0x101FD, 0x102E0, 0x10376, 0x10377, 0x10378, 0x10379, 0x1037A, 0x10A01, 0x10A02, 0x10A03, 0x10A05, 0x10A06, 0x10A0C, 0x10A0D, 0x10A0E, 0x10A0F, 0x10A38, 0x10A39, 0x10A3A, 0x10A3F, 0x10AE5, 0x10AE6, 0x11001, 0x11038, 0x11039, 0x1103A, 0x1103B, 0x1103C, 0x1103D, 0x1103E, 0x1103F, 0x11040, 0x11041, 0x11042, 0x11043, 0x11044, 0x11045, 0x11046, 0x1107F, 0x11080, 0x11081, 0x110B3, 0x110B4, 0x110B5, 0x110B6, 0x110B9, 0x110BA, 0x11100, 0x11101, 0x11102, 0x11127, 0x11128, 0x11129, 0x1112A, 0x1112B, 0x1112D, 0x1112E, 0x1112F, 0x11130, 0x11131, 0x11132, 0x11133, 0x11134, 0x11173, 0x11180, 0x11181, 0x111B6, 0x111B7, 0x111B8, 0x111B9, 0x111BA, 0x111BB, 0x111BC, 0x111BD, 0x111BE, 0x111CA, 0x111CB, 0x111CC, 0x1122F, 0x11230, 0x11231, 0x11234, 0x11236, 0x11237, 0x1123E, 0x112DF, 0x112E3, 0x112E4, 0x112E5, 0x112E6, 0x112E7, 0x112E8, 0x112E9, 0x112EA, 0x11300, 0x11301, 0x1133C, 0x11340, 0x11366, 0x11367, 0x11368, 0x11369, 0x1136A, 0x1136B, 0x1136C, 0x11370, 0x11371, 0x11372, 0x11373, 0x11374, 0x11438, 0x11439, 0x1143A, 0x1143B, 0x1143C, 0x1143D, 0x1143E, 0x1143F, 0x11442, 0x11443, 0x11444, 0x11446, 0x114B3, 0x114B4, 0x114B5, 0x114B6, 0x114B7, 0x114B8, 0x114BA, 0x114BF, 0x114C0, 0x114C2, 0x114C3, 0x115B2, 0x115B3, 0x115B4, 0x115B5, 0x115BC, 0x115BD, 0x115BF, 0x115C0, 0x115DC, 0x115DD, 0x11633, 0x11634, 0x11635, 0x11636, 0x11637, 0x11638, 0x11639, 0x1163A, 0x1163D, 0x1163F, 0x11640, 0x116AB, 0x116AD, 0x116B0, 0x116B1, 0x116B2, 0x116B3, 0x116B4, 0x116B5, 0x116B7, 0x1171D, 0x1171E, 0x1171F, 0x11722, 0x11723, 0x11724, 0x11725, 0x11727, 0x11728, 0x11729, 0x1172A, 0x1172B, 0x11C30, 0x11C31, 0x11C32, 0x11C33, 0x11C34, 0x11C35, 0x11C36, 0x11C38, 0x11C39, 0x11C3A, 0x11C3B, 0x11C3C, 0x11C3D, 0x11C3F, 0x11C92, 0x11C93, 0x11C94, 0x11C95, 0x11C96, 0x11C97, 0x11C98, 0x11C99, 0x11C9A, 0x11C9B, 0x11C9C, 0x11C9D, 0x11C9E, 0x11C9F, 0x11CA0, 0x11CA1, 0x11CA2, 0x11CA3, 0x11CA4, 0x11CA5, 0x11CA6, 0x11CA7, 0x11CAA, 0x11CAB, 0x11CAC, 0x11CAD, 0x11CAE, 0x11CAF, 0x11CB0, 0x11CB2, 0x11CB3, 0x11CB5, 0x11CB6, 0x16AF0, 0x16AF1, 0x16AF2, 0x16AF3, 0x16AF4, 0x16B30, 0x16B31, 0x16B32, 0x16B33, 0x16B34, 0x16B35, 0x16B36, 0x16F8F, 0x16F90, 0x16F91, 0x16F92, 0x1BC9D, 0x1BC9E, 0x1D167, 0x1D168, 0x1D169, 0x1D17B, 0x1D17C, 0x1D17D, 0x1D17E, 0x1D17F, 0x1D180, 0x1D181, 0x1D182, 0x1D185, 0x1D186, 0x1D187, 0x1D188, 0x1D189, 0x1D18A, 0x1D18B, 0x1D1AA, 0x1D1AB, 0x1D1AC, 0x1D1AD, 0x1D242, 0x1D243, 0x1D244, 0x1DA00, 0x1DA01, 0x1DA02, 0x1DA03, 0x1DA04, 0x1DA05, 0x1DA06, 0x1DA07, 0x1DA08, 0x1DA09, 0x1DA0A, 0x1DA0B, 0x1DA0C, 0x1DA0D, 0x1DA0E, 0x1DA0F, 0x1DA10, 0x1DA11, 0x1DA12, 0x1DA13, 0x1DA14, 0x1DA15, 0x1DA16, 0x1DA17, 0x1DA18, 0x1DA19, 0x1DA1A, 0x1DA1B, 0x1DA1C, 0x1DA1D, 0x1DA1E, 0x1DA1F, 0x1DA20, 0x1DA21, 0x1DA22, 0x1DA23, 0x1DA24, 0x1DA25, 0x1DA26, 0x1DA27, 0x1DA28, 0x1DA29, 0x1DA2A, 0x1DA2B, 0x1DA2C, 0x1DA2D, 0x1DA2E, 0x1DA2F, 0x1DA30, 0x1DA31, 0x1DA32, 0x1DA33, 0x1DA34, 0x1DA35, 0x1DA36, 0x1DA3B, 0x1DA3C, 0x1DA3D, 0x1DA3E, 0x1DA3F, 0x1DA40, 0x1DA41, 0x1DA42, 0x1DA43, 0x1DA44, 0x1DA45, 0x1DA46, 0x1DA47, 0x1DA48, 0x1DA49, 0x1DA4A, 0x1DA4B, 0x1DA4C, 0x1DA4D, 0x1DA4E, 0x1DA4F, 0x1DA50, 0x1DA51, 0x1DA52, 0x1DA53, 0x1DA54, 0x1DA55, 0x1DA56, 0x1DA57, 0x1DA58, 0x1DA59, 0x1DA5A, 0x1DA5B, 0x1DA5C, 0x1DA5D, 0x1DA5E, 0x1DA5F, 0x1DA60, 0x1DA61, 0x1DA62, 0x1DA63, 0x1DA64, 0x1DA65, 0x1DA66, 0x1DA67, 0x1DA68, 0x1DA69, 0x1DA6A, 0x1DA6B, 0x1DA6C, 0x1DA75, 0x1DA84, 0x1DA9B, 0x1DA9C, 0x1DA9D, 0x1DA9E, 0x1DA9F, 0x1DAA1, 0x1DAA2, 0x1DAA3, 0x1DAA4, 0x1DAA5, 0x1DAA6, 0x1DAA7, 0x1DAA8, 0x1DAA9, 0x1DAAA, 0x1DAAB, 0x1DAAC, 0x1DAAD, 0x1DAAE, 0x1DAAF, 0x1E000, 0x1E001, 0x1E002, 0x1E003, 0x1E004, 0x1E005, 0x1E006, 0x1E008, 0x1E009, 0x1E00A, 0x1E00B, 0x1E00C, 0x1E00D, 0x1E00E, 0x1E00F, 0x1E010, 0x1E011, 0x1E012, 0x1E013, 0x1E014, 0x1E015, 0x1E016, 0x1E017, 0x1E018, 0x1E01B, 0x1E01C, 0x1E01D, 0x1E01E, 0x1E01F, 0x1E020, 0x1E021, 0x1E023, 0x1E024, 0x1E026, 0x1E027, 0x1E028, 0x1E029, 0x1E02A, 0x1E8D0, 0x1E8D1, 0x1E8D2, 0x1E8D3, 0x1E8D4, 0x1E8D5, 0x1E8D6, 0x1E944, 0x1E945, 0x1E946, 0x1E947, 0x1E948, 0x1E949, 0x1E94A, 0xE0100, 0xE0101, 0xE0102, 0xE0103, 0xE0104, 0xE0105, 0xE0106, 0xE0107, 0xE0108, 0xE0109, 0xE010A, 0xE010B, 0xE010C, 0xE010D, 0xE010E, 0xE010F, 0xE0110, 0xE0111, 0xE0112, 0xE0113, 0xE0114, 0xE0115, 0xE0116, 0xE0117, 0xE0118, 0xE0119, 0xE011A, 0xE011B, 0xE011C, 0xE011D, 0xE011E, 0xE011F, 0xE0120, 0xE0121, 0xE0122, 0xE0123, 0xE0124, 0xE0125, 0xE0126, 0xE0127, 0xE0128, 0xE0129, 0xE012A, 0xE012B, 0xE012C, 0xE012D, 0xE012E, 0xE012F, 0xE0130, 0xE0131, 0xE0132, 0xE0133, 0xE0134, 0xE0135, 0xE0136, 0xE0137, 0xE0138, 0xE0139, 0xE013A, 0xE013B, 0xE013C, 0xE013D, 0xE013E, 0xE013F, 0xE0140, 0xE0141, 0xE0142, 0xE0143, 0xE0144, 0xE0145, 0xE0146, 0xE0147, 0xE0148, 0xE0149, 0xE014A, 0xE014B, 0xE014C, 0xE014D, 0xE014E, 0xE014F, 0xE0150, 0xE0151, 0xE0152, 0xE0153, 0xE0154, 0xE0155, 0xE0156, 0xE0157, 0xE0158, 0xE0159, 0xE015A, 0xE015B, 0xE015C, 0xE015D, 0xE015E, 0xE015F, 0xE0160, 0xE0161, 0xE0162, 0xE0163, 0xE0164, 0xE0165, 0xE0166, 0xE0167, 0xE0168, 0xE0169, 0xE016A, 0xE016B, 0xE016C, 0xE016D, 0xE016E, 0xE016F, 0xE0170, 0xE0171, 0xE0172, 0xE0173, 0xE0174, 0xE0175, 0xE0176, 0xE0177, 0xE0178, 0xE0179, 0xE017A, 0xE017B, 0xE017C, 0xE017D, 0xE017E, 0xE017F, 0xE0180, 0xE0181, 0xE0182, 0xE0183, 0xE0184, 0xE0185, 0xE0186, 0xE0187, 0xE0188, 0xE0189, 0xE018A, 0xE018B, 0xE018C, 0xE018D, 0xE018E, 0xE018F, 0xE0190, 0xE0191, 0xE0192, 0xE0193, 0xE0194, 0xE0195, 0xE0196, 0xE0197, 0xE0198, 0xE0199, 0xE019A, 0xE019B, 0xE019C, 0xE019D, 0xE019E, 0xE019F, 0xE01A0, 0xE01A1, 0xE01A2, 0xE01A3, 0xE01A4, 0xE01A5, 0xE01A6, 0xE01A7, 0xE01A8, 0xE01A9, 0xE01AA, 0xE01AB, 0xE01AC, 0xE01AD, 0xE01AE, 0xE01AF, 0xE01B0, 0xE01B1, 0xE01B2, 0xE01B3, 0xE01B4, 0xE01B5, 0xE01B6, 0xE01B7, 0xE01B8, 0xE01B9, 0xE01BA, 0xE01BB, 0xE01BC, 0xE01BD, 0xE01BE, 0xE01BF, 0xE01C0, 0xE01C1, 0xE01C2, 0xE01C3, 0xE01C4, 0xE01C5, 0xE01C6, 0xE01C7, 0xE01C8, 0xE01C9, 0xE01CA, 0xE01CB, 0xE01CC, 0xE01CD, 0xE01CE, 0xE01CF, 0xE01D0, 0xE01D1, 0xE01D2, 0xE01D3, 0xE01D4, 0xE01D5, 0xE01D6, 0xE01D7, 0xE01D8, 0xE01D9, 0xE01DA, 0xE01DB, 0xE01DC, 0xE01DD, 0xE01DE, 0xE01DF, 0xE01E0, 0xE01E1, 0xE01E2, 0xE01E3, 0xE01E4, 0xE01E5, 0xE01E6, 0xE01E7, 0xE01E8, 0xE01E9, 0xE01EA, 0xE01EB, 0xE01EC, 0xE01ED, 0xE01EE, 0xE01EF, }; /// The length of the combining characters list. const size_t bc_history_combo_chars_len = sizeof(bc_history_combo_chars) / sizeof(bc_history_combo_chars[0]); #endif // BC_ENABLE_HISTORY && !BC_ENABLE_LINE_LIB /// The human-readable name of the main function in bc source code. const char bc_func_main[] = "(main)"; /// The human-readable name of the read function in bc source code. const char bc_func_read[] = "(read)"; #if BC_DEBUG_CODE /// A list of names of instructions for easy debugging output. const char* bc_inst_names[] = { #if BC_ENABLED "BC_INST_INC", "BC_INST_DEC", #endif // BC_ENABLED "BC_INST_NEG", "BC_INST_BOOL_NOT", #if BC_ENABLE_EXTRA_MATH "BC_INST_TRUNC", #endif // BC_ENABLE_EXTRA_MATH "BC_INST_POWER", "BC_INST_MULTIPLY", "BC_INST_DIVIDE", "BC_INST_MODULUS", "BC_INST_PLUS", "BC_INST_MINUS", #if BC_ENABLE_EXTRA_MATH "BC_INST_PLACES", "BC_INST_LSHIFT", "BC_INST_RSHIFT", #endif // BC_ENABLE_EXTRA_MATH "BC_INST_REL_EQ", "BC_INST_REL_LE", "BC_INST_REL_GE", "BC_INST_REL_NE", "BC_INST_REL_LT", "BC_INST_REL_GT", "BC_INST_BOOL_OR", "BC_INST_BOOL_AND", #if BC_ENABLED "BC_INST_ASSIGN_POWER", "BC_INST_ASSIGN_MULTIPLY", "BC_INST_ASSIGN_DIVIDE", "BC_INST_ASSIGN_MODULUS", "BC_INST_ASSIGN_PLUS", "BC_INST_ASSIGN_MINUS", #if BC_ENABLE_EXTRA_MATH "BC_INST_ASSIGN_PLACES", "BC_INST_ASSIGN_LSHIFT", "BC_INST_ASSIGN_RSHIFT", #endif // BC_ENABLE_EXTRA_MATH "BC_INST_ASSIGN", "BC_INST_ASSIGN_POWER_NO_VAL", "BC_INST_ASSIGN_MULTIPLY_NO_VAL", "BC_INST_ASSIGN_DIVIDE_NO_VAL", "BC_INST_ASSIGN_MODULUS_NO_VAL", "BC_INST_ASSIGN_PLUS_NO_VAL", "BC_INST_ASSIGN_MINUS_NO_VAL", #if BC_ENABLE_EXTRA_MATH "BC_INST_ASSIGN_PLACES_NO_VAL", "BC_INST_ASSIGN_LSHIFT_NO_VAL", "BC_INST_ASSIGN_RSHIFT_NO_VAL", #endif // BC_ENABLE_EXTRA_MATH #endif // BC_ENABLED "BC_INST_ASSIGN_NO_VAL", "BC_INST_NUM", "BC_INST_VAR", "BC_INST_ARRAY_ELEM", "BC_INST_ARRAY", "BC_INST_ZERO", "BC_INST_ONE", #if BC_ENABLED "BC_INST_LAST", #endif // BC_ENABLED "BC_INST_IBASE", "BC_INST_OBASE", "BC_INST_SCALE", #if BC_ENABLE_EXTRA_MATH "BC_INST_SEED", #endif // BC_ENABLE_EXTRA_MATH "BC_INST_LENGTH", "BC_INST_SCALE_FUNC", "BC_INST_SQRT", "BC_INST_ABS", "BC_INST_IS_NUMBER", "BC_INST_IS_STRING", #if BC_ENABLE_EXTRA_MATH "BC_INST_IRAND", #endif // BC_ENABLE_EXTRA_MATH "BC_INST_ASCIIFY", "BC_INST_READ", #if BC_ENABLE_EXTRA_MATH "BC_INST_RAND", #endif // BC_ENABLE_EXTRA_MATH "BC_INST_MAXIBASE", "BC_INST_MAXOBASE", "BC_INST_MAXSCALE", #if BC_ENABLE_EXTRA_MATH "BC_INST_MAXRAND", #endif // BC_ENABLE_EXTRA_MATH "BC_INST_PRINT", "BC_INST_PRINT_POP", "BC_INST_STR", #if BC_ENABLED "BC_INST_PRINT_STR", "BC_INST_JUMP", "BC_INST_JUMP_ZERO", "BC_INST_CALL", "BC_INST_RET", "BC_INST_RET0", "BC_INST_RET_VOID", "BC_INST_HALT", #endif // BC_ENABLED "BC_INST_POP", "BC_INST_SWAP", "BC_INST_MODEXP", "BC_INST_DIVMOD", "BC_INST_PRINT_STREAM", #if DC_ENABLED "BC_INST_POP_EXEC", "BC_INST_EXECUTE", "BC_INST_EXEC_COND", "BC_INST_PRINT_STACK", "BC_INST_CLEAR_STACK", "BC_INST_REG_STACK_LEN", "BC_INST_STACK_LEN", "BC_INST_DUPLICATE", "BC_INST_LOAD", "BC_INST_PUSH_VAR", "BC_INST_PUSH_TO_VAR", "BC_INST_QUIT", "BC_INST_NQUIT", "BC_INST_EXEC_STACK_LEN", #endif // DC_ENABLED "BC_INST_INVALID", }; #endif // BC_DEBUG_CODE /// A constant string for 0. const char bc_parse_zero[2] = "0"; /// A constant string for 1. const char bc_parse_one[2] = "1"; #if BC_ENABLED /// A list of keywords for bc. This needs to be updated if keywords change. const BcLexKeyword bc_lex_kws[] = { BC_LEX_KW_ENTRY("auto", 4, true), BC_LEX_KW_ENTRY("break", 5, true), BC_LEX_KW_ENTRY("continue", 8, false), BC_LEX_KW_ENTRY("define", 6, true), BC_LEX_KW_ENTRY("for", 3, true), BC_LEX_KW_ENTRY("if", 2, true), BC_LEX_KW_ENTRY("limits", 6, false), BC_LEX_KW_ENTRY("return", 6, true), BC_LEX_KW_ENTRY("while", 5, true), BC_LEX_KW_ENTRY("halt", 4, false), BC_LEX_KW_ENTRY("last", 4, false), BC_LEX_KW_ENTRY("ibase", 5, true), BC_LEX_KW_ENTRY("obase", 5, true), BC_LEX_KW_ENTRY("scale", 5, true), #if BC_ENABLE_EXTRA_MATH BC_LEX_KW_ENTRY("seed", 4, false), #endif // BC_ENABLE_EXTRA_MATH BC_LEX_KW_ENTRY("length", 6, true), BC_LEX_KW_ENTRY("print", 5, false), BC_LEX_KW_ENTRY("sqrt", 4, true), BC_LEX_KW_ENTRY("abs", 3, false), BC_LEX_KW_ENTRY("is_number", 9, false), BC_LEX_KW_ENTRY("is_string", 9, false), #if BC_ENABLE_EXTRA_MATH BC_LEX_KW_ENTRY("irand", 5, false), #endif // BC_ENABLE_EXTRA_MATH BC_LEX_KW_ENTRY("asciify", 7, false), BC_LEX_KW_ENTRY("modexp", 6, false), BC_LEX_KW_ENTRY("divmod", 6, false), BC_LEX_KW_ENTRY("quit", 4, true), BC_LEX_KW_ENTRY("read", 4, false), #if BC_ENABLE_EXTRA_MATH BC_LEX_KW_ENTRY("rand", 4, false), #endif // BC_ENABLE_EXTRA_MATH BC_LEX_KW_ENTRY("maxibase", 8, false), BC_LEX_KW_ENTRY("maxobase", 8, false), BC_LEX_KW_ENTRY("maxscale", 8, false), #if BC_ENABLE_EXTRA_MATH BC_LEX_KW_ENTRY("maxrand", 7, false), #endif // BC_ENABLE_EXTRA_MATH BC_LEX_KW_ENTRY("line_length", 11, false), BC_LEX_KW_ENTRY("global_stacks", 13, false), BC_LEX_KW_ENTRY("leading_zero", 12, false), BC_LEX_KW_ENTRY("stream", 6, false), BC_LEX_KW_ENTRY("else", 4, false), }; /// The length of the list of bc keywords. const size_t bc_lex_kws_len = sizeof(bc_lex_kws) / sizeof(BcLexKeyword); #if BC_C11 // This is here to ensure that BC_LEX_NKWS, which is needed for the // redefined_kws in BcVm, is correct. If it's correct under C11, it will be // correct under C99, and I did not know any other way of ensuring they remained // synchronized. _Static_assert(sizeof(bc_lex_kws) / sizeof(BcLexKeyword) == BC_LEX_NKWS, "BC_LEX_NKWS is wrong."); #endif // BC_C11 /// An array of booleans that correspond to token types. An entry is true if the /// token is valid in an expression, false otherwise. This will need to change /// if tokens change. const uint8_t bc_parse_exprs[] = { // Starts with BC_LEX_EOF. BC_PARSE_EXPR_ENTRY(false, false, true, true, true, true, true, true), // Starts with BC_LEX_OP_MULTIPLY if extra math is enabled, BC_LEX_OP_DIVIDE // otherwise. BC_PARSE_EXPR_ENTRY(true, true, true, true, true, true, true, true), // Starts with BC_LEX_OP_REL_EQ if extra math is enabled, BC_LEX_OP_REL_LT // otherwise. BC_PARSE_EXPR_ENTRY(true, true, true, true, true, true, true, true), #if BC_ENABLE_EXTRA_MATH // Starts with BC_LEX_OP_ASSIGN_POWER. BC_PARSE_EXPR_ENTRY(true, true, true, true, true, true, true, true), // Starts with BC_LEX_OP_ASSIGN_RSHIFT. BC_PARSE_EXPR_ENTRY(true, true, false, false, true, true, false, false), // Starts with BC_LEX_RBRACKET. BC_PARSE_EXPR_ENTRY(false, false, false, false, true, true, true, false), // Starts with BC_LEX_KW_BREAK. BC_PARSE_EXPR_ENTRY(false, false, false, false, false, false, false, false), // Starts with BC_LEX_KW_HALT. BC_PARSE_EXPR_ENTRY(false, true, true, true, true, true, true, false), // Starts with BC_LEX_KW_SQRT. BC_PARSE_EXPR_ENTRY(true, true, true, true, true, true, true, true), // Starts with BC_LEX_KW_QUIT. BC_PARSE_EXPR_ENTRY(false, true, true, true, true, true, true, true), // Starts with BC_LEX_KW_GLOBAL_STACKS. BC_PARSE_EXPR_ENTRY(true, true, false, false, 0, 0, 0, 0) #else // BC_ENABLE_EXTRA_MATH // Starts with BC_LEX_OP_ASSIGN_PLUS. BC_PARSE_EXPR_ENTRY(true, true, true, false, false, true, true, false), // Starts with BC_LEX_COMMA. BC_PARSE_EXPR_ENTRY(false, false, false, false, false, true, true, true), // Starts with BC_LEX_KW_AUTO. BC_PARSE_EXPR_ENTRY(false, false, false, false, false, false, false, false), // Starts with BC_LEX_KW_WHILE. BC_PARSE_EXPR_ENTRY(false, false, true, true, true, true, true, false), // Starts with BC_LEX_KW_SQRT. BC_PARSE_EXPR_ENTRY(true, true, true, true, true, true, true, false), // Starts with BC_LEX_KW_MAXIBASE. BC_PARSE_EXPR_ENTRY(true, true, true, true, true, true, true, false), // Starts with BC_LEX_KW_ELSE. BC_PARSE_EXPR_ENTRY(false, 0, 0, 0, 0, 0, 0, 0) #endif // BC_ENABLE_EXTRA_MATH }; /// An array of data for operators that correspond to token types. Note that a /// lower precedence *value* means a higher precedence. const uchar bc_parse_ops[] = { BC_PARSE_OP(0, false), BC_PARSE_OP(0, false), BC_PARSE_OP(1, false), BC_PARSE_OP(1, false), #if BC_ENABLE_EXTRA_MATH BC_PARSE_OP(2, false), #endif // BC_ENABLE_EXTRA_MATH BC_PARSE_OP(4, false), BC_PARSE_OP(5, true), BC_PARSE_OP(5, true), BC_PARSE_OP(5, true), BC_PARSE_OP(6, true), BC_PARSE_OP(6, true), #if BC_ENABLE_EXTRA_MATH BC_PARSE_OP(3, false), BC_PARSE_OP(7, true), BC_PARSE_OP(7, true), #endif // BC_ENABLE_EXTRA_MATH BC_PARSE_OP(9, true), BC_PARSE_OP(9, true), BC_PARSE_OP(9, true), BC_PARSE_OP(9, true), BC_PARSE_OP(9, true), BC_PARSE_OP(9, true), BC_PARSE_OP(11, true), BC_PARSE_OP(10, true), BC_PARSE_OP(8, false), BC_PARSE_OP(8, false), BC_PARSE_OP(8, false), BC_PARSE_OP(8, false), BC_PARSE_OP(8, false), BC_PARSE_OP(8, false), #if BC_ENABLE_EXTRA_MATH BC_PARSE_OP(8, false), BC_PARSE_OP(8, false), BC_PARSE_OP(8, false), #endif // BC_ENABLE_EXTRA_MATH BC_PARSE_OP(8, false), }; // These identify what tokens can come after expressions in certain cases. /// The valid next tokens for normal expressions. const BcParseNext bc_parse_next_expr = BC_PARSE_NEXT(4, BC_LEX_NLINE, BC_LEX_SCOLON, BC_LEX_RBRACE, BC_LEX_EOF); /// The valid next tokens for function argument expressions. const BcParseNext bc_parse_next_arg = BC_PARSE_NEXT(2, BC_LEX_RPAREN, BC_LEX_COMMA); /// The valid next tokens for expressions in print statements. const BcParseNext bc_parse_next_print = BC_PARSE_NEXT(4, BC_LEX_COMMA, BC_LEX_NLINE, BC_LEX_SCOLON, BC_LEX_EOF); /// The valid next tokens for if statement conditions or loop conditions. This /// is used in for loops for the update expression and for builtin function. /// /// The name is an artifact of history, and is related to @a BC_PARSE_REL (see /// include/parse.h). It refers to how POSIX only allows some operators as part /// of the conditional of for loops, while loops, and if statements. const BcParseNext bc_parse_next_rel = BC_PARSE_NEXT(1, BC_LEX_RPAREN); /// The valid next tokens for array element expressions. const BcParseNext bc_parse_next_elem = BC_PARSE_NEXT(1, BC_LEX_RBRACKET); /// The valid next tokens for for loop initialization expressions and condition /// expressions. const BcParseNext bc_parse_next_for = BC_PARSE_NEXT(1, BC_LEX_SCOLON); /// The valid next tokens for read expressions. const BcParseNext bc_parse_next_read = BC_PARSE_NEXT(2, BC_LEX_NLINE, BC_LEX_EOF); /// The valid next tokens for the arguments of a builtin function with multiple /// arguments. const BcParseNext bc_parse_next_builtin = BC_PARSE_NEXT(1, BC_LEX_COMMA); #endif // BC_ENABLED #if DC_ENABLED /// A list of instructions that need register arguments in dc. const uint8_t dc_lex_regs[] = { BC_LEX_OP_REL_EQ, BC_LEX_OP_REL_LE, BC_LEX_OP_REL_GE, BC_LEX_OP_REL_NE, BC_LEX_OP_REL_LT, BC_LEX_OP_REL_GT, BC_LEX_SCOLON, BC_LEX_COLON, BC_LEX_KW_ELSE, BC_LEX_LOAD, BC_LEX_LOAD_POP, BC_LEX_OP_ASSIGN, BC_LEX_STORE_PUSH, BC_LEX_REG_STACK_LEVEL, BC_LEX_ARRAY_LENGTH, }; /// The length of the list of register instructions. const size_t dc_lex_regs_len = sizeof(dc_lex_regs) / sizeof(uint8_t); /// A list corresponding to characters starting at double quote ("). If an entry /// is BC_LEX_INVALID, then that character needs extra lexing in dc. If it does /// not, the character can trivially be replaced by the entry. Positions are /// kept because it corresponds to the ASCII table. This may need to be changed /// if tokens change. const uchar dc_lex_tokens[] = { #if BC_ENABLE_EXTRA_MATH BC_LEX_KW_IRAND, #else // BC_ENABLE_EXTRA_MATH BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH BC_LEX_INVALID, #if BC_ENABLE_EXTRA_MATH BC_LEX_OP_TRUNC, #else // BC_ENABLE_EXTRA_MATH BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH BC_LEX_OP_MODULUS, BC_LEX_INVALID, #if BC_ENABLE_EXTRA_MATH BC_LEX_KW_RAND, #else // BC_ENABLE_EXTRA_MATH BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH BC_LEX_LPAREN, BC_LEX_RPAREN, BC_LEX_OP_MULTIPLY, BC_LEX_OP_PLUS, BC_LEX_EXEC_STACK_LENGTH, BC_LEX_OP_MINUS, BC_LEX_INVALID, BC_LEX_OP_DIVIDE, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_COLON, BC_LEX_SCOLON, BC_LEX_OP_REL_GT, BC_LEX_OP_REL_EQ, BC_LEX_OP_REL_LT, BC_LEX_KW_READ, #if BC_ENABLE_EXTRA_MATH BC_LEX_OP_PLACES, #else // BC_ENABLE_EXTRA_MATH BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_EQ_NO_REG, #if BC_ENABLE_EXTRA_MATH BC_LEX_OP_LSHIFT, #else // BC_ENABLE_EXTRA_MATH BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH BC_LEX_KW_IBASE, #if BC_ENABLE_EXTRA_MATH BC_LEX_KW_SEED, #else // BC_ENABLE_EXTRA_MATH BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH BC_LEX_KW_SCALE, BC_LEX_LOAD_POP, BC_LEX_OP_BOOL_AND, BC_LEX_OP_BOOL_NOT, BC_LEX_KW_OBASE, BC_LEX_KW_STREAM, BC_LEX_NQUIT, BC_LEX_POP, BC_LEX_STORE_PUSH, BC_LEX_KW_MAXIBASE, BC_LEX_KW_MAXOBASE, BC_LEX_KW_MAXSCALE, #if BC_ENABLE_EXTRA_MATH BC_LEX_KW_MAXRAND, #else // BC_ENABLE_EXTRA_MATH BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH BC_LEX_SCALE_FACTOR, BC_LEX_ARRAY_LENGTH, BC_LEX_KW_LENGTH, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_OP_POWER, BC_LEX_NEG, BC_LEX_INVALID, BC_LEX_KW_ASCIIFY, BC_LEX_KW_ABS, BC_LEX_CLEAR_STACK, BC_LEX_DUPLICATE, BC_LEX_KW_ELSE, BC_LEX_PRINT_STACK, BC_LEX_INVALID, #if BC_ENABLE_EXTRA_MATH BC_LEX_OP_RSHIFT, #else // BC_ENABLE_EXTRA_MATH BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH BC_LEX_STORE_IBASE, #if BC_ENABLE_EXTRA_MATH BC_LEX_STORE_SEED, #else // BC_ENABLE_EXTRA_MATH BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH BC_LEX_STORE_SCALE, BC_LEX_LOAD, BC_LEX_OP_BOOL_OR, BC_LEX_PRINT_POP, BC_LEX_STORE_OBASE, BC_LEX_KW_PRINT, BC_LEX_KW_QUIT, BC_LEX_SWAP, BC_LEX_OP_ASSIGN, BC_LEX_KW_IS_STRING, BC_LEX_KW_IS_NUMBER, BC_LEX_KW_SQRT, BC_LEX_INVALID, BC_LEX_EXECUTE, BC_LEX_REG_STACK_LEVEL, BC_LEX_STACK_LEVEL, BC_LEX_LBRACE, BC_LEX_KW_MODEXP, BC_LEX_RBRACE, BC_LEX_KW_DIVMOD, BC_LEX_INVALID }; /// A list of instructions that correspond to lex tokens. If an entry is /// @a BC_INST_INVALID, that lex token needs extra parsing in the dc parser. /// Otherwise, the token can trivially be replaced by the entry. This needs to /// be updated if the tokens change. const uchar dc_parse_insts[] = { BC_INST_INVALID, BC_INST_INVALID, #if BC_ENABLED BC_INST_INVALID, BC_INST_INVALID, #endif // BC_ENABLED BC_INST_INVALID, BC_INST_BOOL_NOT, #if BC_ENABLE_EXTRA_MATH BC_INST_TRUNC, #endif // BC_ENABLE_EXTRA_MATH - BC_INST_POWER, BC_INST_MULTIPLY, BC_INST_DIVIDE, - BC_INST_MODULUS, BC_INST_PLUS, BC_INST_MINUS, + BC_INST_POWER, BC_INST_MULTIPLY, + BC_INST_DIVIDE, BC_INST_MODULUS, + BC_INST_PLUS, BC_INST_MINUS, #if BC_ENABLE_EXTRA_MATH - BC_INST_PLACES, BC_INST_LSHIFT, BC_INST_RSHIFT, + BC_INST_PLACES, BC_INST_LSHIFT, + BC_INST_RSHIFT, #endif // BC_ENABLE_EXTRA_MATH - BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, - BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, + BC_INST_INVALID, BC_INST_INVALID, + BC_INST_INVALID, BC_INST_INVALID, + BC_INST_INVALID, BC_INST_INVALID, BC_INST_BOOL_OR, BC_INST_BOOL_AND, #if BC_ENABLED - BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, - BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, + BC_INST_INVALID, BC_INST_INVALID, + BC_INST_INVALID, BC_INST_INVALID, + BC_INST_INVALID, BC_INST_INVALID, #if BC_ENABLE_EXTRA_MATH - BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, + BC_INST_INVALID, BC_INST_INVALID, + BC_INST_INVALID, #endif // BC_ENABLE_EXTRA_MATH #endif // BC_ENABLED - BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, - BC_INST_REL_GT, BC_INST_REL_LT, BC_INST_INVALID, - BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GE, - BC_INST_INVALID, BC_INST_REL_LE, BC_INST_INVALID, + BC_INST_INVALID, BC_INST_INVALID, + BC_INST_INVALID, BC_INST_REL_GT, + BC_INST_REL_LT, BC_INST_INVALID, + BC_INST_INVALID, BC_INST_INVALID, + BC_INST_REL_GE, BC_INST_INVALID, + BC_INST_REL_LE, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, #if BC_ENABLED - BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, - BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, - BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, + BC_INST_INVALID, BC_INST_INVALID, + BC_INST_INVALID, BC_INST_INVALID, + BC_INST_INVALID, BC_INST_INVALID, + BC_INST_INVALID, BC_INST_INVALID, + BC_INST_INVALID, #endif // BC_ENABLED - BC_INST_IBASE, BC_INST_OBASE, BC_INST_SCALE, + BC_INST_IBASE, BC_INST_OBASE, + BC_INST_SCALE, #if BC_ENABLE_EXTRA_MATH BC_INST_SEED, #endif // BC_ENABLE_EXTRA_MATH - BC_INST_LENGTH, BC_INST_PRINT, BC_INST_SQRT, - BC_INST_ABS, BC_INST_IS_NUMBER, BC_INST_IS_STRING, + BC_INST_LENGTH, BC_INST_PRINT, + BC_INST_SQRT, BC_INST_ABS, + BC_INST_IS_NUMBER, BC_INST_IS_STRING, #if BC_ENABLE_EXTRA_MATH BC_INST_IRAND, #endif // BC_ENABLE_EXTRA_MATH - BC_INST_ASCIIFY, BC_INST_MODEXP, BC_INST_DIVMOD, - BC_INST_QUIT, BC_INST_INVALID, + BC_INST_ASCIIFY, BC_INST_MODEXP, + BC_INST_DIVMOD, BC_INST_QUIT, + BC_INST_INVALID, #if BC_ENABLE_EXTRA_MATH BC_INST_RAND, #endif // BC_ENABLE_EXTRA_MATH - BC_INST_MAXIBASE, BC_INST_MAXOBASE, BC_INST_MAXSCALE, + BC_INST_MAXIBASE, BC_INST_MAXOBASE, + BC_INST_MAXSCALE, #if BC_ENABLE_EXTRA_MATH BC_INST_MAXRAND, #endif // BC_ENABLE_EXTRA_MATH BC_INST_LINE_LENGTH, #if BC_ENABLED BC_INST_INVALID, #endif // BC_ENABLED - BC_INST_LEADING_ZERO, BC_INST_PRINT_STREAM, BC_INST_INVALID, - BC_INST_EXTENDED_REGISTERS, BC_INST_REL_EQ, BC_INST_INVALID, - BC_INST_EXECUTE, BC_INST_PRINT_STACK, BC_INST_CLEAR_STACK, - BC_INST_INVALID, BC_INST_STACK_LEN, BC_INST_DUPLICATE, - BC_INST_SWAP, BC_INST_POP, BC_INST_INVALID, - BC_INST_INVALID, BC_INST_INVALID, + BC_INST_LEADING_ZERO, BC_INST_PRINT_STREAM, + BC_INST_INVALID, BC_INST_EXTENDED_REGISTERS, + BC_INST_REL_EQ, BC_INST_INVALID, + BC_INST_EXECUTE, BC_INST_PRINT_STACK, + BC_INST_CLEAR_STACK, BC_INST_INVALID, + BC_INST_STACK_LEN, BC_INST_DUPLICATE, + BC_INST_SWAP, BC_INST_POP, + BC_INST_INVALID, BC_INST_INVALID, + BC_INST_INVALID, #if BC_ENABLE_EXTRA_MATH BC_INST_INVALID, #endif // BC_ENABLE_EXTRA_MATH - BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, - BC_INST_PRINT_POP, BC_INST_NQUIT, BC_INST_EXEC_STACK_LEN, + BC_INST_INVALID, BC_INST_INVALID, + BC_INST_INVALID, BC_INST_PRINT_POP, + BC_INST_NQUIT, BC_INST_EXEC_STACK_LEN, BC_INST_SCALE_FUNC, BC_INST_INVALID, }; #endif // DC_ENABLED #endif // !BC_ENABLE_LIBRARY #if BC_ENABLE_EXTRA_MATH /// A constant for the rand multiplier. const BcRandState bc_rand_multiplier = BC_RAND_MULTIPLIER; #endif // BC_ENABLE_EXTRA_MATH // clang-format off #if BC_LONG_BIT >= 64 /// A constant array for the max of a bigdig number as a BcDig array. const BcDig bc_num_bigdigMax[] = { 709551616U, 446744073U, 18U, }; /// A constant array for the max of 2 times a bigdig number as a BcDig array. const BcDig bc_num_bigdigMax2[] = { 768211456U, 374607431U, 938463463U, 282366920U, 340U, }; #else // BC_LONG_BIT >= 64 /// A constant array for the max of a bigdig number as a BcDig array. const BcDig bc_num_bigdigMax[] = { 7296U, 9496U, 42U, }; /// A constant array for the max of 2 times a bigdig number as a BcDig array. const BcDig bc_num_bigdigMax2[] = { 1616U, 955U, 737U, 6744U, 1844U, }; #endif // BC_LONG_BIT >= 64 // clang-format on /// The size of the bigdig max array. const size_t bc_num_bigdigMax_size = sizeof(bc_num_bigdigMax) / sizeof(BcDig); /// The size of the bigdig max times 2 array. const size_t bc_num_bigdigMax2_size = sizeof(bc_num_bigdigMax2) / sizeof(BcDig); /// A string of digits for easy conversion from characters to digits. const char bc_num_hex_digits[] = "0123456789ABCDEF"; // clang-format off /// An array for easy conversion from exponent to power of 10. const BcBigDig bc_num_pow10[BC_BASE_DIGS + 1] = { 1, 10, 100, 1000, 10000, #if BC_BASE_DIGS > 4 100000, 1000000, 10000000, 100000000, 1000000000, #endif // BC_BASE_DIGS > 4 }; // clang-format on #if !BC_ENABLE_LIBRARY /// An array of functions for binary operators corresponding to the order of /// the instructions for the operators. const BcNumBinaryOp bc_program_ops[] = { bc_num_pow, bc_num_mul, bc_num_div, bc_num_mod, bc_num_add, bc_num_sub, #if BC_ENABLE_EXTRA_MATH bc_num_places, bc_num_lshift, bc_num_rshift, #endif // BC_ENABLE_EXTRA_MATH }; /// An array of functions for binary operators allocation requests corresponding /// to the order of the instructions for the operators. const BcNumBinaryOpReq bc_program_opReqs[] = { bc_num_powReq, bc_num_mulReq, bc_num_divReq, bc_num_divReq, bc_num_addReq, bc_num_addReq, #if BC_ENABLE_EXTRA_MATH bc_num_placesReq, bc_num_placesReq, bc_num_placesReq, #endif // BC_ENABLE_EXTRA_MATH }; /// An array of unary operator functions corresponding to the order of the /// instructions. const BcProgramUnary bc_program_unarys[] = { bc_program_negate, bc_program_not, #if BC_ENABLE_EXTRA_MATH bc_program_trunc, #endif // BC_ENABLE_EXTRA_MATH }; /// A filename for when parsing expressions. const char bc_program_exprs_name[] = ""; /// A filename for when parsing stdin.. const char bc_program_stdin_name[] = ""; /// A ready message for SIGINT catching. const char bc_program_ready_msg[] = "ready for more input\n"; /// The length of the ready message. const size_t bc_program_ready_msg_len = sizeof(bc_program_ready_msg) - 1; /// A list of escape characters that a print statement should treat specially. const char bc_program_esc_chars[] = "ab\\efnqrt"; /// A list of characters corresponding to the escape characters above. const char bc_program_esc_seqs[] = "\a\b\\\\\f\n\"\r\t"; #endif // !BC_ENABLE_LIBRARY diff --git a/contrib/bc/src/library.c b/contrib/bc/src/library.c index 6283d198139e..cc32a3a3a98c 100644 --- a/contrib/bc/src/library.c +++ b/contrib/bc/src/library.c @@ -1,1469 +1,1768 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2023 Gavin D. Howard and contributors. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * ***************************************************************************** * * The public functions for libbc. * */ #if BC_ENABLE_LIBRARY #include #include #include #include #include #include #include #ifndef _WIN32 #include #endif // _WIN32 // The asserts in this file are important to testing; in many cases, the test // would not work without the asserts, so don't remove them without reason. // // Also, there are many uses of bc_num_clear() here; that is because numbers are // being reused, and a clean slate is required. // // Also, there are a bunch of BC_UNSETJMP between calls to bc_num_init(). That // is because locals are being initialized, and unlike bc proper, this code // cannot assume that allocation failures are fatal. So we have to reset the // jumps every time to ensure that the locals will be correct after jumping. +#if BC_ENABLE_MEMCHECK + +BC_NORETURN void +bcl_invalidGeneration(void) +{ + abort(); +} + +BC_NORETURN void +bcl_nonexistentNum(void) +{ + abort(); +} + +BC_NORETURN void +bcl_numIdxOutOfRange(void) +{ + abort(); +} + +#endif // BC_ENABLE_MEMCHECK + static BclTls* tls = NULL; static BclTls tls_real; BclError bcl_start(void) { #ifndef _WIN32 int r; if (tls != NULL) return BCL_ERROR_NONE; r = pthread_key_create(&tls_real, NULL); if (BC_ERR(r != 0)) return BCL_ERROR_FATAL_ALLOC_ERR; #else // _WIN32 if (tls != NULL) return BCL_ERROR_NONE; tls_real = TlsAlloc(); if (BC_ERR(tls_real == TLS_OUT_OF_INDEXES)) { return BCL_ERROR_FATAL_ALLOC_ERR; } #endif // _WIN32 tls = &tls_real; return BCL_ERROR_NONE; } /** * Sets the thread-specific data for the thread. * @param vm The @a BcVm to set as the thread data. * @return An error code, if any. */ static BclError bcl_setspecific(BcVm* vm) { #ifndef _WIN32 int r; assert(tls != NULL); r = pthread_setspecific(tls_real, vm); if (BC_ERR(r != 0)) return BCL_ERROR_FATAL_ALLOC_ERR; #else // _WIN32 bool r; assert(tls != NULL); r = TlsSetValue(tls_real, vm); if (BC_ERR(!r)) return BCL_ERROR_FATAL_ALLOC_ERR; #endif // _WIN32 return BCL_ERROR_NONE; } BcVm* bcl_getspecific(void) { BcVm* vm; #ifndef _WIN32 vm = pthread_getspecific(tls_real); #else // _WIN32 vm = TlsGetValue(tls_real); #endif // _WIN32 return vm; } BclError bcl_init(void) { BclError e = BCL_ERROR_NONE; BcVm* vm; assert(tls != NULL); vm = bcl_getspecific(); if (vm != NULL) { assert(vm->refs >= 1); vm->refs += 1; return e; } vm = bc_vm_malloc(sizeof(BcVm)); if (BC_ERR(vm == NULL)) return BCL_ERROR_FATAL_ALLOC_ERR; e = bcl_setspecific(vm); if (BC_ERR(e != BCL_ERROR_NONE)) { free(vm); return e; } memset(vm, 0, sizeof(BcVm)); vm->refs += 1; assert(vm->refs == 1); // Setting these to NULL ensures that if an error occurs, we only free what // is necessary. vm->ctxts.v = NULL; vm->jmp_bufs.v = NULL; vm->out.v = NULL; vm->abrt = false; vm->leading_zeroes = false; vm->digit_clamp = true; // The jmp_bufs always has to be initialized first. bc_vec_init(&vm->jmp_bufs, sizeof(sigjmp_buf), BC_DTOR_NONE); BC_FUNC_HEADER(vm, err); bc_vm_init(); bc_vec_init(&vm->ctxts, sizeof(BclContext), BC_DTOR_NONE); bc_vec_init(&vm->out, sizeof(uchar), BC_DTOR_NONE); - // We need to seed this in case /dev/random and /dev/urandm don't work. +#if BC_ENABLE_EXTRA_MATH + + // We need to seed this in case /dev/random and /dev/urandom don't work. srand((unsigned int) time(NULL)); bc_rand_init(&vm->rng); +#endif // BC_ENABLE_EXTRA_MATH + err: BC_FUNC_FOOTER(vm, e); // This is why we had to set them to NULL. if (BC_ERR(vm != NULL && vm->err)) { if (vm->out.v != NULL) bc_vec_free(&vm->out); if (vm->jmp_bufs.v != NULL) bc_vec_free(&vm->jmp_bufs); if (vm->ctxts.v != NULL) bc_vec_free(&vm->ctxts); bcl_setspecific(NULL); free(vm); } return e; } BclError bcl_pushContext(BclContext ctxt) { BclError e = BCL_ERROR_NONE; BcVm* vm = bcl_getspecific(); BC_FUNC_HEADER(vm, err); bc_vec_push(&vm->ctxts, &ctxt); err: + BC_FUNC_FOOTER(vm, e); return e; } void bcl_popContext(void) { BcVm* vm = bcl_getspecific(); if (vm->ctxts.len) bc_vec_pop(&vm->ctxts); } static BclContext bcl_contextHelper(BcVm* vm) { if (!vm->ctxts.len) return NULL; return *((BclContext*) bc_vec_top(&vm->ctxts)); } BclContext bcl_context(void) { BcVm* vm = bcl_getspecific(); return bcl_contextHelper(vm); } void bcl_free(void) { size_t i; BcVm* vm = bcl_getspecific(); vm->refs -= 1; if (vm->refs) return; +#if BC_ENABLE_EXTRA_MATH bc_rand_free(&vm->rng); +#endif // BC_ENABLE_EXTRA_MATH bc_vec_free(&vm->out); for (i = 0; i < vm->ctxts.len; ++i) { BclContext ctxt = *((BclContext*) bc_vec_item(&vm->ctxts, i)); bcl_ctxt_free(ctxt); } bc_vec_free(&vm->ctxts); bc_vm_atexit(); free(vm); bcl_setspecific(NULL); } void bcl_end(void) { #ifndef _WIN32 // We ignore the return value. pthread_key_delete(tls_real); #else // _WIN32 // We ignore the return value. TlsFree(tls_real); #endif // _WIN32 tls = NULL; } void bcl_gc(void) { bc_vm_freeTemps(); } bool bcl_abortOnFatalError(void) { BcVm* vm = bcl_getspecific(); return vm->abrt; } void bcl_setAbortOnFatalError(bool abrt) { BcVm* vm = bcl_getspecific(); vm->abrt = abrt; } bool bcl_leadingZeroes(void) { BcVm* vm = bcl_getspecific(); return vm->leading_zeroes; } void bcl_setLeadingZeroes(bool leadingZeroes) { BcVm* vm = bcl_getspecific(); vm->leading_zeroes = leadingZeroes; } bool bcl_digitClamp(void) { BcVm* vm = bcl_getspecific(); return vm->digit_clamp; } void bcl_setDigitClamp(bool digitClamp) { BcVm* vm = bcl_getspecific(); vm->digit_clamp = digitClamp; } BclContext bcl_ctxt_create(void) { BcVm* vm = bcl_getspecific(); BclContext ctxt = NULL; BC_FUNC_HEADER(vm, err); // We want the context to be free of any interference of other parties, so // malloc() is appropriate here. ctxt = bc_vm_malloc(sizeof(BclCtxt)); - bc_vec_init(&ctxt->nums, sizeof(BcNum), BC_DTOR_BCL_NUM); + bc_vec_init(&ctxt->nums, sizeof(BclNum), BC_DTOR_BCL_NUM); bc_vec_init(&ctxt->free_nums, sizeof(BclNumber), BC_DTOR_NONE); ctxt->scale = 0; ctxt->ibase = 10; ctxt->obase = 10; err: if (BC_ERR(vm->err && ctxt != NULL)) { if (ctxt->nums.v != NULL) bc_vec_free(&ctxt->nums); free(ctxt); ctxt = NULL; } BC_FUNC_FOOTER_NO_ERR(vm); return ctxt; } void bcl_ctxt_free(BclContext ctxt) { bc_vec_free(&ctxt->free_nums); bc_vec_free(&ctxt->nums); free(ctxt); } void bcl_ctxt_freeNums(BclContext ctxt) { bc_vec_popAll(&ctxt->nums); bc_vec_popAll(&ctxt->free_nums); } size_t bcl_ctxt_scale(BclContext ctxt) { return ctxt->scale; } void bcl_ctxt_setScale(BclContext ctxt, size_t scale) { ctxt->scale = scale; } size_t bcl_ctxt_ibase(BclContext ctxt) { return ctxt->ibase; } void bcl_ctxt_setIbase(BclContext ctxt, size_t ibase) { if (ibase < BC_NUM_MIN_BASE) ibase = BC_NUM_MIN_BASE; else if (ibase > BC_NUM_MAX_IBASE) ibase = BC_NUM_MAX_IBASE; ctxt->ibase = ibase; } size_t bcl_ctxt_obase(BclContext ctxt) { return ctxt->obase; } void bcl_ctxt_setObase(BclContext ctxt, size_t obase) { ctxt->obase = obase; } BclError bcl_err(BclNumber n) { BclContext ctxt; BcVm* vm = bcl_getspecific(); BC_CHECK_CTXT_ERR(vm, ctxt); + // We need to clear the top byte in memcheck mode. We can do this because + // the parameter is a copy. + BCL_CLEAR_GEN(n); + // Errors are encoded as (0 - error_code). If the index is in that range, it // is an encoded error. if (n.i >= ctxt->nums.len) { if (n.i > 0 - (size_t) BCL_ERROR_NELEMS) return (BclError) (0 - n.i); else return BCL_ERROR_INVALID_NUM; } else return BCL_ERROR_NONE; } /** * Inserts a BcNum into a context's list of numbers. * @param ctxt The context to insert into. * @param n The BcNum to insert. * @return The resulting BclNumber from the insert. */ static BclNumber -bcl_num_insert(BclContext ctxt, BcNum* restrict n) +bcl_num_insert(BclContext ctxt, BclNum* restrict n) { BclNumber idx; // If there is a free spot... if (ctxt->free_nums.len) { - BcNum* ptr; + BclNum* ptr; // Get the index of the free spot and remove it. idx = *((BclNumber*) bc_vec_top(&ctxt->free_nums)); bc_vec_pop(&ctxt->free_nums); // Copy the number into the spot. ptr = bc_vec_item(&ctxt->nums, idx.i); - memcpy(ptr, n, sizeof(BcNum)); + + memcpy(BCL_NUM_NUM(ptr), n, sizeof(BcNum)); + +#if BC_ENABLE_MEMCHECK + + ptr->gen_idx += 1; + + if (ptr->gen_idx == UCHAR_MAX) + { + ptr->gen_idx = 0; + } + + idx.i |= (ptr->gen_idx << ((sizeof(size_t) - 1) * CHAR_BIT)); + +#endif // BC_ENABLE_MEMCHECK } else { - // Just push the number onto the vector. +#if BC_ENABLE_MEMCHECK + n->gen_idx = 0; +#endif // BC_ENABLE_MEMCHECK + + // Just push the number onto the vector because the generation index is + // 0. idx.i = ctxt->nums.len; bc_vec_push(&ctxt->nums, n); } return idx; } BclNumber bcl_num_create(void) { BclError e = BCL_ERROR_NONE; - BcNum n; + BclNum n; BclNumber idx; BclContext ctxt; BcVm* vm = bcl_getspecific(); BC_CHECK_CTXT(vm, ctxt); BC_FUNC_HEADER(vm, err); - bc_vec_grow(&ctxt->nums, 1); + BCL_GROW_NUMS(ctxt); - bc_num_init(&n, BC_NUM_DEF_SIZE); + bc_num_init(BCL_NUM_NUM_NP(n), BC_NUM_DEF_SIZE); err: + BC_FUNC_FOOTER(vm, e); BC_MAYBE_SETUP(ctxt, e, n, idx); return idx; } /** * Destructs a number and marks its spot as free. * @param ctxt The context. * @param n The index of the number. * @param num The number to destroy. */ static void -bcl_num_dtor(BclContext ctxt, BclNumber n, BcNum* restrict num) +bcl_num_dtor(BclContext ctxt, BclNumber n, BclNum* restrict num) { - assert(num != NULL && num->num != NULL); + assert(num != NULL && BCL_NUM_ARRAY(num) != NULL); + + BCL_CLEAR_GEN(n); bcl_num_destruct(num); bc_vec_push(&ctxt->free_nums, &n); + +#if BC_ENABLE_MEMCHECK + num->n.num = NULL; +#endif // BC_ENABLE_MEMCHECK } void bcl_num_free(BclNumber n) { - BcNum* num; + BclNum* num; BclContext ctxt; BcVm* vm = bcl_getspecific(); BC_CHECK_CTXT_ASSERT(vm, ctxt); - assert(n.i < ctxt->nums.len); + BCL_CHECK_NUM_VALID(ctxt, n); + + assert(BCL_NO_GEN(n) < ctxt->nums.len); - num = BC_NUM(ctxt, n); + num = BCL_NUM(ctxt, n); bcl_num_dtor(ctxt, n, num); } BclError bcl_copy(BclNumber d, BclNumber s) { BclError e = BCL_ERROR_NONE; - BcNum* dest; - BcNum* src; + BclNum* dest; + BclNum* src; BclContext ctxt; BcVm* vm = bcl_getspecific(); BC_CHECK_CTXT_ERR(vm, ctxt); + BCL_CHECK_NUM_VALID(ctxt, d); + BCL_CHECK_NUM_VALID(ctxt, s); + BC_FUNC_HEADER(vm, err); - assert(d.i < ctxt->nums.len && s.i < ctxt->nums.len); + assert(BCL_NO_GEN(d) < ctxt->nums.len); + assert(BCL_NO_GEN(s) < ctxt->nums.len); - dest = BC_NUM(ctxt, d); - src = BC_NUM(ctxt, s); + dest = BCL_NUM(ctxt, d); + src = BCL_NUM(ctxt, s); assert(dest != NULL && src != NULL); - assert(dest->num != NULL && src->num != NULL); + assert(BCL_NUM_ARRAY(dest) != NULL && BCL_NUM_ARRAY(src) != NULL); - bc_num_copy(dest, src); + bc_num_copy(BCL_NUM_NUM(dest), BCL_NUM_NUM(src)); err: + BC_FUNC_FOOTER(vm, e); return e; } BclNumber bcl_dup(BclNumber s) { BclError e = BCL_ERROR_NONE; - BcNum *src, dest; + BclNum *src, dest; BclNumber idx; BclContext ctxt; BcVm* vm = bcl_getspecific(); BC_CHECK_CTXT(vm, ctxt); + BCL_CHECK_NUM_VALID(ctxt, s); + BC_FUNC_HEADER(vm, err); - bc_vec_grow(&ctxt->nums, 1); + BCL_GROW_NUMS(ctxt); - assert(s.i < ctxt->nums.len); + assert(BCL_NO_GEN(s) < ctxt->nums.len); - src = BC_NUM(ctxt, s); + src = BCL_NUM(ctxt, s); - assert(src != NULL && src->num != NULL); + assert(src != NULL && BCL_NUM_NUM(src) != NULL); // Copy the number. - bc_num_clear(&dest); - bc_num_createCopy(&dest, src); + bc_num_clear(BCL_NUM_NUM(&dest)); + bc_num_createCopy(BCL_NUM_NUM(&dest), BCL_NUM_NUM(src)); err: + BC_FUNC_FOOTER(vm, e); BC_MAYBE_SETUP(ctxt, e, dest, idx); return idx; } void bcl_num_destruct(void* num) { - BcNum* n = (BcNum*) num; + BclNum* n = (BclNum*) num; assert(n != NULL); - if (n->num == NULL) return; + if (BCL_NUM_ARRAY(n) == NULL) return; - bc_num_free(num); - bc_num_clear(num); + bc_num_free(BCL_NUM_NUM(n)); + bc_num_clear(BCL_NUM_NUM(n)); } bool bcl_num_neg(BclNumber n) { - BcNum* num; + BclNum* num; BclContext ctxt; BcVm* vm = bcl_getspecific(); BC_CHECK_CTXT_ASSERT(vm, ctxt); - assert(n.i < ctxt->nums.len); + BCL_CHECK_NUM_VALID(ctxt, n); - num = BC_NUM(ctxt, n); + assert(BCL_NO_GEN(n) < ctxt->nums.len); - assert(num != NULL && num->num != NULL); + num = BCL_NUM(ctxt, n); - return BC_NUM_NEG(num) != 0; + assert(num != NULL && BCL_NUM_ARRAY(num) != NULL); + + return BC_NUM_NEG(BCL_NUM_NUM(num)) != 0; } void bcl_num_setNeg(BclNumber n, bool neg) { - BcNum* num; + BclNum* num; BclContext ctxt; BcVm* vm = bcl_getspecific(); BC_CHECK_CTXT_ASSERT(vm, ctxt); - assert(n.i < ctxt->nums.len); + BCL_CHECK_NUM_VALID(ctxt, n); + + assert(BCL_NO_GEN(n) < ctxt->nums.len); - num = BC_NUM(ctxt, n); + num = BCL_NUM(ctxt, n); - assert(num != NULL && num->num != NULL); + assert(num != NULL && BCL_NUM_ARRAY(num) != NULL); - num->rdx = BC_NUM_NEG_VAL(num, neg); + BCL_NUM_NUM(num)->rdx = BC_NUM_NEG_VAL(BCL_NUM_NUM(num), neg); } size_t bcl_num_scale(BclNumber n) { - BcNum* num; + BclNum* num; BclContext ctxt; BcVm* vm = bcl_getspecific(); BC_CHECK_CTXT_ASSERT(vm, ctxt); - assert(n.i < ctxt->nums.len); + BCL_CHECK_NUM_VALID(ctxt, n); + + assert(BCL_NO_GEN(n) < ctxt->nums.len); - num = BC_NUM(ctxt, n); + num = BCL_NUM(ctxt, n); - assert(num != NULL && num->num != NULL); + assert(num != NULL && BCL_NUM_ARRAY(num) != NULL); - return bc_num_scale(num); + return bc_num_scale(BCL_NUM_NUM(num)); } BclError bcl_num_setScale(BclNumber n, size_t scale) { BclError e = BCL_ERROR_NONE; - BcNum* nptr; + BclNum* nptr; BclContext ctxt; BcVm* vm = bcl_getspecific(); BC_CHECK_CTXT_ERR(vm, ctxt); BC_CHECK_NUM_ERR(ctxt, n); + BCL_CHECK_NUM_VALID(ctxt, n); + BC_FUNC_HEADER(vm, err); - assert(n.i < ctxt->nums.len); + assert(BCL_NO_GEN(n) < ctxt->nums.len); - nptr = BC_NUM(ctxt, n); + nptr = BCL_NUM(ctxt, n); - assert(nptr != NULL && nptr->num != NULL); + assert(nptr != NULL && BCL_NUM_ARRAY(nptr) != NULL); - if (scale > nptr->scale) bc_num_extend(nptr, scale - nptr->scale); - else if (scale < nptr->scale) bc_num_truncate(nptr, nptr->scale - scale); + if (scale > BCL_NUM_NUM(nptr)->scale) + { + bc_num_extend(BCL_NUM_NUM(nptr), scale - BCL_NUM_NUM(nptr)->scale); + } + else if (scale < BCL_NUM_NUM(nptr)->scale) + { + bc_num_truncate(BCL_NUM_NUM(nptr), BCL_NUM_NUM(nptr)->scale - scale); + } err: + BC_FUNC_FOOTER(vm, e); return e; } size_t bcl_num_len(BclNumber n) { - BcNum* num; + BclNum* num; BclContext ctxt; BcVm* vm = bcl_getspecific(); BC_CHECK_CTXT_ASSERT(vm, ctxt); - assert(n.i < ctxt->nums.len); + BCL_CHECK_NUM_VALID(ctxt, n); - num = BC_NUM(ctxt, n); + assert(BCL_NO_GEN(n) < ctxt->nums.len); - assert(num != NULL && num->num != NULL); + num = BCL_NUM(ctxt, n); - return bc_num_len(num); + assert(num != NULL && BCL_NUM_ARRAY(num) != NULL); + + return bc_num_len(BCL_NUM_NUM(num)); } -BclError -bcl_bigdig(BclNumber n, BclBigDig* result) +static BclError +bcl_bigdig_helper(BclNumber n, BclBigDig* result, bool destruct) { BclError e = BCL_ERROR_NONE; - BcNum* num; + BclNum* num; BclContext ctxt; BcVm* vm = bcl_getspecific(); BC_CHECK_CTXT_ERR(vm, ctxt); + BCL_CHECK_NUM_VALID(ctxt, n); + BC_FUNC_HEADER(vm, err); - assert(n.i < ctxt->nums.len); + assert(BCL_NO_GEN(n) < ctxt->nums.len); assert(result != NULL); - num = BC_NUM(ctxt, n); + num = BCL_NUM(ctxt, n); - assert(num != NULL && num->num != NULL); + assert(num != NULL && BCL_NUM_ARRAY(num) != NULL); - *result = bc_num_bigdig(num); + *result = bc_num_bigdig(BCL_NUM_NUM(num)); err: - bcl_num_dtor(ctxt, n, num); + + if (destruct) + { + bcl_num_dtor(ctxt, n, num); + } + BC_FUNC_FOOTER(vm, e); return e; } +BclError +bcl_bigdig(BclNumber n, BclBigDig* result) +{ + return bcl_bigdig_helper(n, result, true); +} + +BclError +bcl_bigdig_keep(BclNumber n, BclBigDig* result) +{ + return bcl_bigdig_helper(n, result, false); +} + BclNumber bcl_bigdig2num(BclBigDig val) { BclError e = BCL_ERROR_NONE; - BcNum n; + BclNum n; BclNumber idx; BclContext ctxt; BcVm* vm = bcl_getspecific(); BC_CHECK_CTXT(vm, ctxt); BC_FUNC_HEADER(vm, err); - bc_vec_grow(&ctxt->nums, 1); + BCL_GROW_NUMS(ctxt); - bc_num_createFromBigdig(&n, val); + bc_num_createFromBigdig(BCL_NUM_NUM_NP(n), val); err: + BC_FUNC_FOOTER(vm, e); BC_MAYBE_SETUP(ctxt, e, n, idx); return idx; } /** * Sets up and executes a binary operator operation. - * @param a The first operand. - * @param b The second operand. - * @param op The operation. - * @param req The function to get the size of the result for preallocation. - * @return The result of the operation. + * @param a The first operand. + * @param b The second operand. + * @param op The operation. + * @param req The function to get the size of the result for + * preallocation. + * @param destruct True if the parameters should be consumed, false otherwise. + * @return The result of the operation. */ static BclNumber bcl_binary(BclNumber a, BclNumber b, const BcNumBinaryOp op, - const BcNumBinaryOpReq req) + const BcNumBinaryOpReq req, bool destruct) { BclError e = BCL_ERROR_NONE; - BcNum* aptr; - BcNum* bptr; - BcNum c; + BclNum* aptr; + BclNum* bptr; + BclNum c; BclNumber idx; BclContext ctxt; BcVm* vm = bcl_getspecific(); BC_CHECK_CTXT(vm, ctxt); BC_CHECK_NUM(ctxt, a); BC_CHECK_NUM(ctxt, b); BC_FUNC_HEADER(vm, err); - bc_vec_grow(&ctxt->nums, 1); + BCL_GROW_NUMS(ctxt); - assert(a.i < ctxt->nums.len && b.i < ctxt->nums.len); + assert(BCL_NO_GEN(a) < ctxt->nums.len && BCL_NO_GEN(b) < ctxt->nums.len); - aptr = BC_NUM(ctxt, a); - bptr = BC_NUM(ctxt, b); + aptr = BCL_NUM(ctxt, a); + bptr = BCL_NUM(ctxt, b); assert(aptr != NULL && bptr != NULL); - assert(aptr->num != NULL && bptr->num != NULL); + assert(BCL_NUM_ARRAY(aptr) != NULL && BCL_NUM_ARRAY(bptr) != NULL); // Clear and initialize the result. - bc_num_clear(&c); - bc_num_init(&c, req(aptr, bptr, ctxt->scale)); + bc_num_clear(BCL_NUM_NUM_NP(c)); + bc_num_init(BCL_NUM_NUM_NP(c), + req(BCL_NUM_NUM(aptr), BCL_NUM_NUM(bptr), ctxt->scale)); - op(aptr, bptr, &c, ctxt->scale); + op(BCL_NUM_NUM(aptr), BCL_NUM_NUM(bptr), BCL_NUM_NUM_NP(c), ctxt->scale); err: - // Eat the operands. - bcl_num_dtor(ctxt, a, aptr); - if (b.i != a.i) bcl_num_dtor(ctxt, b, bptr); + if (destruct) + { + // Eat the operands. + bcl_num_dtor(ctxt, a, aptr); + if (b.i != a.i) bcl_num_dtor(ctxt, b, bptr); + } BC_FUNC_FOOTER(vm, e); BC_MAYBE_SETUP(ctxt, e, c, idx); return idx; } BclNumber bcl_add(BclNumber a, BclNumber b) { - return bcl_binary(a, b, bc_num_add, bc_num_addReq); + return bcl_binary(a, b, bc_num_add, bc_num_addReq, true); +} + +BclNumber +bcl_add_keep(BclNumber a, BclNumber b) +{ + return bcl_binary(a, b, bc_num_add, bc_num_addReq, false); } BclNumber bcl_sub(BclNumber a, BclNumber b) { - return bcl_binary(a, b, bc_num_sub, bc_num_addReq); + return bcl_binary(a, b, bc_num_sub, bc_num_addReq, true); +} + +BclNumber +bcl_sub_keep(BclNumber a, BclNumber b) +{ + return bcl_binary(a, b, bc_num_sub, bc_num_addReq, false); } BclNumber bcl_mul(BclNumber a, BclNumber b) { - return bcl_binary(a, b, bc_num_mul, bc_num_mulReq); + return bcl_binary(a, b, bc_num_mul, bc_num_mulReq, true); +} + +BclNumber +bcl_mul_keep(BclNumber a, BclNumber b) +{ + return bcl_binary(a, b, bc_num_mul, bc_num_mulReq, false); } BclNumber bcl_div(BclNumber a, BclNumber b) { - return bcl_binary(a, b, bc_num_div, bc_num_divReq); + return bcl_binary(a, b, bc_num_div, bc_num_divReq, true); +} + +BclNumber +bcl_div_keep(BclNumber a, BclNumber b) +{ + return bcl_binary(a, b, bc_num_div, bc_num_divReq, false); } BclNumber bcl_mod(BclNumber a, BclNumber b) { - return bcl_binary(a, b, bc_num_mod, bc_num_divReq); + return bcl_binary(a, b, bc_num_mod, bc_num_divReq, true); +} + +BclNumber +bcl_mod_keep(BclNumber a, BclNumber b) +{ + return bcl_binary(a, b, bc_num_mod, bc_num_divReq, false); } BclNumber bcl_pow(BclNumber a, BclNumber b) { - return bcl_binary(a, b, bc_num_pow, bc_num_powReq); + return bcl_binary(a, b, bc_num_pow, bc_num_powReq, true); +} + +BclNumber +bcl_pow_keep(BclNumber a, BclNumber b) +{ + return bcl_binary(a, b, bc_num_pow, bc_num_powReq, false); } BclNumber bcl_lshift(BclNumber a, BclNumber b) { - return bcl_binary(a, b, bc_num_lshift, bc_num_placesReq); + return bcl_binary(a, b, bc_num_lshift, bc_num_placesReq, true); +} + +BclNumber +bcl_lshift_keep(BclNumber a, BclNumber b) +{ + return bcl_binary(a, b, bc_num_lshift, bc_num_placesReq, false); } BclNumber bcl_rshift(BclNumber a, BclNumber b) { - return bcl_binary(a, b, bc_num_rshift, bc_num_placesReq); + return bcl_binary(a, b, bc_num_rshift, bc_num_placesReq, true); } BclNumber -bcl_sqrt(BclNumber a) +bcl_rshift_keep(BclNumber a, BclNumber b) +{ + return bcl_binary(a, b, bc_num_rshift, bc_num_placesReq, false); +} + +static BclNumber +bcl_sqrt_helper(BclNumber a, bool destruct) { BclError e = BCL_ERROR_NONE; - BcNum* aptr; - BcNum b; + BclNum* aptr; + BclNum b; BclNumber idx; BclContext ctxt; BcVm* vm = bcl_getspecific(); BC_CHECK_CTXT(vm, ctxt); BC_CHECK_NUM(ctxt, a); BC_FUNC_HEADER(vm, err); - bc_vec_grow(&ctxt->nums, 1); + BCL_GROW_NUMS(ctxt); - assert(a.i < ctxt->nums.len); + assert(BCL_NO_GEN(a) < ctxt->nums.len); - aptr = BC_NUM(ctxt, a); + aptr = BCL_NUM(ctxt, a); - bc_num_sqrt(aptr, &b, ctxt->scale); + bc_num_sqrt(BCL_NUM_NUM(aptr), BCL_NUM_NUM_NP(b), ctxt->scale); err: - bcl_num_dtor(ctxt, a, aptr); + + if (destruct) + { + bcl_num_dtor(ctxt, a, aptr); + } + BC_FUNC_FOOTER(vm, e); BC_MAYBE_SETUP(ctxt, e, b, idx); return idx; } -BclError -bcl_divmod(BclNumber a, BclNumber b, BclNumber* c, BclNumber* d) +BclNumber +bcl_sqrt(BclNumber a) +{ + return bcl_sqrt_helper(a, true); +} + +BclNumber +bcl_sqrt_keep(BclNumber a) +{ + return bcl_sqrt_helper(a, false); +} + +static BclError +bcl_divmod_helper(BclNumber a, BclNumber b, BclNumber* c, BclNumber* d, + bool destruct) { BclError e = BCL_ERROR_NONE; size_t req; - BcNum* aptr; - BcNum* bptr; - BcNum cnum, dnum; + BclNum* aptr; + BclNum* bptr; + BclNum cnum, dnum; BclContext ctxt; BcVm* vm = bcl_getspecific(); BC_CHECK_CTXT_ERR(vm, ctxt); BC_CHECK_NUM_ERR(ctxt, a); BC_CHECK_NUM_ERR(ctxt, b); BC_FUNC_HEADER(vm, err); - bc_vec_grow(&ctxt->nums, 2); + BCL_GROW_NUMS(ctxt); assert(c != NULL && d != NULL); - aptr = BC_NUM(ctxt, a); - bptr = BC_NUM(ctxt, b); + aptr = BCL_NUM(ctxt, a); + bptr = BCL_NUM(ctxt, b); assert(aptr != NULL && bptr != NULL); - assert(aptr->num != NULL && bptr->num != NULL); + assert(BCL_NUM_ARRAY(aptr) != NULL && BCL_NUM_ARRAY(bptr) != NULL); - bc_num_clear(&cnum); - bc_num_clear(&dnum); + bc_num_clear(BCL_NUM_NUM_NP(cnum)); + bc_num_clear(BCL_NUM_NUM_NP(dnum)); - req = bc_num_divReq(aptr, bptr, ctxt->scale); + req = bc_num_divReq(BCL_NUM_NUM(aptr), BCL_NUM_NUM(bptr), ctxt->scale); // Initialize the numbers. - bc_num_init(&cnum, req); + bc_num_init(BCL_NUM_NUM_NP(cnum), req); BC_UNSETJMP(vm); BC_SETJMP(vm, err); - bc_num_init(&dnum, req); + bc_num_init(BCL_NUM_NUM_NP(dnum), req); - bc_num_divmod(aptr, bptr, &cnum, &dnum, ctxt->scale); + bc_num_divmod(BCL_NUM_NUM(aptr), BCL_NUM_NUM(bptr), BCL_NUM_NUM_NP(cnum), + BCL_NUM_NUM_NP(dnum), ctxt->scale); err: - // Eat the operands. - bcl_num_dtor(ctxt, a, aptr); - if (b.i != a.i) bcl_num_dtor(ctxt, b, bptr); + if (destruct) + { + // Eat the operands. + bcl_num_dtor(ctxt, a, aptr); + if (b.i != a.i) bcl_num_dtor(ctxt, b, bptr); + } // If there was an error... if (BC_ERR(vm->err)) { // Free the results. - if (cnum.num != NULL) bc_num_free(&cnum); - if (dnum.num != NULL) bc_num_free(&dnum); + if (BCL_NUM_ARRAY_NP(cnum) != NULL) bc_num_free(&cnum); + if (BCL_NUM_ARRAY_NP(cnum) != NULL) bc_num_free(&dnum); // Make sure the return values are invalid. c->i = 0 - (size_t) BCL_ERROR_INVALID_NUM; d->i = c->i; BC_FUNC_FOOTER(vm, e); } else { BC_FUNC_FOOTER(vm, e); // Insert the results into the context. *c = bcl_num_insert(ctxt, &cnum); *d = bcl_num_insert(ctxt, &dnum); } return e; } -BclNumber -bcl_modexp(BclNumber a, BclNumber b, BclNumber c) +BclError +bcl_divmod(BclNumber a, BclNumber b, BclNumber* c, BclNumber* d) +{ + return bcl_divmod_helper(a, b, c, d, true); +} + +BclError +bcl_divmod_keep(BclNumber a, BclNumber b, BclNumber* c, BclNumber* d) +{ + return bcl_divmod_helper(a, b, c, d, false); +} + +static BclNumber +bcl_modexp_helper(BclNumber a, BclNumber b, BclNumber c, bool destruct) { BclError e = BCL_ERROR_NONE; size_t req; - BcNum* aptr; - BcNum* bptr; - BcNum* cptr; - BcNum d; + BclNum* aptr; + BclNum* bptr; + BclNum* cptr; + BclNum d; BclNumber idx; BclContext ctxt; BcVm* vm = bcl_getspecific(); BC_CHECK_CTXT(vm, ctxt); BC_CHECK_NUM(ctxt, a); BC_CHECK_NUM(ctxt, b); BC_CHECK_NUM(ctxt, c); BC_FUNC_HEADER(vm, err); - bc_vec_grow(&ctxt->nums, 1); + BCL_GROW_NUMS(ctxt); - assert(a.i < ctxt->nums.len && b.i < ctxt->nums.len); - assert(c.i < ctxt->nums.len); + assert(BCL_NO_GEN(a) < ctxt->nums.len && BCL_NO_GEN(b) < ctxt->nums.len); + assert(BCL_NO_GEN(c) < ctxt->nums.len); - aptr = BC_NUM(ctxt, a); - bptr = BC_NUM(ctxt, b); - cptr = BC_NUM(ctxt, c); + aptr = BCL_NUM(ctxt, a); + bptr = BCL_NUM(ctxt, b); + cptr = BCL_NUM(ctxt, c); assert(aptr != NULL && bptr != NULL && cptr != NULL); - assert(aptr->num != NULL && bptr->num != NULL && cptr->num != NULL); + assert(BCL_NUM_NUM(aptr) != NULL && BCL_NUM_NUM(bptr) != NULL && + BCL_NUM_NUM(cptr) != NULL); // Prepare the result. - bc_num_clear(&d); + bc_num_clear(BCL_NUM_NUM_NP(d)); - req = bc_num_divReq(aptr, cptr, 0); + req = bc_num_divReq(BCL_NUM_NUM(aptr), BCL_NUM_NUM(cptr), 0); // Initialize the result. - bc_num_init(&d, req); + bc_num_init(BCL_NUM_NUM_NP(d), req); - bc_num_modexp(aptr, bptr, cptr, &d); + bc_num_modexp(BCL_NUM_NUM(aptr), BCL_NUM_NUM(bptr), BCL_NUM_NUM(cptr), + BCL_NUM_NUM_NP(d)); err: - // Eat the operands. - bcl_num_dtor(ctxt, a, aptr); - if (b.i != a.i) bcl_num_dtor(ctxt, b, bptr); - if (c.i != a.i && c.i != b.i) bcl_num_dtor(ctxt, c, cptr); + if (destruct) + { + // Eat the operands. + bcl_num_dtor(ctxt, a, aptr); + if (b.i != a.i) bcl_num_dtor(ctxt, b, bptr); + if (c.i != a.i && c.i != b.i) bcl_num_dtor(ctxt, c, cptr); + } BC_FUNC_FOOTER(vm, e); BC_MAYBE_SETUP(ctxt, e, d, idx); return idx; } +BclNumber +bcl_modexp(BclNumber a, BclNumber b, BclNumber c) +{ + return bcl_modexp_helper(a, b, c, true); +} + +BclNumber +bcl_modexp_keep(BclNumber a, BclNumber b, BclNumber c) +{ + return bcl_modexp_helper(a, b, c, false); +} + ssize_t bcl_cmp(BclNumber a, BclNumber b) { - BcNum* aptr; - BcNum* bptr; + BclNum* aptr; + BclNum* bptr; BclContext ctxt; BcVm* vm = bcl_getspecific(); BC_CHECK_CTXT_ASSERT(vm, ctxt); - assert(a.i < ctxt->nums.len && b.i < ctxt->nums.len); + BCL_CHECK_NUM_VALID(ctxt, a); + BCL_CHECK_NUM_VALID(ctxt, b); + + assert(BCL_NO_GEN(a) < ctxt->nums.len && BCL_NO_GEN(b) < ctxt->nums.len); - aptr = BC_NUM(ctxt, a); - bptr = BC_NUM(ctxt, b); + aptr = BCL_NUM(ctxt, a); + bptr = BCL_NUM(ctxt, b); assert(aptr != NULL && bptr != NULL); - assert(aptr->num != NULL && bptr->num != NULL); + assert(BCL_NUM_NUM(aptr) != NULL && BCL_NUM_NUM(bptr)); - return bc_num_cmp(aptr, bptr); + return bc_num_cmp(BCL_NUM_NUM(aptr), BCL_NUM_NUM(bptr)); } void bcl_zero(BclNumber n) { - BcNum* nptr; + BclNum* nptr; BclContext ctxt; BcVm* vm = bcl_getspecific(); BC_CHECK_CTXT_ASSERT(vm, ctxt); - assert(n.i < ctxt->nums.len); + BCL_CHECK_NUM_VALID(ctxt, n); - nptr = BC_NUM(ctxt, n); + assert(BCL_NO_GEN(n) < ctxt->nums.len); - assert(nptr != NULL && nptr->num != NULL); + nptr = BCL_NUM(ctxt, n); - bc_num_zero(nptr); + assert(nptr != NULL && BCL_NUM_NUM(nptr) != NULL); + + bc_num_zero(BCL_NUM_NUM(nptr)); } void bcl_one(BclNumber n) { - BcNum* nptr; + BclNum* nptr; BclContext ctxt; BcVm* vm = bcl_getspecific(); BC_CHECK_CTXT_ASSERT(vm, ctxt); - assert(n.i < ctxt->nums.len); + BCL_CHECK_NUM_VALID(ctxt, n); + + assert(BCL_NO_GEN(n) < ctxt->nums.len); - nptr = BC_NUM(ctxt, n); + nptr = BCL_NUM(ctxt, n); - assert(nptr != NULL && nptr->num != NULL); + assert(nptr != NULL && BCL_NUM_NUM(nptr) != NULL); - bc_num_one(nptr); + bc_num_one(BCL_NUM_NUM(nptr)); } BclNumber bcl_parse(const char* restrict val) { BclError e = BCL_ERROR_NONE; - BcNum n; + BclNum n; BclNumber idx; BclContext ctxt; BcVm* vm = bcl_getspecific(); bool neg; BC_CHECK_CTXT(vm, ctxt); BC_FUNC_HEADER(vm, err); - bc_vec_grow(&ctxt->nums, 1); + BCL_GROW_NUMS(ctxt); assert(val != NULL); // We have to take care of negative here because bc's number parsing does // not. neg = (val[0] == '-'); if (neg) val += 1; if (!bc_num_strValid(val)) { vm->err = BCL_ERROR_PARSE_INVALID_STR; goto err; } // Clear and initialize the number. - bc_num_clear(&n); - bc_num_init(&n, BC_NUM_DEF_SIZE); + bc_num_clear(BCL_NUM_NUM_NP(n)); + bc_num_init(BCL_NUM_NUM_NP(n), BC_NUM_DEF_SIZE); - bc_num_parse(&n, val, (BcBigDig) ctxt->ibase); + bc_num_parse(BCL_NUM_NUM_NP(n), val, (BcBigDig) ctxt->ibase); // Set the negative. +#if BC_ENABLE_MEMCHECK + n.n.rdx = BC_NUM_NEG_VAL(BCL_NUM_NUM_NP(n), neg); +#else // BC_ENABLE_MEMCHECK n.rdx = BC_NUM_NEG_VAL_NP(n, neg); +#endif // BC_ENABLE_MEMCHECK err: + BC_FUNC_FOOTER(vm, e); BC_MAYBE_SETUP(ctxt, e, n, idx); return idx; } -char* -bcl_string(BclNumber n) +static char* +bcl_string_helper(BclNumber n, bool destruct) { - BcNum* nptr; + BclNum* nptr; char* str = NULL; BclContext ctxt; BcVm* vm = bcl_getspecific(); BC_CHECK_CTXT_ASSERT(vm, ctxt); - if (BC_ERR(n.i >= ctxt->nums.len)) return str; + BCL_CHECK_NUM_VALID(ctxt, n); + + if (BC_ERR(BCL_NO_GEN(n) >= ctxt->nums.len)) return str; BC_FUNC_HEADER(vm, err); - assert(n.i < ctxt->nums.len); + assert(BCL_NO_GEN(n) < ctxt->nums.len); - nptr = BC_NUM(ctxt, n); + nptr = BCL_NUM(ctxt, n); - assert(nptr != NULL && nptr->num != NULL); + assert(nptr != NULL && BCL_NUM_NUM(nptr) != NULL); // Clear the buffer. bc_vec_popAll(&vm->out); // Print to the buffer. - bc_num_print(nptr, (BcBigDig) ctxt->obase, false); + bc_num_print(BCL_NUM_NUM(nptr), (BcBigDig) ctxt->obase, false); bc_vec_pushByte(&vm->out, '\0'); // Just dup the string; the caller is responsible for it. str = bc_vm_strdup(vm->out.v); err: - // Eat the operand. - bcl_num_dtor(ctxt, n, nptr); + if (destruct) + { + // Eat the operand. + bcl_num_dtor(ctxt, n, nptr); + } BC_FUNC_FOOTER_NO_ERR(vm); return str; } -BclNumber -bcl_irand(BclNumber a) +char* +bcl_string(BclNumber n) +{ + return bcl_string_helper(n, true); +} + +char* +bcl_string_keep(BclNumber n) +{ + return bcl_string_helper(n, false); +} + +#if BC_ENABLE_EXTRA_MATH + +static BclNumber +bcl_irand_helper(BclNumber a, bool destruct) { BclError e = BCL_ERROR_NONE; - BcNum* aptr; - BcNum b; + BclNum* aptr; + BclNum b; BclNumber idx; BclContext ctxt; BcVm* vm = bcl_getspecific(); BC_CHECK_CTXT(vm, ctxt); BC_CHECK_NUM(ctxt, a); BC_FUNC_HEADER(vm, err); - bc_vec_grow(&ctxt->nums, 1); + BCL_GROW_NUMS(ctxt); - assert(a.i < ctxt->nums.len); + assert(BCL_NO_GEN(a) < ctxt->nums.len); - aptr = BC_NUM(ctxt, a); + aptr = BCL_NUM(ctxt, a); - assert(aptr != NULL && aptr->num != NULL); + assert(aptr != NULL && BCL_NUM_NUM(aptr) != NULL); // Clear and initialize the result. - bc_num_clear(&b); - bc_num_init(&b, BC_NUM_DEF_SIZE); + bc_num_clear(BCL_NUM_NUM_NP(b)); + bc_num_init(BCL_NUM_NUM_NP(b), BC_NUM_DEF_SIZE); - bc_num_irand(aptr, &b, &vm->rng); + bc_num_irand(BCL_NUM_NUM(aptr), BCL_NUM_NUM_NP(b), &vm->rng); err: - // Eat the operand. - bcl_num_dtor(ctxt, a, aptr); + if (destruct) + { + // Eat the operand. + bcl_num_dtor(ctxt, a, aptr); + } BC_FUNC_FOOTER(vm, e); BC_MAYBE_SETUP(ctxt, e, b, idx); return idx; } +BclNumber +bcl_irand(BclNumber a) +{ + return bcl_irand_helper(a, true); +} + +BclNumber +bcl_irand_keep(BclNumber a) +{ + return bcl_irand_helper(a, false); +} + /** * Helps bcl_frand(). This is separate because the error handling is easier that * way. It is also easier to do ifrand that way. * @param b The return parameter. * @param places The number of decimal places to generate. */ static void bcl_frandHelper(BcNum* restrict b, size_t places) { BcNum exp, pow, ten; BcDig exp_digs[BC_NUM_BIGDIG_LOG10]; BcDig ten_digs[BC_NUM_BIGDIG_LOG10]; BcVm* vm = bcl_getspecific(); // Set up temporaries. bc_num_setup(&exp, exp_digs, BC_NUM_BIGDIG_LOG10); bc_num_setup(&ten, ten_digs, BC_NUM_BIGDIG_LOG10); ten.num[0] = 10; ten.len = 1; bc_num_bigdig2num(&exp, (BcBigDig) places); // Clear the temporary that might need to grow. bc_num_clear(&pow); // Initialize the temporary that might need to grow. bc_num_init(&pow, bc_num_powReq(&ten, &exp, 0)); BC_SETJMP(vm, err); // Generate the number. bc_num_pow(&ten, &exp, &pow, 0); bc_num_irand(&pow, b, &vm->rng); // Make the number entirely fraction. bc_num_shiftRight(b, places); err: + bc_num_free(&pow); BC_LONGJMP_CONT(vm); } BclNumber bcl_frand(size_t places) { BclError e = BCL_ERROR_NONE; - BcNum n; + BclNum n; BclNumber idx; BclContext ctxt; BcVm* vm = bcl_getspecific(); BC_CHECK_CTXT(vm, ctxt); BC_FUNC_HEADER(vm, err); - bc_vec_grow(&ctxt->nums, 1); + BCL_GROW_NUMS(ctxt); // Clear and initialize the number. - bc_num_clear(&n); - bc_num_init(&n, BC_NUM_DEF_SIZE); + bc_num_clear(BCL_NUM_NUM_NP(n)); + bc_num_init(BCL_NUM_NUM_NP(n), BC_NUM_DEF_SIZE); - bcl_frandHelper(&n, places); + bcl_frandHelper(BCL_NUM_NUM_NP(n), places); err: BC_FUNC_FOOTER(vm, e); BC_MAYBE_SETUP(ctxt, e, n, idx); return idx; } /** * Helps bc_ifrand(). This is separate because error handling is easier that * way. * @param a The limit for bc_num_irand(). * @param b The return parameter. * @param places The number of decimal places to generate. */ static void bcl_ifrandHelper(BcNum* restrict a, BcNum* restrict b, size_t places) { BcNum ir, fr; BcVm* vm = bcl_getspecific(); // Clear the integer and fractional numbers. bc_num_clear(&ir); bc_num_clear(&fr); // Initialize the integer and fractional numbers. bc_num_init(&ir, BC_NUM_DEF_SIZE); bc_num_init(&fr, BC_NUM_DEF_SIZE); BC_SETJMP(vm, err); bc_num_irand(a, &ir, &vm->rng); bcl_frandHelper(&fr, places); bc_num_add(&ir, &fr, b, 0); err: + bc_num_free(&fr); bc_num_free(&ir); BC_LONGJMP_CONT(vm); } -BclNumber -bcl_ifrand(BclNumber a, size_t places) +static BclNumber +bcl_ifrand_helper(BclNumber a, size_t places, bool destruct) { BclError e = BCL_ERROR_NONE; - BcNum* aptr; - BcNum b; + BclNum* aptr; + BclNum b; BclNumber idx; BclContext ctxt; BcVm* vm = bcl_getspecific(); BC_CHECK_CTXT(vm, ctxt); BC_CHECK_NUM(ctxt, a); BC_FUNC_HEADER(vm, err); - bc_vec_grow(&ctxt->nums, 1); + BCL_GROW_NUMS(ctxt); - assert(a.i < ctxt->nums.len); + assert(BCL_NO_GEN(a) < ctxt->nums.len); - aptr = BC_NUM(ctxt, a); + aptr = BCL_NUM(ctxt, a); - assert(aptr != NULL && aptr->num != NULL); + assert(aptr != NULL && BCL_NUM_NUM(aptr) != NULL); // Clear and initialize the number. - bc_num_clear(&b); - bc_num_init(&b, BC_NUM_DEF_SIZE); + bc_num_clear(BCL_NUM_NUM_NP(b)); + bc_num_init(BCL_NUM_NUM_NP(b), BC_NUM_DEF_SIZE); - bcl_ifrandHelper(aptr, &b, places); + bcl_ifrandHelper(BCL_NUM_NUM(aptr), BCL_NUM_NUM_NP(b), places); err: - // Eat the oprand. - bcl_num_dtor(ctxt, a, aptr); + if (destruct) + { + // Eat the oprand. + bcl_num_dtor(ctxt, a, aptr); + } BC_FUNC_FOOTER(vm, e); BC_MAYBE_SETUP(ctxt, e, b, idx); return idx; } -BclError -bcl_rand_seedWithNum(BclNumber n) +BclNumber +bcl_ifrand(BclNumber a, size_t places) +{ + return bcl_ifrand_helper(a, places, true); +} + +BclNumber +bcl_ifrand_keep(BclNumber a, size_t places) +{ + return bcl_ifrand_helper(a, places, false); +} + +static BclError +bcl_rand_seedWithNum_helper(BclNumber n, bool destruct) { BclError e = BCL_ERROR_NONE; - BcNum* nptr; + BclNum* nptr; BclContext ctxt; BcVm* vm = bcl_getspecific(); BC_CHECK_CTXT_ERR(vm, ctxt); BC_CHECK_NUM_ERR(ctxt, n); BC_FUNC_HEADER(vm, err); - assert(n.i < ctxt->nums.len); + assert(BCL_NO_GEN(n) < ctxt->nums.len); - nptr = BC_NUM(ctxt, n); + nptr = BCL_NUM(ctxt, n); - assert(nptr != NULL && nptr->num != NULL); + assert(nptr != NULL && BCL_NUM_NUM(nptr) != NULL); - bc_num_rng(nptr, &vm->rng); + bc_num_rng(BCL_NUM_NUM(nptr), &vm->rng); err: + + if (destruct) + { + // Eat the oprand. + bcl_num_dtor(ctxt, n, nptr); + } + BC_FUNC_FOOTER(vm, e); + return e; } +BclError +bcl_rand_seedWithNum(BclNumber n) +{ + return bcl_rand_seedWithNum_helper(n, true); +} + +BclError +bcl_rand_seedWithNum_keep(BclNumber n) +{ + return bcl_rand_seedWithNum_helper(n, false); +} + BclError bcl_rand_seed(unsigned char seed[BCL_SEED_SIZE]) { BclError e = BCL_ERROR_NONE; size_t i; ulong vals[BCL_SEED_ULONGS]; BcVm* vm = bcl_getspecific(); BC_FUNC_HEADER(vm, err); // Fill the array. for (i = 0; i < BCL_SEED_SIZE; ++i) { ulong val = ((ulong) seed[i]) << (((ulong) CHAR_BIT) * (i % sizeof(ulong))); vals[i / sizeof(long)] |= val; } bc_rand_seed(&vm->rng, vals[0], vals[1], vals[2], vals[3]); err: + BC_FUNC_FOOTER(vm, e); + return e; } void bcl_rand_reseed(void) { BcVm* vm = bcl_getspecific(); bc_rand_srand(bc_vec_top(&vm->rng.v)); } BclNumber bcl_rand_seed2num(void) { BclError e = BCL_ERROR_NONE; - BcNum n; + BclNum n; BclNumber idx; BclContext ctxt; BcVm* vm = bcl_getspecific(); BC_CHECK_CTXT(vm, ctxt); BC_FUNC_HEADER(vm, err); // Clear and initialize the number. - bc_num_clear(&n); - bc_num_init(&n, BC_NUM_DEF_SIZE); + bc_num_clear(BCL_NUM_NUM_NP(n)); + bc_num_init(BCL_NUM_NUM_NP(n), BC_NUM_DEF_SIZE); - bc_num_createFromRNG(&n, &vm->rng); + bc_num_createFromRNG(BCL_NUM_NUM_NP(n), &vm->rng); err: + BC_FUNC_FOOTER(vm, e); BC_MAYBE_SETUP(ctxt, e, n, idx); return idx; } BclRandInt bcl_rand_int(void) { BcVm* vm = bcl_getspecific(); return (BclRandInt) bc_rand_int(&vm->rng); } BclRandInt bcl_rand_bounded(BclRandInt bound) { BcVm* vm = bcl_getspecific(); if (bound <= 1) return 0; return (BclRandInt) bc_rand_bounded(&vm->rng, (BcRand) bound); } +#endif // BC_ENABLE_EXTRA_MATH + #endif // BC_ENABLE_LIBRARY diff --git a/contrib/bc/src/program.c b/contrib/bc/src/program.c index b6fac12c7d65..243f827fe98c 100644 --- a/contrib/bc/src/program.c +++ b/contrib/bc/src/program.c @@ -1,3828 +1,3835 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2023 Gavin D. Howard and contributors. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * ***************************************************************************** * * Code to execute bc programs. * */ #include #include #include #include #include #include #include #include #include #include /** * Does a type check for something that expects a number. * @param r The result that will be checked. * @param n The result's number. */ static inline void bc_program_type_num(BcResult* r, BcNum* n) { #if BC_ENABLED // This should have already been taken care of. assert(r->t != BC_RESULT_VOID); #endif // BC_ENABLED if (BC_ERR(!BC_PROG_NUM(r, n))) bc_err(BC_ERR_EXEC_TYPE); } #if BC_ENABLED /** * Does a type check. * @param r The result to check. * @param t The type that the result should be. */ static void bc_program_type_match(BcResult* r, BcType t) { if (BC_ERR((r->t != BC_RESULT_ARRAY) != (!t))) bc_err(BC_ERR_EXEC_TYPE); } #endif // BC_ENABLED /** * Pulls an index out of a bytecode vector and updates the index into the vector * to point to the spot after the index. For more details on bytecode indices, * see the development manual (manuals/development.md#bytecode-indices). * @param code The bytecode vector. * @param bgn An in/out parameter; the index into the vector that will be * updated. * @return The index at @a bgn in the bytecode vector. */ static size_t bc_program_index(const char* restrict code, size_t* restrict bgn) { uchar amt = (uchar) code[(*bgn)++], i = 0; size_t res = 0; for (; i < amt; ++i, ++(*bgn)) { size_t temp = ((size_t) ((int) (uchar) code[*bgn]) & UCHAR_MAX); res |= (temp << (i * CHAR_BIT)); } return res; } /** * Returns a string from a result and its number. * @param p The program. * @param n The number tied to the result. * @return The string corresponding to the result and number. */ static inline char* bc_program_string(BcProgram* p, const BcNum* n) { return *((char**) bc_vec_item(&p->strs, n->scale)); } #if BC_ENABLED /** * Prepares the globals for a function call. This is only called when global * stacks are on because it pushes a copy of the current globals onto each of * their respective stacks. * @param p The program. */ static void bc_program_prepGlobals(BcProgram* p) { size_t i; for (i = 0; i < BC_PROG_GLOBALS_LEN; ++i) { bc_vec_push(p->globals_v + i, p->globals + i); } #if BC_ENABLE_EXTRA_MATH bc_rand_push(&p->rng); #endif // BC_ENABLE_EXTRA_MATH } /** * Pops globals stacks on returning from a function, or in the case of reset, * pops all but one item on each global stack. * @param p The program. * @param reset True if all but one item on each stack should be popped, false * otherwise. */ static void bc_program_popGlobals(BcProgram* p, bool reset) { size_t i; BC_SIG_ASSERT_LOCKED; for (i = 0; i < BC_PROG_GLOBALS_LEN; ++i) { BcVec* v = p->globals_v + i; bc_vec_npop(v, reset ? v->len - 1 : 1); p->globals[i] = BC_PROG_GLOBAL(v); } #if BC_ENABLE_EXTRA_MATH bc_rand_pop(&p->rng, reset); #endif // BC_ENABLE_EXTRA_MATH } /** * Derefeneces an array reference and returns a pointer to the real array. * @param p The program. * @param vec The reference vector. * @return A pointer to the desired array. */ static BcVec* bc_program_dereference(const BcProgram* p, BcVec* vec) { BcVec* v; size_t vidx, nidx, i = 0; // We want to be sure we have a reference vector. assert(vec->size == sizeof(uchar)); // Get the index of the vector in arrs, then the index of the original // referenced vector. vidx = bc_program_index(vec->v, &i); nidx = bc_program_index(vec->v, &i); v = bc_vec_item(bc_vec_item(&p->arrs, vidx), nidx); // We want to be sure we do *not* have a reference vector. assert(v->size != sizeof(uchar)); return v; } #endif // BC_ENABLED /** * Creates a BcNum from a BcBigDig and pushes onto the results stack. This is a * convenience function. * @param p The program. * @param dig The BcBigDig to push onto the results stack. * @param type The type that the pushed result should be. */ static void bc_program_pushBigdig(BcProgram* p, BcBigDig dig, BcResultType type) { BcResult res; res.t = type; BC_SIG_LOCK; bc_num_createFromBigdig(&res.d.n, dig); bc_vec_push(&p->results, &res); BC_SIG_UNLOCK; } size_t bc_program_addString(BcProgram* p, const char* str) { size_t idx; BC_SIG_ASSERT_LOCKED; if (bc_map_insert(&p->str_map, str, p->strs.len, &idx)) { char** str_ptr; BcId* id = bc_vec_item(&p->str_map, idx); // Get the index. idx = id->idx; // Push an empty string on the proper vector. str_ptr = bc_vec_pushEmpty(&p->strs); // We reuse the string in the ID (allocated by bc_map_insert()), because // why not? *str_ptr = id->name; } else { BcId* id = bc_vec_item(&p->str_map, idx); idx = id->idx; } return idx; } size_t bc_program_search(BcProgram* p, const char* name, bool var) { BcVec* v; BcVec* map; size_t i; BC_SIG_ASSERT_LOCKED; // Grab the right vector and map. v = var ? &p->vars : &p->arrs; map = var ? &p->var_map : &p->arr_map; // We do an insert because the variable might not exist yet. This is because // the parser calls this function. If the insert succeeds, we create a stack // for the variable/array. But regardless, bc_map_insert() gives us the // index of the item in i. if (bc_map_insert(map, name, v->len, &i)) { BcVec* temp = bc_vec_pushEmpty(v); bc_array_init(temp, var); } return ((BcId*) bc_vec_item(map, i))->idx; } /** * Returns the correct variable or array stack for the type. * @param p The program. * @param idx The index of the variable or array in the variable or array * vector. * @param type The type of vector to return. * @return A pointer to the variable or array stack. */ static inline BcVec* bc_program_vec(const BcProgram* p, size_t idx, BcType type) { const BcVec* v = (type == BC_TYPE_VAR) ? &p->vars : &p->arrs; return bc_vec_item(v, idx); } /** * Returns a pointer to the BcNum corresponding to the result. There is one * case, however, where this returns a pointer to a BcVec: if the type of the * result is array. In that case, the pointer is casted to a pointer to BcNum, * but is never used. The function that calls this expecting an array casts the * pointer back. This function is called a lot and needs to be as fast as * possible. * @param p The program. * @param r The result whose number will be returned. * @return The BcNum corresponding to the result. */ static BcNum* bc_program_num(BcProgram* p, BcResult* r) { BcNum* n; #ifdef _WIN32 // Windows made it an error to not initialize this, so shut it up. // I don't want to do this on other platforms because this procedure // is one of the most heavily-used, and eliminating the initialization // is a performance win. n = NULL; #endif // _WIN32 switch (r->t) { case BC_RESULT_STR: case BC_RESULT_TEMP: case BC_RESULT_IBASE: case BC_RESULT_SCALE: case BC_RESULT_OBASE: #if BC_ENABLE_EXTRA_MATH case BC_RESULT_SEED: #endif // BC_ENABLE_EXTRA_MATH { n = &r->d.n; break; } case BC_RESULT_VAR: case BC_RESULT_ARRAY: case BC_RESULT_ARRAY_ELEM: { BcVec* v; BcType type = (r->t == BC_RESULT_VAR) ? BC_TYPE_VAR : BC_TYPE_ARRAY; // Get the correct variable or array vector. v = bc_program_vec(p, r->d.loc.loc, type); // Surprisingly enough, the hard case is *not* returning an array; // it's returning an array element. This is because we have to dig // deeper to get *to* the element. That's what the code inside this // if statement does. if (r->t == BC_RESULT_ARRAY_ELEM) { size_t idx = r->d.loc.idx; v = bc_vec_item(v, r->d.loc.stack_idx); #if BC_ENABLED // If this is true, we have a reference vector, so dereference // it. The reason we don't need to worry about it for returning // a straight array is because we only care about references // when we access elements of an array that is a reference. That // is this code, so in essence, this line takes care of arrays // as well. if (v->size == sizeof(uchar)) v = bc_program_dereference(p, v); #endif // BC_ENABLED // We want to be sure we got a valid array of numbers. assert(v->size == sizeof(BcNum)); // The bc spec says that if an element is accessed that does not // exist, it should be preinitialized to 0. Well, if we access // an element *way* out there, we have to preinitialize all // elements between the current last element and the actual // accessed element. if (v->len <= idx) { BC_SIG_LOCK; bc_array_expand(v, bc_vm_growSize(idx, 1)); BC_SIG_UNLOCK; } n = bc_vec_item(v, idx); } // This is either a number (for a var) or an array (for an array). // Because bc_vec_top() and bc_vec_item() return a void*, we don't // need to cast. else { #if BC_ENABLED if (BC_IS_BC) { n = bc_vec_item(v, r->d.loc.stack_idx); } else #endif // BC_ENABLED { n = bc_vec_top(v); } } break; } case BC_RESULT_ZERO: { n = &vm->zero; break; } case BC_RESULT_ONE: { n = &vm->one; break; } #if BC_ENABLED // We should never get here; this is taken care of earlier because a // result is expected. case BC_RESULT_VOID: #if BC_DEBUG { abort(); // Fallthrough } #endif // BC_DEBUG case BC_RESULT_LAST: { n = &p->last; break; } #endif // BC_ENABLED #if BC_GCC // This is here in GCC to quiet the "maybe-uninitialized" warning. default: { abort(); } #endif // BC_GCC } return n; } /** * Prepares an operand for use. * @param p The program. * @param r An out parameter; this is set to the pointer to the result that * we care about. * @param n An out parameter; this is set to the pointer to the number that * we care about. * @param idx The index of the result from the top of the results stack. */ static void bc_program_operand(BcProgram* p, BcResult** r, BcNum** n, size_t idx) { *r = bc_vec_item_rev(&p->results, idx); #if BC_ENABLED if (BC_ERR((*r)->t == BC_RESULT_VOID)) bc_err(BC_ERR_EXEC_VOID_VAL); #endif // BC_ENABLED *n = bc_program_num(p, *r); } /** * Prepares the operands of a binary operator. * @param p The program. * @param l An out parameter; this is set to the pointer to the result for * the left operand. * @param ln An out parameter; this is set to the pointer to the number for * the left operand. * @param r An out parameter; this is set to the pointer to the result for * the right operand. * @param rn An out parameter; this is set to the pointer to the number for * the right operand. * @param idx The starting index where the operands are in the results stack, * starting from the top. */ static void bc_program_binPrep(BcProgram* p, BcResult** l, BcNum** ln, BcResult** r, BcNum** rn, size_t idx) { BcResultType lt; assert(p != NULL && l != NULL && ln != NULL && r != NULL && rn != NULL); #ifndef BC_PROG_NO_STACK_CHECK // Check the stack for dc. if (BC_IS_DC) { if (BC_ERR(!BC_PROG_STACK(&p->results, idx + 2))) { bc_err(BC_ERR_EXEC_STACK); } } #endif // BC_PROG_NO_STACK_CHECK assert(BC_PROG_STACK(&p->results, idx + 2)); // Get the operands. bc_program_operand(p, l, ln, idx + 1); bc_program_operand(p, r, rn, idx); lt = (*l)->t; #if BC_ENABLED // bc_program_operand() checked these for us. assert(lt != BC_RESULT_VOID && (*r)->t != BC_RESULT_VOID); #endif // BC_ENABLED // We run this again under these conditions in case any vector has been // reallocated out from under the BcNums or arrays we had. In other words, // this is to fix pointer invalidation. if (lt == (*r)->t && (lt == BC_RESULT_VAR || lt == BC_RESULT_ARRAY_ELEM)) { *ln = bc_program_num(p, *l); } if (BC_ERR(lt == BC_RESULT_STR)) bc_err(BC_ERR_EXEC_TYPE); } /** * Prepares the operands of a binary operator and type checks them. This is * separate from bc_program_binPrep() because some places want this, others want * bc_program_binPrep(). * @param p The program. * @param l An out parameter; this is set to the pointer to the result for * the left operand. * @param ln An out parameter; this is set to the pointer to the number for * the left operand. * @param r An out parameter; this is set to the pointer to the result for * the right operand. * @param rn An out parameter; this is set to the pointer to the number for * the right operand. * @param idx The starting index where the operands are in the results stack, * starting from the top. */ static void bc_program_binOpPrep(BcProgram* p, BcResult** l, BcNum** ln, BcResult** r, BcNum** rn, size_t idx) { bc_program_binPrep(p, l, ln, r, rn, idx); bc_program_type_num(*l, *ln); bc_program_type_num(*r, *rn); } /** * Prepares the operands of an assignment operator. * @param p The program. * @param l An out parameter; this is set to the pointer to the result for the * left operand. * @param ln An out parameter; this is set to the pointer to the number for the * left operand. * @param r An out parameter; this is set to the pointer to the result for the * right operand. * @param rn An out parameter; this is set to the pointer to the number for the * right operand. */ static void bc_program_assignPrep(BcProgram* p, BcResult** l, BcNum** ln, BcResult** r, BcNum** rn) { BcResultType lt, min; bool good; // This is the min non-allowable result type. dc allows strings. min = BC_RESULT_TEMP - ((unsigned int) (BC_IS_BC)); // Prepare the operands. bc_program_binPrep(p, l, ln, r, rn, 0); lt = (*l)->t; // Typecheck the left. if (BC_ERR(lt >= min && lt <= BC_RESULT_ONE)) bc_err(BC_ERR_EXEC_TYPE); // Strings can be assigned to variables. We are already good if we are // assigning a string. good = ((*r)->t == BC_RESULT_STR && lt <= BC_RESULT_ARRAY_ELEM); assert(BC_PROG_STR(*rn) || (*r)->t != BC_RESULT_STR); // If not, type check for a number. if (!good) bc_program_type_num(*r, *rn); } /** * Prepares a single operand and type checks it. This is separate from * bc_program_operand() because different places want one or the other. * @param p The program. * @param r An out parameter; this is set to the pointer to the result that * we care about. * @param n An out parameter; this is set to the pointer to the number that * we care about. * @param idx The index of the result from the top of the results stack. */ static void bc_program_prep(BcProgram* p, BcResult** r, BcNum** n, size_t idx) { assert(p != NULL && r != NULL && n != NULL); #ifndef BC_PROG_NO_STACK_CHECK // Check the stack for dc. if (BC_IS_DC) { if (BC_ERR(!BC_PROG_STACK(&p->results, idx + 1))) { bc_err(BC_ERR_EXEC_STACK); } } #endif // BC_PROG_NO_STACK_CHECK assert(BC_PROG_STACK(&p->results, idx + 1)); bc_program_operand(p, r, n, idx); // dc does not allow strings in this case. bc_program_type_num(*r, *n); } /** * Prepares and returns a clean result for the result of an operation. * @param p The program. * @return A clean result. */ static BcResult* bc_program_prepResult(BcProgram* p) { BcResult* res = bc_vec_pushEmpty(&p->results); bc_result_clear(res); return res; } /** * Prepares a constant for use. This parses the constant into a number and then * pushes that number onto the results stack. * @param p The program. * @param code The bytecode vector that we will pull the index of the constant * from. * @param bgn An in/out parameter; marks the start of the index in the * bytecode vector and will be updated to point to after the index. */ static void bc_program_const(BcProgram* p, const char* code, size_t* bgn) { // I lied. I actually push the result first. I can do this because the // result will be popped on error. I also get the constant itself. BcResult* r = bc_program_prepResult(p); BcConst* c = bc_vec_item(&p->consts, bc_program_index(code, bgn)); BcBigDig base = BC_PROG_IBASE(p); // Only reparse if the base changed. if (c->base != base) { // Allocate if we haven't yet. if (c->num.num == NULL) { // The plus 1 is in case of overflow with lack of clamping. size_t len = strlen(c->val) + (BC_DIGIT_CLAMP == 0); BC_SIG_LOCK; bc_num_init(&c->num, BC_NUM_RDX(len)); BC_SIG_UNLOCK; } // We need to zero an already existing number. else bc_num_zero(&c->num); // bc_num_parse() should only do operations that cannot fail. bc_num_parse(&c->num, c->val, base); c->base = base; } BC_SIG_LOCK; bc_num_createCopy(&r->d.n, &c->num); BC_SIG_UNLOCK; } /** * Executes a binary operator operation. * @param p The program. * @param inst The instruction corresponding to the binary operator to execute. */ static void bc_program_op(BcProgram* p, uchar inst) { BcResult* opd1; BcResult* opd2; BcResult* res; BcNum* n1; BcNum* n2; size_t idx = inst - BC_INST_POWER; res = bc_program_prepResult(p); bc_program_binOpPrep(p, &opd1, &n1, &opd2, &n2, 1); BC_SIG_LOCK; // Initialize the number with enough space, using the correct // BcNumBinaryOpReq function. This looks weird because it is executing an // item of an array. Rest assured that item is a function. bc_num_init(&res->d.n, bc_program_opReqs[idx](n1, n2, BC_PROG_SCALE(p))); BC_SIG_UNLOCK; assert(BC_NUM_RDX_VALID(n1)); assert(BC_NUM_RDX_VALID(n2)); // Run the operation. This also executes an item of an array. bc_program_ops[idx](n1, n2, &res->d.n, BC_PROG_SCALE(p)); bc_program_retire(p, 1, 2); } /** * Executes a read() or ? command. * @param p The program. */ static void bc_program_read(BcProgram* p) { BcStatus s; BcInstPtr ip; size_t i; const char* file; BcMode mode; BcFunc* f = bc_vec_item(&p->fns, BC_PROG_READ); // If we are already executing a read, that is an error. So look for a read // and barf. for (i = 0; i < p->stack.len; ++i) { BcInstPtr* ip_ptr = bc_vec_item(&p->stack, i); if (ip_ptr->func == BC_PROG_READ) bc_err(BC_ERR_EXEC_REC_READ); } BC_SIG_LOCK; // Save the filename because we are going to overwrite it. file = vm->file; mode = vm->mode; // It is a parse error if there needs to be more than one line, so we unset // this to tell the lexer to not request more. We set it back later. vm->mode = BC_MODE_FILE; if (!BC_PARSE_IS_INITED(&vm->read_prs, p)) { // We need to parse, but we don't want to use the existing parser // because it has state it needs to keep. (It could have a partial parse // state.) So we create a new parser. This parser is in the BcVm struct // so that it is not local, which means that a longjmp() could change // it. bc_parse_init(&vm->read_prs, p, BC_PROG_READ); // We need a separate input buffer; that's why it is also in the BcVm // struct. bc_vec_init(&vm->read_buf, sizeof(char), BC_DTOR_NONE); } - // This needs to be updated because the parser could have been used - // somewhere else - else bc_parse_updateFunc(&vm->read_prs, BC_PROG_READ); + else + { + // This needs to be updated because the parser could have been used + // somewhere else. + bc_parse_updateFunc(&vm->read_prs, BC_PROG_READ); + + // The read buffer also needs to be emptied or else it will still + // contain previous read expressions. + bc_vec_empty(&vm->read_buf); + } BC_SETJMP_LOCKED(vm, exec_err); BC_SIG_UNLOCK; // Set up the lexer and the read function. bc_lex_file(&vm->read_prs.l, bc_program_stdin_name); bc_vec_popAll(&f->code); // Read a line. if (!BC_R) s = bc_read_line(&vm->read_buf, ""); else s = bc_read_line(&vm->read_buf, BC_VM_READ_PROMPT); // We should *not* have run into EOF. if (s == BC_STATUS_EOF) bc_err(BC_ERR_EXEC_READ_EXPR); // Parse *one* expression, so mode should not be stdin. bc_parse_text(&vm->read_prs, vm->read_buf.v, BC_MODE_FILE); BC_SIG_LOCK; vm->expr(&vm->read_prs, BC_PARSE_NOREAD | BC_PARSE_NEEDVAL); BC_SIG_UNLOCK; // We *must* have a valid expression. A semicolon cannot end an expression, // although EOF can. if (BC_ERR(vm->read_prs.l.t != BC_LEX_NLINE && vm->read_prs.l.t != BC_LEX_EOF)) { bc_err(BC_ERR_EXEC_READ_EXPR); } #if BC_ENABLED // Push on the globals stack if necessary. if (BC_G) bc_program_prepGlobals(p); #endif // BC_ENABLED // Set up a new BcInstPtr. ip.func = BC_PROG_READ; ip.idx = 0; ip.len = p->results.len; // Update this pointer, just in case. f = bc_vec_item(&p->fns, BC_PROG_READ); // We want a return instruction to simplify things. bc_vec_pushByte(&f->code, vm->read_ret); // This lock is here to make sure dc's tail calls are the same length. BC_SIG_LOCK; bc_vec_push(&p->stack, &ip); #if DC_ENABLED // We need a new tail call entry for dc. if (BC_IS_DC) { size_t temp = 0; bc_vec_push(&p->tail_calls, &temp); } #endif // DC_ENABLED exec_err: BC_SIG_MAYLOCK; vm->mode = (uchar) mode; vm->file = file; BC_LONGJMP_CONT(vm); } #if BC_ENABLE_EXTRA_MATH /** * Execute a rand(). * @param p The program. */ static void bc_program_rand(BcProgram* p) { BcRand rand = bc_rand_int(&p->rng); bc_program_pushBigdig(p, (BcBigDig) rand, BC_RESULT_TEMP); #if BC_DEBUG // This is just to ensure that the generated number is correct. I also use // braces because I declare every local at the top of the scope. { BcResult* r = bc_vec_top(&p->results); assert(BC_NUM_RDX_VALID_NP(r->d.n)); } #endif // BC_DEBUG } #endif // BC_ENABLE_EXTRA_MATH /** * Prints a series of characters, without escapes. * @param str The string (series of characters). */ static void bc_program_printChars(const char* str) { const char* nl; size_t len = vm->nchars + strlen(str); sig_atomic_t lock; BC_SIG_TRYLOCK(lock); bc_file_puts(&vm->fout, bc_flush_save, str); // We need to update the number of characters, so we find the last newline // and set the characters accordingly. nl = strrchr(str, '\n'); if (nl != NULL) len = strlen(nl + 1); vm->nchars = len > UINT16_MAX ? UINT16_MAX : (uint16_t) len; BC_SIG_TRYUNLOCK(lock); } /** * Prints a string with escapes. * @param str The string. */ static void bc_program_printString(const char* restrict str) { size_t i, len = strlen(str); #if DC_ENABLED // This is to ensure a nul byte is printed for dc's stream operation. if (!len && BC_IS_DC) { bc_vm_putchar('\0', bc_flush_save); return; } #endif // DC_ENABLED // Loop over the characters, processing escapes and printing the rest. for (i = 0; i < len; ++i) { int c = str[i]; // If we have an escape... if (c == '\\' && i != len - 1) { const char* ptr; // Get the escape character and its companion. c = str[++i]; ptr = strchr(bc_program_esc_chars, c); // If we have a companion character... if (ptr != NULL) { // We need to specially handle a newline. if (c == 'n') { BC_SIG_LOCK; vm->nchars = UINT16_MAX; BC_SIG_UNLOCK; } // Grab the actual character. c = bc_program_esc_seqs[(size_t) (ptr - bc_program_esc_chars)]; } else { // Just print the backslash if there is no companion character. // The following character will be printed later after the outer // if statement. bc_vm_putchar('\\', bc_flush_save); } } bc_vm_putchar(c, bc_flush_save); } } /** * Executes a print. This function handles all printing except streaming. * @param p The program. * @param inst The instruction for the type of print we are doing. * @param idx The index of the result that we are printing. */ static void bc_program_print(BcProgram* p, uchar inst, size_t idx) { BcResult* r; char* str; BcNum* n; bool pop = (inst != BC_INST_PRINT); assert(p != NULL); #ifndef BC_PROG_NO_STACK_CHECK if (BC_IS_DC) { if (BC_ERR(!BC_PROG_STACK(&p->results, idx + 1))) { bc_err(BC_ERR_EXEC_STACK); } } #endif // BC_PROG_NO_STACK_CHECK assert(BC_PROG_STACK(&p->results, idx + 1)); r = bc_vec_item_rev(&p->results, idx); #if BC_ENABLED // If we have a void value, that's not necessarily an error. It is if pop is // true because that means that we are executing a print statement, but // attempting to do a print on a lone void value is allowed because that's // exactly how we want void values used. if (r->t == BC_RESULT_VOID) { if (BC_ERR(pop)) bc_err(BC_ERR_EXEC_VOID_VAL); bc_vec_pop(&p->results); return; } #endif // BC_ENABLED n = bc_program_num(p, r); // If we have a number... if (BC_PROG_NUM(r, n)) { #if BC_ENABLED assert(inst != BC_INST_PRINT_STR); #endif // BC_ENABLED // Print the number. bc_num_print(n, BC_PROG_OBASE(p), !pop); #if BC_ENABLED // Need to store the number in last. if (BC_IS_BC) bc_num_copy(&p->last, n); #endif // BC_ENABLED } else { // We want to flush any stuff in the stdout buffer first. bc_file_flush(&vm->fout, bc_flush_save); str = bc_program_string(p, n); #if BC_ENABLED if (inst == BC_INST_PRINT_STR) bc_program_printChars(str); else #endif // BC_ENABLED { bc_program_printString(str); // Need to print a newline only in this case. if (inst == BC_INST_PRINT) bc_vm_putchar('\n', bc_flush_err); } } // bc always pops. This macro makes sure that happens. if (BC_PROGRAM_POP(pop)) bc_vec_pop(&p->results); } void bc_program_negate(BcResult* r, BcNum* n) { bc_num_copy(&r->d.n, n); if (BC_NUM_NONZERO(&r->d.n)) BC_NUM_NEG_TGL_NP(r->d.n); } void bc_program_not(BcResult* r, BcNum* n) { if (!bc_num_cmpZero(n)) bc_num_one(&r->d.n); } #if BC_ENABLE_EXTRA_MATH void bc_program_trunc(BcResult* r, BcNum* n) { bc_num_copy(&r->d.n, n); bc_num_truncate(&r->d.n, n->scale); } #endif // BC_ENABLE_EXTRA_MATH /** * Runs a unary operation. * @param p The program. * @param inst The unary operation. */ static void bc_program_unary(BcProgram* p, uchar inst) { BcResult* res; BcResult* ptr; BcNum* num; res = bc_program_prepResult(p); bc_program_prep(p, &ptr, &num, 1); BC_SIG_LOCK; bc_num_init(&res->d.n, num->len); BC_SIG_UNLOCK; // This calls a function that is in an array. bc_program_unarys[inst - BC_INST_NEG](res, num); bc_program_retire(p, 1, 1); } /** * Executes a logical operator. * @param p The program. * @param inst The operator. */ static void bc_program_logical(BcProgram* p, uchar inst) { BcResult* opd1; BcResult* opd2; BcResult* res; BcNum* n1; BcNum* n2; bool cond = 0; ssize_t cmp; res = bc_program_prepResult(p); // All logical operators (except boolean not, which is taken care of by // bc_program_unary()), are binary operators. bc_program_binOpPrep(p, &opd1, &n1, &opd2, &n2, 1); // Boolean and and or are not short circuiting. This is why; they can be // implemented much easier this way. if (inst == BC_INST_BOOL_AND) { cond = (bc_num_cmpZero(n1) && bc_num_cmpZero(n2)); } else if (inst == BC_INST_BOOL_OR) { cond = (bc_num_cmpZero(n1) || bc_num_cmpZero(n2)); } else { // We have a relational operator, so do a comparison. cmp = bc_num_cmp(n1, n2); switch (inst) { case BC_INST_REL_EQ: { cond = (cmp == 0); break; } case BC_INST_REL_LE: { cond = (cmp <= 0); break; } case BC_INST_REL_GE: { cond = (cmp >= 0); break; } case BC_INST_REL_NE: { cond = (cmp != 0); break; } case BC_INST_REL_LT: { cond = (cmp < 0); break; } case BC_INST_REL_GT: { cond = (cmp > 0); break; } #if BC_DEBUG default: { // There is a bug if we get here. abort(); } #endif // BC_DEBUG } } BC_SIG_LOCK; bc_num_init(&res->d.n, BC_NUM_DEF_SIZE); BC_SIG_UNLOCK; if (cond) bc_num_one(&res->d.n); bc_program_retire(p, 1, 2); } /** * Assigns a string to a variable. * @param p The program. * @param num The location of the string as a BcNum. * @param v The stack for the variable. * @param push Whether to push the string or not. To push means to move the * string from the results stack and push it onto the variable * stack. */ static void bc_program_assignStr(BcProgram* p, BcNum* num, BcVec* v, bool push) { BcNum* n; assert(BC_PROG_STACK(&p->results, 1 + !push)); assert(num != NULL && num->num == NULL && num->cap == 0); // If we are not pushing onto the variable stack, we need to replace the // top of the variable stack. if (!push) bc_vec_pop(v); bc_vec_npop(&p->results, 1 + !push); n = bc_vec_pushEmpty(v); // We can just copy because the num should not have allocated anything. // NOLINTNEXTLINE memcpy(n, num, sizeof(BcNum)); } /** * Copies a value to a variable. This is used for storing in dc as well as to * set function parameters to arguments in bc. * @param p The program. * @param idx The index of the variable or array to copy to. * @param t The type to copy to. This could be a variable or an array. */ static void bc_program_copyToVar(BcProgram* p, size_t idx, BcType t) { BcResult *ptr = NULL, r; BcVec* vec; BcNum* n = NULL; bool var = (t == BC_TYPE_VAR); #if DC_ENABLED // Check the stack for dc. if (BC_IS_DC) { if (BC_ERR(!BC_PROG_STACK(&p->results, 1))) bc_err(BC_ERR_EXEC_STACK); } #endif assert(BC_PROG_STACK(&p->results, 1)); bc_program_operand(p, &ptr, &n, 0); #if BC_ENABLED // Get the variable for a bc function call. if (BC_IS_BC) { // Type match the result. bc_program_type_match(ptr, t); } #endif // BC_ENABLED vec = bc_program_vec(p, idx, t); // We can shortcut in dc if it's assigning a string by using // bc_program_assignStr(). if (ptr->t == BC_RESULT_STR) { assert(BC_PROG_STR(n)); if (BC_ERR(!var)) bc_err(BC_ERR_EXEC_TYPE); bc_program_assignStr(p, n, vec, true); return; } BC_SIG_LOCK; // Just create and copy for a normal variable. if (var) { if (BC_PROG_STR(n)) { // NOLINTNEXTLINE memcpy(&r.d.n, n, sizeof(BcNum)); } else bc_num_createCopy(&r.d.n, n); } else { // If we get here, we are handling an array. This is one place we need // to cast the number from bc_program_num() to a vector. BcVec* v = (BcVec*) n; BcVec* rv = &r.d.v; #if BC_ENABLED if (BC_IS_BC) { bool ref, ref_size; // True if we are using a reference. ref = (v->size == sizeof(BcNum) && t == BC_TYPE_REF); // True if we already have a reference vector. This is slightly // (okay, a lot; it just doesn't look that way) different from // above. The above means that we need to construct a reference // vector, whereas this means that we have one and we might have to // *dereference* it. ref_size = (v->size == sizeof(uchar)); // If we *should* have a reference. if (ref || (ref_size && t == BC_TYPE_REF)) { // Create a new reference vector. bc_vec_init(rv, sizeof(uchar), BC_DTOR_NONE); // If this is true, then we need to construct a reference. if (ref) { // Make sure the pointer was not invalidated. vec = bc_program_vec(p, idx, t); // Push the indices onto the reference vector. This takes // care of last; it ensures the reference goes to the right // place. bc_vec_pushIndex(rv, ptr->d.loc.loc); bc_vec_pushIndex(rv, ptr->d.loc.stack_idx); } // If we get here, we are copying a ref to a ref. Just push a // copy of all of the bytes. else bc_vec_npush(rv, v->len * sizeof(uchar), v->v); // Push the reference vector onto the array stack and pop the // source. bc_vec_push(vec, &r.d); bc_vec_pop(&p->results); // We need to return early to avoid executing code that we must // not touch. BC_SIG_UNLOCK; return; } // If we get here, we have a reference, but we need an array, so // dereference the array. else if (ref_size && t != BC_TYPE_REF) { v = bc_program_dereference(p, v); } } #endif // BC_ENABLED // If we get here, we need to copy the array because in bc, all // arguments are passed by value. Yes, this is expensive. bc_array_init(rv, true); bc_array_copy(rv, v); } // Push the vector onto the array stack and pop the source. bc_vec_push(vec, &r.d); bc_vec_pop(&p->results); BC_SIG_UNLOCK; } void bc_program_assignBuiltin(BcProgram* p, bool scale, bool obase, BcBigDig val) { BcBigDig* ptr_t; BcBigDig max, min; #if BC_ENABLED BcVec* v; BcBigDig* ptr; #endif // BC_ENABLED assert(!scale || !obase); // Scale needs handling separate from ibase and obase. if (scale) { // Set the min and max. min = 0; max = vm->maxes[BC_PROG_GLOBALS_SCALE]; #if BC_ENABLED // Get a pointer to the stack. v = p->globals_v + BC_PROG_GLOBALS_SCALE; #endif // BC_ENABLED // Get a pointer to the current value. ptr_t = p->globals + BC_PROG_GLOBALS_SCALE; } else { // Set the min and max. min = BC_NUM_MIN_BASE; if (BC_ENABLE_EXTRA_MATH && obase && (BC_IS_DC || !BC_IS_POSIX)) { min = 0; } max = vm->maxes[obase + BC_PROG_GLOBALS_IBASE]; #if BC_ENABLED // Get a pointer to the stack. v = p->globals_v + BC_PROG_GLOBALS_IBASE + obase; #endif // BC_ENABLED // Get a pointer to the current value. ptr_t = p->globals + BC_PROG_GLOBALS_IBASE + obase; } // Check for error. if (BC_ERR(val > max || val < min)) { BcErr e; // This grabs the right error. if (scale) e = BC_ERR_EXEC_SCALE; else if (obase) e = BC_ERR_EXEC_OBASE; else e = BC_ERR_EXEC_IBASE; bc_verr(e, min, max); } #if BC_ENABLED // Set the top of the stack. ptr = bc_vec_top(v); *ptr = val; #endif // BC_ENABLED // Set the actual global variable. *ptr_t = val; } #if BC_ENABLE_EXTRA_MATH void bc_program_assignSeed(BcProgram* p, BcNum* val) { bc_num_rng(val, &p->rng); } #endif // BC_ENABLE_EXTRA_MATH /** * Executes an assignment operator. * @param p The program. * @param inst The assignment operator to execute. */ static void bc_program_assign(BcProgram* p, uchar inst) { // The local use_val is true when the assigned value needs to be copied. BcResult* left; BcResult* right; BcResult res; BcNum* l; BcNum* r; bool ob, sc, use_val = BC_INST_USE_VAL(inst); bc_program_assignPrep(p, &left, &l, &right, &r); // Assigning to a string should be impossible simply because of the parse. assert(left->t != BC_RESULT_STR); // If we are assigning a string... if (right->t == BC_RESULT_STR) { assert(BC_PROG_STR(r)); #if BC_ENABLED if (inst != BC_INST_ASSIGN && inst != BC_INST_ASSIGN_NO_VAL) { bc_err(BC_ERR_EXEC_TYPE); } #endif // BC_ENABLED // If we are assigning to an array element... if (left->t == BC_RESULT_ARRAY_ELEM) { BC_SIG_LOCK; // We need to free the number and clear it. bc_num_free(l); // NOLINTNEXTLINE memcpy(l, r, sizeof(BcNum)); // Now we can pop the results. bc_vec_npop(&p->results, 2); BC_SIG_UNLOCK; } else { // If we get here, we are assigning to a variable, which we can use // bc_program_assignStr() for. BcVec* v = bc_program_vec(p, left->d.loc.loc, BC_TYPE_VAR); bc_program_assignStr(p, r, v, false); } #if BC_ENABLED // If this is true, the value is going to be used again, so we want to // push a temporary with the string. if (inst == BC_INST_ASSIGN) { res.t = BC_RESULT_STR; // NOLINTNEXTLINE memcpy(&res.d.n, r, sizeof(BcNum)); bc_vec_push(&p->results, &res); } #endif // BC_ENABLED // By using bc_program_assignStr(), we short-circuited this, so return. return; } // If we have a normal assignment operator, not a math one... if (BC_INST_IS_ASSIGN(inst)) { // Assigning to a variable that has a string here is fine because there // is no math done on it. // BC_RESULT_TEMP, BC_RESULT_IBASE, BC_RESULT_OBASE, BC_RESULT_SCALE, // and BC_RESULT_SEED all have temporary copies. Because that's the // case, we can free the left and just move the value over. We set the // type of right to BC_RESULT_ZERO in order to prevent it from being // freed. We also don't have to worry about BC_RESULT_STR because it's // take care of above. if (right->t == BC_RESULT_TEMP || right->t >= BC_RESULT_IBASE) { BC_SIG_LOCK; bc_num_free(l); // NOLINTNEXTLINE memcpy(l, r, sizeof(BcNum)); right->t = BC_RESULT_ZERO; BC_SIG_UNLOCK; } // Copy over. else bc_num_copy(l, r); } #if BC_ENABLED else { // If we get here, we are doing a math assignment (+=, -=, etc.). So // we need to prepare for a binary operator. BcBigDig scale = BC_PROG_SCALE(p); // At this point, the left side could still be a string because it could // be a variable that has the string. If that's the case, we have a type // error. if (BC_PROG_STR(l)) bc_err(BC_ERR_EXEC_TYPE); // Get the right type of assignment operator, whether val is used or // NO_VAL for performance. if (!use_val) { inst -= (BC_INST_ASSIGN_POWER_NO_VAL - BC_INST_ASSIGN_POWER); } assert(BC_NUM_RDX_VALID(l)); assert(BC_NUM_RDX_VALID(r)); // Run the actual operation. We do not need worry about reallocating l // because bc_num_binary() does that behind the scenes for us. bc_program_ops[inst - BC_INST_ASSIGN_POWER](l, r, l, scale); } #endif // BC_ENABLED ob = (left->t == BC_RESULT_OBASE); sc = (left->t == BC_RESULT_SCALE); // The globals need special handling, especially the non-seed ones. The // first part of the if statement handles them. if (ob || sc || left->t == BC_RESULT_IBASE) { // Get the actual value. BcBigDig val = bc_num_bigdig(l); bc_program_assignBuiltin(p, sc, ob, val); } #if BC_ENABLE_EXTRA_MATH // To assign to steed, let bc_num_rng() do its magic. else if (left->t == BC_RESULT_SEED) bc_program_assignSeed(p, l); #endif // BC_ENABLE_EXTRA_MATH BC_SIG_LOCK; // If we needed to use the value, then we need to copy it. Otherwise, we can // pop indiscriminately. Oh, and the copy should be a BC_RESULT_TEMP. if (use_val) { bc_num_createCopy(&res.d.n, l); res.t = BC_RESULT_TEMP; bc_vec_npop(&p->results, 2); bc_vec_push(&p->results, &res); } else bc_vec_npop(&p->results, 2); BC_SIG_UNLOCK; } /** * Pushes a variable's value onto the results stack. * @param p The program. * @param code The bytecode vector to pull the variable's index out of. * @param bgn An in/out parameter; the start of the index in the bytecode * vector, and will be updated to point after the index on return. * @param pop True if the variable's value should be popped off its stack. * This is only used in dc. * @param copy True if the variable's value should be copied to the results * stack. This is only used in dc. */ static void bc_program_pushVar(BcProgram* p, const char* restrict code, size_t* restrict bgn, bool pop, bool copy) { BcResult r; size_t idx = bc_program_index(code, bgn); BcVec* v; // Set the result appropriately. r.t = BC_RESULT_VAR; r.d.loc.loc = idx; // Get the stack for the variable. This is used in both bc and dc. v = bc_program_vec(p, idx, BC_TYPE_VAR); r.d.loc.stack_idx = v->len - 1; #if DC_ENABLED // If this condition is true, then we have the hard case, where we have to // adjust dc registers. if (BC_IS_DC && (pop || copy)) { // Get the number at the top at the top of the stack. BcNum* num = bc_vec_top(v); // Ensure there are enough elements on the stack. if (BC_ERR(!BC_PROG_STACK(v, 2 - copy))) { const char* name = bc_map_name(&p->var_map, idx); bc_verr(BC_ERR_EXEC_STACK_REGISTER, name); } assert(BC_PROG_STACK(v, 2 - copy)); // If the top of the stack is actually a number... if (!BC_PROG_STR(num)) { BC_SIG_LOCK; // Create a copy to go onto the results stack as appropriate. r.t = BC_RESULT_TEMP; bc_num_createCopy(&r.d.n, num); // If we are not actually copying, we need to do a replace, so pop. if (!copy) bc_vec_pop(v); bc_vec_push(&p->results, &r); BC_SIG_UNLOCK; return; } else { // Set the string result. We can just memcpy because all of the // fields in the num should be cleared. // NOLINTNEXTLINE memcpy(&r.d.n, num, sizeof(BcNum)); r.t = BC_RESULT_STR; } // If we are not actually copying, we need to do a replace, so pop. if (!copy) bc_vec_pop(v); } #endif // DC_ENABLED bc_vec_push(&p->results, &r); } /** * Pushes an array or an array element onto the results stack. * @param p The program. * @param code The bytecode vector to pull the variable's index out of. * @param bgn An in/out parameter; the start of the index in the bytecode * vector, and will be updated to point after the index on return. * @param inst The instruction; whether to push an array or an array element. */ static void bc_program_pushArray(BcProgram* p, const char* restrict code, size_t* restrict bgn, uchar inst) { BcResult r; BcResult* operand; BcNum* num; BcBigDig temp; BcVec* v; // Get the index of the array. r.d.loc.loc = bc_program_index(code, bgn); // We need the array to get its length. v = bc_program_vec(p, r.d.loc.loc, BC_TYPE_ARRAY); assert(v != NULL); r.d.loc.stack_idx = v->len - 1; // Doing an array is easy; just set the result type and finish. if (inst == BC_INST_ARRAY) { r.t = BC_RESULT_ARRAY; bc_vec_push(&p->results, &r); return; } // Grab the top element of the results stack for the array index. bc_program_prep(p, &operand, &num, 0); temp = bc_num_bigdig(num); // Set the result. r.t = BC_RESULT_ARRAY_ELEM; r.d.loc.idx = (size_t) temp; BC_SIG_LOCK; // Pop the index and push the element. bc_vec_pop(&p->results); bc_vec_push(&p->results, &r); BC_SIG_UNLOCK; } #if BC_ENABLED /** * Executes an increment or decrement operator. This only handles postfix * inc/dec because the parser translates prefix inc/dec into an assignment where * the value is used. * @param p The program. * @param inst The instruction; whether to do an increment or decrement. */ static void bc_program_incdec(BcProgram* p, uchar inst) { BcResult *ptr, res, copy; BcNum* num; uchar inst2; bc_program_prep(p, &ptr, &num, 0); BC_SIG_LOCK; // We need a copy from *before* the operation. copy.t = BC_RESULT_TEMP; bc_num_createCopy(©.d.n, num); BC_SETJMP_LOCKED(vm, exit); BC_SIG_UNLOCK; // Create the proper assignment. res.t = BC_RESULT_ONE; inst2 = BC_INST_ASSIGN_PLUS_NO_VAL + (inst & 0x01); bc_vec_push(&p->results, &res); bc_program_assign(p, inst2); BC_SIG_LOCK; bc_vec_push(&p->results, ©); BC_UNSETJMP(vm); BC_SIG_UNLOCK; // No need to free the copy here because we pushed it onto the stack. return; exit: BC_SIG_MAYLOCK; bc_num_free(©.d.n); BC_LONGJMP_CONT(vm); } /** * Executes a function call for bc. * @param p The program. * @param code The bytecode vector to pull the number of arguments and the * function index out of. * @param bgn An in/out parameter; the start of the indices in the bytecode * vector, and will be updated to point after the indices on * return. */ static void bc_program_call(BcProgram* p, const char* restrict code, size_t* restrict bgn) { BcInstPtr ip; size_t i, nargs; BcFunc* f; BcVec* v; BcAuto* a; BcResult* arg; // Pull the number of arguments out of the bytecode vector. nargs = bc_program_index(code, bgn); // Set up instruction pointer. ip.idx = 0; ip.func = bc_program_index(code, bgn); f = bc_vec_item(&p->fns, ip.func); // Error checking. if (BC_ERR(!f->code.len)) bc_verr(BC_ERR_EXEC_UNDEF_FUNC, f->name); if (BC_ERR(nargs != f->nparams)) { bc_verr(BC_ERR_EXEC_PARAMS, f->nparams, nargs); } // Set the length of the results stack. We discount the argument, of course. ip.len = p->results.len - nargs; assert(BC_PROG_STACK(&p->results, nargs)); // Prepare the globals' stacks. if (BC_G) bc_program_prepGlobals(p); // Push the arguments onto the stacks of their respective parameters. for (i = 0; i < nargs; ++i) { arg = bc_vec_top(&p->results); if (BC_ERR(arg->t == BC_RESULT_VOID)) bc_err(BC_ERR_EXEC_VOID_VAL); // Get the corresponding parameter. a = bc_vec_item(&f->autos, nargs - 1 - i); // Actually push the value onto the parameter's stack. bc_program_copyToVar(p, a->idx, a->type); } BC_SIG_LOCK; // Push zeroes onto the stacks of the auto variables. for (; i < f->autos.len; ++i) { // Get the auto and its stack. a = bc_vec_item(&f->autos, i); v = bc_program_vec(p, a->idx, a->type); // If a variable, just push a 0; otherwise, push an array. if (a->type == BC_TYPE_VAR) { BcNum* n = bc_vec_pushEmpty(v); bc_num_init(n, BC_NUM_DEF_SIZE); } else { BcVec* v2; assert(a->type == BC_TYPE_ARRAY); v2 = bc_vec_pushEmpty(v); bc_array_init(v2, true); } } // Push the instruction pointer onto the execution stack. bc_vec_push(&p->stack, &ip); BC_SIG_UNLOCK; } /** * Executes a return instruction. * @param p The program. * @param inst The return instruction. bc can return void, and we need to know * if it is. */ static void bc_program_return(BcProgram* p, uchar inst) { BcResult* res; BcFunc* f; BcInstPtr* ip; size_t i, nresults; // Get the instruction pointer. ip = bc_vec_top(&p->stack); // Get the difference between the actual number of results and the number of // results the caller expects. nresults = p->results.len - ip->len; // If this isn't true, there was a missing call somewhere. assert(BC_PROG_STACK(&p->stack, 2)); // If this isn't true, the parser screwed by giving us no value when we // expected one, or giving us a value when we expected none. assert(BC_PROG_STACK(&p->results, ip->len + (inst == BC_INST_RET))); // Get the function we are returning from. f = bc_vec_item(&p->fns, ip->func); res = bc_program_prepResult(p); // If we are returning normally... if (inst == BC_INST_RET) { BcNum* num; BcResult* operand; // Prepare and copy the return value. bc_program_operand(p, &operand, &num, 1); if (BC_PROG_STR(num)) { // We need to set this because otherwise, it will be a // BC_RESULT_TEMP, and BC_RESULT_TEMP needs an actual number to make // it easier to do type checking. res->t = BC_RESULT_STR; // NOLINTNEXTLINE memcpy(&res->d.n, num, sizeof(BcNum)); } else { BC_SIG_LOCK; bc_num_createCopy(&res->d.n, num); } } // Void is easy; set the result. else if (inst == BC_INST_RET_VOID) res->t = BC_RESULT_VOID; else { BC_SIG_LOCK; // If we get here, the instruction is for returning a zero, so do that. bc_num_init(&res->d.n, BC_NUM_DEF_SIZE); } BC_SIG_MAYUNLOCK; // We need to pop items off of the stacks of arguments and autos as well. for (i = 0; i < f->autos.len; ++i) { BcAuto* a = bc_vec_item(&f->autos, i); BcVec* v = bc_program_vec(p, a->idx, a->type); bc_vec_pop(v); } BC_SIG_LOCK; // When we retire, pop all of the unused results. bc_program_retire(p, 1, nresults); // Pop the globals, if necessary. if (BC_G) bc_program_popGlobals(p, false); // Pop the stack. This is what causes the function to actually "return." bc_vec_pop(&p->stack); BC_SIG_UNLOCK; } #endif // BC_ENABLED /** * Executes a builtin function. * @param p The program. * @param inst The builtin to execute. */ static void bc_program_builtin(BcProgram* p, uchar inst) { BcResult* opd; BcResult* res; BcNum* num; bool len = (inst == BC_INST_LENGTH); // Ensure we have a valid builtin. #if BC_ENABLE_EXTRA_MATH assert(inst >= BC_INST_LENGTH && inst <= BC_INST_IRAND); #else // BC_ENABLE_EXTRA_MATH assert(inst >= BC_INST_LENGTH && inst <= BC_INST_IS_STRING); #endif // BC_ENABLE_EXTRA_MATH #ifndef BC_PROG_NO_STACK_CHECK // Check stack for dc. if (BC_IS_DC && BC_ERR(!BC_PROG_STACK(&p->results, 1))) { bc_err(BC_ERR_EXEC_STACK); } #endif // BC_PROG_NO_STACK_CHECK assert(BC_PROG_STACK(&p->results, 1)); res = bc_program_prepResult(p); bc_program_operand(p, &opd, &num, 1); assert(num != NULL); // We need to ensure that strings and arrays aren't passed to most builtins. // The scale function can take strings in dc. if (!len && (inst != BC_INST_SCALE_FUNC || BC_IS_BC) && inst != BC_INST_IS_NUMBER && inst != BC_INST_IS_STRING) { bc_program_type_num(opd, num); } // Square root is easy. if (inst == BC_INST_SQRT) bc_num_sqrt(num, &res->d.n, BC_PROG_SCALE(p)); // Absolute value is easy. else if (inst == BC_INST_ABS) { BC_SIG_LOCK; bc_num_createCopy(&res->d.n, num); BC_SIG_UNLOCK; BC_NUM_NEG_CLR_NP(res->d.n); } // Testing for number or string is easy. else if (inst == BC_INST_IS_NUMBER || inst == BC_INST_IS_STRING) { bool cond; bool is_str; BC_SIG_LOCK; bc_num_init(&res->d.n, BC_NUM_DEF_SIZE); BC_SIG_UNLOCK; // Test if the number is a string. is_str = BC_PROG_STR(num); // This confusing condition simply means that the instruction must be // true if is_str is, or it must be false if is_str is. Otherwise, the // returned value is false (0). cond = ((inst == BC_INST_IS_STRING) == is_str); if (cond) bc_num_one(&res->d.n); } #if BC_ENABLE_EXTRA_MATH // irand() is easy. else if (inst == BC_INST_IRAND) { BC_SIG_LOCK; bc_num_init(&res->d.n, num->len - BC_NUM_RDX_VAL(num)); BC_SIG_UNLOCK; bc_num_irand(num, &res->d.n, &p->rng); } #endif // BC_ENABLE_EXTRA_MATH // Everything else is...not easy. else { BcBigDig val = 0; // Well, scale() is easy, but length() is not. if (len) { // If we are bc and we have an array... if (opd->t == BC_RESULT_ARRAY) { // Yes, this is one place where we need to cast the number from // bc_program_num() to a vector. BcVec* v = (BcVec*) num; // XXX: If this is changed, you should also change the similar // code in bc_program_asciify(). #if BC_ENABLED // Dereference the array, if necessary. if (BC_IS_BC && v->size == sizeof(uchar)) { v = bc_program_dereference(p, v); } #endif // BC_ENABLED assert(v->size == sizeof(BcNum)); val = (BcBigDig) v->len; } else { // If the item is a string... if (!BC_PROG_NUM(opd, num)) { char* str; // Get the string, then get the length. str = bc_program_string(p, num); val = (BcBigDig) strlen(str); } else { // Calculate the length of the number. val = (BcBigDig) bc_num_len(num); } } } // Like I said; scale() is actually easy. It just also needs the integer // conversion that length() does. else if (BC_IS_BC || BC_PROG_NUM(opd, num)) { val = (BcBigDig) bc_num_scale(num); } BC_SIG_LOCK; // Create the result. bc_num_createFromBigdig(&res->d.n, val); BC_SIG_UNLOCK; } bc_program_retire(p, 1, 1); } /** * Executes a divmod. * @param p The program. */ static void bc_program_divmod(BcProgram* p) { BcResult* opd1; BcResult* opd2; BcResult* res; BcResult* res2; BcNum* n1; BcNum* n2; size_t req; // We grow first to avoid pointer invalidation. bc_vec_grow(&p->results, 2); // We don't need to update the pointer because // the capacity is enough due to the line above. res2 = bc_program_prepResult(p); res = bc_program_prepResult(p); // Prepare the operands. bc_program_binOpPrep(p, &opd1, &n1, &opd2, &n2, 2); req = bc_num_mulReq(n1, n2, BC_PROG_SCALE(p)); BC_SIG_LOCK; // Initialize the results. bc_num_init(&res->d.n, req); bc_num_init(&res2->d.n, req); BC_SIG_UNLOCK; // Execute. bc_num_divmod(n1, n2, &res2->d.n, &res->d.n, BC_PROG_SCALE(p)); bc_program_retire(p, 2, 2); } /** * Executes modular exponentiation. * @param p The program. */ static void bc_program_modexp(BcProgram* p) { BcResult* r1; BcResult* r2; BcResult* r3; BcResult* res; BcNum* n1; BcNum* n2; BcNum* n3; #if DC_ENABLED // Check the stack. if (BC_IS_DC && BC_ERR(!BC_PROG_STACK(&p->results, 3))) { bc_err(BC_ERR_EXEC_STACK); } #endif // DC_ENABLED assert(BC_PROG_STACK(&p->results, 3)); res = bc_program_prepResult(p); // Get the first operand and typecheck. bc_program_operand(p, &r1, &n1, 3); bc_program_type_num(r1, n1); // Get the last two operands. bc_program_binOpPrep(p, &r2, &n2, &r3, &n3, 1); // Make sure that the values have their pointers updated, if necessary. // Only array elements are possible because this is dc. if (r1->t == BC_RESULT_ARRAY_ELEM && (r1->t == r2->t || r1->t == r3->t)) { n1 = bc_program_num(p, r1); } BC_SIG_LOCK; bc_num_init(&res->d.n, n3->len); BC_SIG_UNLOCK; bc_num_modexp(n1, n2, n3, &res->d.n); bc_program_retire(p, 1, 3); } /** * Asciifies a number for dc. This is a helper for bc_program_asciify(). * @param p The program. * @param n The number to asciify. */ static uchar bc_program_asciifyNum(BcProgram* p, BcNum* n) { bc_num_copy(&p->asciify, n); // We want to clear the scale and sign for easy mod later. bc_num_truncate(&p->asciify, p->asciify.scale); BC_NUM_NEG_CLR(&p->asciify); // This is guaranteed to not have a divide by 0 // because strmb is equal to 256. bc_num_mod(&p->asciify, &p->strmb, &p->asciify, 0); // This is also guaranteed to not error because num is in the range // [0, UCHAR_MAX], which is definitely in range for a BcBigDig. And // it is not negative. return (uchar) bc_num_bigdig2(&p->asciify); } /** * Executes the "asciify" command in bc and dc. * @param p The program. */ static void bc_program_asciify(BcProgram* p) { BcResult *r, res; BcNum* n; uchar c; size_t idx; #if BC_ENABLED // This is in the outer scope because it has to be freed after a jump. char* temp_str; #endif // BC_ENABLED // Check the stack. if (BC_ERR(!BC_PROG_STACK(&p->results, 1))) bc_err(BC_ERR_EXEC_STACK); assert(BC_PROG_STACK(&p->results, 1)); // Get the top of the results stack. bc_program_operand(p, &r, &n, 0); assert(n != NULL); assert(BC_IS_BC || r->t != BC_RESULT_ARRAY); #if BC_ENABLED // Handle arrays in bc specially. if (r->t == BC_RESULT_ARRAY) { // Yes, this is one place where we need to cast the number from // bc_program_num() to a vector. BcVec* v = (BcVec*) n; size_t i; // XXX: If this is changed, you should also change the similar code in // bc_program_builtin(). // Dereference the array, if necessary. if (v->size == sizeof(uchar)) { v = bc_program_dereference(p, v); } assert(v->size == sizeof(BcNum)); // Allocate the string and set the jump for it. BC_SIG_LOCK; temp_str = bc_vm_malloc(v->len + 1); BC_SETJMP_LOCKED(vm, exit); BC_SIG_UNLOCK; // Convert the array. for (i = 0; i < v->len; ++i) { BcNum* num = (BcNum*) bc_vec_item(v, i); if (BC_PROG_STR(num)) { temp_str[i] = (bc_program_string(p, num))[0]; } else { temp_str[i] = (char) bc_program_asciifyNum(p, num); } } temp_str[v->len] = '\0'; // Store the string in the slab and map, and free the temp string. BC_SIG_LOCK; idx = bc_program_addString(p, temp_str); free(temp_str); BC_UNSETJMP(vm); BC_SIG_UNLOCK; } else #endif // BC_ENABLED { char str[2]; char* str2; // Asciify. if (BC_PROG_NUM(r, n)) c = bc_program_asciifyNum(p, n); else { // Get the string itself, then the first character. str2 = bc_program_string(p, n); c = (uchar) str2[0]; } // Fill the resulting string. str[0] = (char) c; str[1] = '\0'; // Add the string to the data structures. BC_SIG_LOCK; idx = bc_program_addString(p, str); BC_SIG_UNLOCK; } // Set the result res.t = BC_RESULT_STR; bc_num_clear(&res.d.n); res.d.n.scale = idx; // Pop and push. bc_vec_pop(&p->results); bc_vec_push(&p->results, &res); return; #if BC_ENABLED exit: free(temp_str); #endif // BC_ENABLED } /** * Streams a number or a string to stdout. * @param p The program. */ static void bc_program_printStream(BcProgram* p) { BcResult* r; BcNum* n; // Check the stack. if (BC_ERR(!BC_PROG_STACK(&p->results, 1))) bc_err(BC_ERR_EXEC_STACK); assert(BC_PROG_STACK(&p->results, 1)); // Get the top of the results stack. bc_program_operand(p, &r, &n, 0); assert(n != NULL); // Stream appropriately. if (BC_PROG_NUM(r, n)) bc_num_stream(n); else bc_program_printChars(bc_program_string(p, n)); // Pop the operand. bc_vec_pop(&p->results); } #if DC_ENABLED /** * Gets the length of a register in dc and pushes it onto the results stack. * @param p The program. * @param code The bytecode vector to pull the register's index out of. * @param bgn An in/out parameter; the start of the index in the bytecode * vector, and will be updated to point after the index on return. */ static void bc_program_regStackLen(BcProgram* p, const char* restrict code, size_t* restrict bgn) { size_t idx = bc_program_index(code, bgn); BcVec* v = bc_program_vec(p, idx, BC_TYPE_VAR); bc_program_pushBigdig(p, (BcBigDig) v->len, BC_RESULT_TEMP); } /** * Pushes the length of the results stack onto the results stack. * @param p The program. */ static void bc_program_stackLen(BcProgram* p) { bc_program_pushBigdig(p, (BcBigDig) p->results.len, BC_RESULT_TEMP); } /** * Pops a certain number of elements off the execution stack. * @param p The program. * @param inst The instruction to tell us how many. There is one to pop up to * 2, and one to pop the amount equal to the number at the top of * the results stack. */ static void bc_program_nquit(BcProgram* p, uchar inst) { BcResult* opnd; BcNum* num; BcBigDig val; size_t i; // Ensure that the tail calls stack is correct. assert(p->stack.len == p->tail_calls.len); // Get the number of executions to pop. if (inst == BC_INST_QUIT) val = 2; else { bc_program_prep(p, &opnd, &num, 0); val = bc_num_bigdig(num); bc_vec_pop(&p->results); } // Loop over the tail call stack and adjust the quit value appropriately. for (i = 0; val && i < p->tail_calls.len; ++i) { // Get the number of tail calls for this one. size_t calls = *((size_t*) bc_vec_item_rev(&p->tail_calls, i)) + 1; // Adjust the value. if (calls >= val) val = 0; else val -= (BcBigDig) calls; } // If we don't have enough executions, just quit. if (i == p->stack.len) { vm->status = BC_STATUS_QUIT; BC_JMP; } else { // We can always pop the last item we reached on the tail call stack // because these are for tail calls. That means that any executions that // we would not have quit in that position on the stack would have quit // anyway. BC_SIG_LOCK; bc_vec_npop(&p->stack, i); bc_vec_npop(&p->tail_calls, i); BC_SIG_UNLOCK; } } /** * Pushes the depth of the execution stack onto the stack. * @param p The program. */ static void bc_program_execStackLen(BcProgram* p) { size_t i, amt, len = p->tail_calls.len; amt = len; for (i = 0; i < len; ++i) { amt += *((size_t*) bc_vec_item(&p->tail_calls, i)); } bc_program_pushBigdig(p, (BcBigDig) amt, BC_RESULT_TEMP); } /** * * @param p The program. * @param code The bytecode vector to pull the register's index out of. * @param bgn An in/out parameter; the start of the index in the bytecode * vector, and will be updated to point after the index on return. * @param cond True if the execution is conditional, false otherwise. * @param len The number of bytes in the bytecode vector. */ static void bc_program_execStr(BcProgram* p, const char* restrict code, size_t* restrict bgn, bool cond, size_t len) { BcResult* r; char* str; BcFunc* f; BcInstPtr ip; size_t fidx; BcNum* n; assert(p->stack.len == p->tail_calls.len); // Check the stack. if (BC_ERR(!BC_PROG_STACK(&p->results, 1))) bc_err(BC_ERR_EXEC_STACK); assert(BC_PROG_STACK(&p->results, 1)); // Get the operand. bc_program_operand(p, &r, &n, 0); // If execution is conditional... if (cond) { bool exec; size_t then_idx; // These are volatile to quiet warnings on GCC about clobbering with // longjmp(). volatile size_t else_idx; volatile size_t idx; // Get the index of the "then" var and "else" var. then_idx = bc_program_index(code, bgn); else_idx = bc_program_index(code, bgn); // Figure out if we should execute. exec = (r->d.n.len != 0); idx = exec ? then_idx : else_idx; BC_SIG_LOCK; BC_SETJMP_LOCKED(vm, exit); // If we are supposed to execute, execute. If else_idx == SIZE_MAX, that // means there was no else clause, so if execute is false and else does // not exist, we don't execute. The goto skips all of the setup for the // execution. if (exec || (else_idx != SIZE_MAX)) { n = bc_vec_top(bc_program_vec(p, idx, BC_TYPE_VAR)); } else goto exit; if (BC_ERR(!BC_PROG_STR(n))) bc_err(BC_ERR_EXEC_TYPE); BC_UNSETJMP(vm); BC_SIG_UNLOCK; } else { // In non-conditional situations, only the top of stack can be executed, // and in those cases, variables are not allowed to be "on the stack"; // they are only put on the stack to be assigned to. assert(r->t != BC_RESULT_VAR); if (r->t != BC_RESULT_STR) return; } assert(BC_PROG_STR(n)); // Get the string. str = bc_program_string(p, n); // Get the function index and function. BC_SIG_LOCK; fidx = bc_program_insertFunc(p, str); BC_SIG_UNLOCK; f = bc_vec_item(&p->fns, fidx); // If the function has not been parsed yet... if (!f->code.len) { BC_SIG_LOCK; if (!BC_PARSE_IS_INITED(&vm->read_prs, p)) { bc_parse_init(&vm->read_prs, p, fidx); // Initialize this too because bc_vm_shutdown() expects them to be // initialized togther. bc_vec_init(&vm->read_buf, sizeof(char), BC_DTOR_NONE); } // This needs to be updated because the parser could have been used // somewhere else else bc_parse_updateFunc(&vm->read_prs, fidx); bc_lex_file(&vm->read_prs.l, vm->file); BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; // Parse. Only one expression is needed, so stdin isn't used. bc_parse_text(&vm->read_prs, str, BC_MODE_FILE); BC_SIG_LOCK; vm->expr(&vm->read_prs, BC_PARSE_NOCALL); BC_UNSETJMP(vm); // We can just assert this here because // dc should parse everything until EOF. assert(vm->read_prs.l.t == BC_LEX_EOF); BC_SIG_UNLOCK; } // Set the instruction pointer. ip.idx = 0; ip.len = p->results.len; ip.func = fidx; BC_SIG_LOCK; // Pop the operand. bc_vec_pop(&p->results); // Tail call processing. This condition means that there is more on the // execution stack, and we are at the end of the bytecode vector, and the // last instruction is just a BC_INST_POP_EXEC, which would return. if (p->stack.len > 1 && *bgn == len - 1 && code[*bgn] == BC_INST_POP_EXEC) { size_t* call_ptr = bc_vec_top(&p->tail_calls); // Add one to the tail call. *call_ptr += 1; // Pop the execution stack before pushing the new instruction pointer // on. bc_vec_pop(&p->stack); } // If not a tail call, just push a new one. else bc_vec_push(&p->tail_calls, &ip.idx); // Push the new function onto the execution stack and return. bc_vec_push(&p->stack, &ip); BC_SIG_UNLOCK; return; err: BC_SIG_MAYLOCK; f = bc_vec_item(&p->fns, fidx); // Make sure to erase the bytecode vector so dc knows it is not parsed. bc_vec_popAll(&f->code); exit: bc_vec_pop(&p->results); BC_LONGJMP_CONT(vm); } /** * Prints every item on the results stack, one per line. * @param p The program. */ static void bc_program_printStack(BcProgram* p) { size_t idx; for (idx = 0; idx < p->results.len; ++idx) { bc_program_print(p, BC_INST_PRINT, idx); } } #endif // DC_ENABLED /** * Pushes the value of a global onto the results stack. * @param p The program. * @param inst Which global to push, as an instruction. */ static void bc_program_pushGlobal(BcProgram* p, uchar inst) { BcResultType t; // Make sure the instruction is valid. assert(inst >= BC_INST_IBASE && inst <= BC_INST_SCALE); // Push the global. t = inst - BC_INST_IBASE + BC_RESULT_IBASE; bc_program_pushBigdig(p, p->globals[inst - BC_INST_IBASE], t); } /** * Pushes the value of a global setting onto the stack. * @param p The program. * @param inst Which global setting to push, as an instruction. */ static void bc_program_globalSetting(BcProgram* p, uchar inst) { BcBigDig val; // Make sure the instruction is valid. #if DC_ENABLED assert((inst >= BC_INST_LINE_LENGTH && inst <= BC_INST_LEADING_ZERO) || (BC_IS_DC && inst == BC_INST_EXTENDED_REGISTERS)); #else // DC_ENABLED assert(inst >= BC_INST_LINE_LENGTH && inst <= BC_INST_LEADING_ZERO); #endif // DC_ENABLED if (inst == BC_INST_LINE_LENGTH) val = (BcBigDig) vm->line_len; #if BC_ENABLED else if (inst == BC_INST_GLOBAL_STACKS) val = (BC_G != 0); #endif // BC_ENABLED #if DC_ENABLED else if (inst == BC_INST_EXTENDED_REGISTERS) val = (DC_X != 0); #endif // DC_ENABLED else val = (BC_Z != 0); // Push the global. bc_program_pushBigdig(p, val, BC_RESULT_TEMP); } #if BC_ENABLE_EXTRA_MATH /** * Pushes the value of seed on the stack. * @param p The program. */ static void bc_program_pushSeed(BcProgram* p) { BcResult* res; res = bc_program_prepResult(p); res->t = BC_RESULT_SEED; BC_SIG_LOCK; // We need 2*BC_RAND_NUM_SIZE because of the size of the state. bc_num_init(&res->d.n, 2 * BC_RAND_NUM_SIZE); BC_SIG_UNLOCK; bc_num_createFromRNG(&res->d.n, &p->rng); } #endif // BC_ENABLE_EXTRA_MATH /** * Adds a function to the fns array. The function's ID must have already been * inserted into the map. * @param p The program. * @param id_ptr The ID of the function as inserted into the map. */ static void bc_program_addFunc(BcProgram* p, BcId* id_ptr) { BcFunc* f; BC_SIG_ASSERT_LOCKED; // Push and init. f = bc_vec_pushEmpty(&p->fns); bc_func_init(f, id_ptr->name); } size_t bc_program_insertFunc(BcProgram* p, const char* name) { BcId* id_ptr; bool new; size_t idx; BC_SIG_ASSERT_LOCKED; assert(p != NULL && name != NULL); // Insert into the map and get the resulting ID. new = bc_map_insert(&p->fn_map, name, p->fns.len, &idx); id_ptr = (BcId*) bc_vec_item(&p->fn_map, idx); idx = id_ptr->idx; // If the function is new... if (new) { // Add the function to the fns array. bc_program_addFunc(p, id_ptr); } #if BC_ENABLED // bc has to reset the function because it's about to be redefined. else if (BC_IS_BC) { BcFunc* func = bc_vec_item(&p->fns, idx); bc_func_reset(func); } #endif // BC_ENABLED return idx; } #if BC_DEBUG void bc_program_free(BcProgram* p) { #if BC_ENABLED size_t i; #endif // BC_ENABLED BC_SIG_ASSERT_LOCKED; assert(p != NULL); #if BC_ENABLED // Free the globals stacks. for (i = 0; i < BC_PROG_GLOBALS_LEN; ++i) { bc_vec_free(p->globals_v + i); } #endif // BC_ENABLED bc_vec_free(&p->fns); bc_vec_free(&p->fn_map); bc_vec_free(&p->vars); bc_vec_free(&p->var_map); bc_vec_free(&p->arrs); bc_vec_free(&p->arr_map); bc_vec_free(&p->results); bc_vec_free(&p->stack); bc_vec_free(&p->consts); bc_vec_free(&p->const_map); bc_vec_free(&p->strs); bc_vec_free(&p->str_map); bc_num_free(&p->asciify); #if BC_ENABLED if (BC_IS_BC) bc_num_free(&p->last); #endif // BC_ENABLED #if BC_ENABLE_EXTRA_MATH bc_rand_free(&p->rng); #endif // BC_ENABLE_EXTRA_MATH #if DC_ENABLED if (BC_IS_DC) bc_vec_free(&p->tail_calls); #endif // DC_ENABLED } #endif // BC_DEBUG void bc_program_init(BcProgram* p) { BcInstPtr ip; size_t i; BC_SIG_ASSERT_LOCKED; assert(p != NULL); // We want this clear. // NOLINTNEXTLINE memset(&ip, 0, sizeof(BcInstPtr)); // Setup the globals stacks and the current values. for (i = 0; i < BC_PROG_GLOBALS_LEN; ++i) { BcBigDig val = i == BC_PROG_GLOBALS_SCALE ? 0 : BC_BASE; #if BC_ENABLED bc_vec_init(p->globals_v + i, sizeof(BcBigDig), BC_DTOR_NONE); bc_vec_push(p->globals_v + i, &val); #endif // BC_ENABLED p->globals[i] = val; } #if DC_ENABLED // dc-only setup. if (BC_IS_DC) { bc_vec_init(&p->tail_calls, sizeof(size_t), BC_DTOR_NONE); // We want an item for the main function on the tail call stack. i = 0; bc_vec_push(&p->tail_calls, &i); } #endif // DC_ENABLED bc_num_setup(&p->strmb, p->strmb_num, BC_NUM_BIGDIG_LOG10); bc_num_bigdig2num(&p->strmb, BC_NUM_STREAM_BASE); bc_num_init(&p->asciify, BC_NUM_DEF_SIZE); #if BC_ENABLE_EXTRA_MATH // We need to initialize srand() just in case /dev/urandom and /dev/random // are not available. srand((unsigned int) time(NULL)); bc_rand_init(&p->rng); #endif // BC_ENABLE_EXTRA_MATH #if BC_ENABLED if (BC_IS_BC) bc_num_init(&p->last, BC_NUM_DEF_SIZE); #endif // BC_ENABLED #if BC_DEBUG bc_vec_init(&p->fns, sizeof(BcFunc), BC_DTOR_FUNC); #else // BC_DEBUG bc_vec_init(&p->fns, sizeof(BcFunc), BC_DTOR_NONE); #endif // BC_DEBUG bc_map_init(&p->fn_map); bc_program_insertFunc(p, bc_func_main); bc_program_insertFunc(p, bc_func_read); bc_vec_init(&p->vars, sizeof(BcVec), BC_DTOR_VEC); bc_map_init(&p->var_map); bc_vec_init(&p->arrs, sizeof(BcVec), BC_DTOR_VEC); bc_map_init(&p->arr_map); bc_vec_init(&p->results, sizeof(BcResult), BC_DTOR_RESULT); // Push the first instruction pointer onto the execution stack. bc_vec_init(&p->stack, sizeof(BcInstPtr), BC_DTOR_NONE); bc_vec_push(&p->stack, &ip); bc_vec_init(&p->consts, sizeof(BcConst), BC_DTOR_CONST); bc_map_init(&p->const_map); bc_vec_init(&p->strs, sizeof(char*), BC_DTOR_NONE); bc_map_init(&p->str_map); } void bc_program_printStackTrace(BcProgram* p) { size_t i, max_digits; max_digits = bc_vm_numDigits(p->stack.len - 1); for (i = 0; i < p->stack.len; ++i) { BcInstPtr* ip = bc_vec_item_rev(&p->stack, i); BcFunc* f = bc_vec_item(&p->fns, ip->func); size_t j, digits; digits = bc_vm_numDigits(i); bc_file_puts(&vm->ferr, bc_flush_none, " "); for (j = 0; j < max_digits - digits; ++j) { bc_file_putchar(&vm->ferr, bc_flush_none, ' '); } bc_file_printf(&vm->ferr, "%zu: %s", i, f->name); #if BC_ENABLED if (BC_IS_BC && ip->func != BC_PROG_MAIN && ip->func != BC_PROG_READ) { bc_file_puts(&vm->ferr, bc_flush_none, "()"); } #endif // BC_ENABLED bc_file_putchar(&vm->ferr, bc_flush_none, '\n'); } } void bc_program_reset(BcProgram* p) { BcFunc* f; BcInstPtr* ip; BC_SIG_ASSERT_LOCKED; // Pop all but the last execution and all results. bc_vec_npop(&p->stack, p->stack.len - 1); bc_vec_popAll(&p->results); #if DC_ENABLED // We need to pop tail calls too. if (BC_IS_DC) bc_vec_npop(&p->tail_calls, p->tail_calls.len - 1); #endif // DC_ENABLED #if BC_ENABLED // Clear the globals' stacks. if (BC_G) bc_program_popGlobals(p, true); #endif // BC_ENABLED // Clear the bytecode vector of the main function. f = bc_vec_item(&p->fns, BC_PROG_MAIN); bc_vec_npop(&f->code, f->code.len); // Reset the instruction pointer. ip = bc_vec_top(&p->stack); // NOLINTNEXTLINE memset(ip, 0, sizeof(BcInstPtr)); if (BC_SIG_INTERRUPT(vm)) { // Write the ready message for a signal. bc_file_printf(&vm->fout, "%s", bc_program_ready_msg); bc_file_flush(&vm->fout, bc_flush_err); } // Clear the signal. vm->sig = 0; } void bc_program_exec(BcProgram* p) { size_t idx; BcResult r; BcResult* ptr; BcInstPtr* ip; BcFunc* func; char* code; bool cond = false; uchar inst; #if BC_ENABLED BcNum* num; #endif // BC_ENABLED #if !BC_HAS_COMPUTED_GOTO #if BC_DEBUG size_t jmp_bufs_len; #endif // BC_DEBUG #endif // !BC_HAS_COMPUTED_GOTO #if BC_HAS_COMPUTED_GOTO #if BC_GCC #pragma GCC diagnostic ignored "-Wpedantic" #endif // BC_GCC #if BC_CLANG #pragma clang diagnostic ignored "-Wgnu-label-as-value" #endif // BC_CLANG BC_PROG_LBLS; BC_PROG_LBLS_ASSERT; #if BC_CLANG #pragma clang diagnostic warning "-Wgnu-label-as-value" #endif // BC_CLANG #if BC_GCC #pragma GCC diagnostic warning "-Wpedantic" #endif // BC_GCC // BC_INST_INVALID is a marker for the end so that we don't have to have an // execution loop. func = (BcFunc*) bc_vec_item(&p->fns, BC_PROG_MAIN); bc_vec_pushByte(&func->code, BC_INST_INVALID); #endif // BC_HAS_COMPUTED_GOTO BC_SETJMP(vm, end); ip = bc_vec_top(&p->stack); func = (BcFunc*) bc_vec_item(&p->fns, ip->func); code = func->code.v; #if !BC_HAS_COMPUTED_GOTO #if BC_DEBUG jmp_bufs_len = vm->jmp_bufs.len; #endif // BC_DEBUG // This loop is the heart of the execution engine. It *is* the engine. For // computed goto, it is ignored. while (ip->idx < func->code.len) #endif // !BC_HAS_COMPUTED_GOTO { BC_SIG_ASSERT_NOT_LOCKED; #if BC_HAS_COMPUTED_GOTO #if BC_GCC #pragma GCC diagnostic ignored "-Wpedantic" #endif // BC_GCC #if BC_CLANG #pragma clang diagnostic ignored "-Wgnu-label-as-value" #endif // BC_CLANG BC_PROG_JUMP(inst, code, ip); #else // BC_HAS_COMPUTED_GOTO // Get the next instruction and increment the index. inst = (uchar) code[(ip->idx)++]; #endif // BC_HAS_COMPUTED_GOTO #if BC_DEBUG_CODE bc_file_printf(&vm->ferr, "inst: %s\n", bc_inst_names[inst]); bc_file_flush(&vm->ferr, bc_flush_none); #endif // BC_DEBUG_CODE #if !BC_HAS_COMPUTED_GOTO switch (inst) #endif // !BC_HAS_COMPUTED_GOTO { #if BC_ENABLED // This just sets up the condition for the unconditional jump below, // which checks the condition, if necessary. // clang-format off BC_PROG_LBL(BC_INST_JUMP_ZERO): // clang-format on { bc_program_prep(p, &ptr, &num, 0); cond = !bc_num_cmpZero(num); bc_vec_pop(&p->results); BC_PROG_DIRECT_JUMP(BC_INST_JUMP) } // Fallthrough. BC_PROG_FALLTHROUGH // clang-format off BC_PROG_LBL(BC_INST_JUMP): // clang-format on { idx = bc_program_index(code, &ip->idx); // If a jump is required... if (inst == BC_INST_JUMP || cond) { // Get the address to jump to. size_t* addr = bc_vec_item(&func->labels, idx); // If this fails, then the parser failed to set up the // labels correctly. assert(*addr != SIZE_MAX); // Set the new address. ip->idx = *addr; } BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_CALL): // clang-format on { assert(BC_IS_BC); bc_program_call(p, code, &ip->idx); // Because we changed the execution stack and where we are // executing, we have to update all of this. BC_SIG_LOCK; ip = bc_vec_top(&p->stack); func = bc_vec_item(&p->fns, ip->func); code = func->code.v; BC_SIG_UNLOCK; BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_INC): BC_PROG_LBL(BC_INST_DEC): // clang-format on { bc_program_incdec(p, inst); BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_HALT): // clang-format on { vm->status = BC_STATUS_QUIT; // Just jump out. The jump series will take care of everything. BC_JMP; BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_RET): BC_PROG_LBL(BC_INST_RET0): BC_PROG_LBL(BC_INST_RET_VOID): // clang-format on { bc_program_return(p, inst); // Because we changed the execution stack and where we are // executing, we have to update all of this. BC_SIG_LOCK; ip = bc_vec_top(&p->stack); func = bc_vec_item(&p->fns, ip->func); code = func->code.v; BC_SIG_UNLOCK; BC_PROG_JUMP(inst, code, ip); } #endif // BC_ENABLED // clang-format off BC_PROG_LBL(BC_INST_BOOL_OR): BC_PROG_LBL(BC_INST_BOOL_AND): BC_PROG_LBL(BC_INST_REL_EQ): BC_PROG_LBL(BC_INST_REL_LE): BC_PROG_LBL(BC_INST_REL_GE): BC_PROG_LBL(BC_INST_REL_NE): BC_PROG_LBL(BC_INST_REL_LT): BC_PROG_LBL(BC_INST_REL_GT): // clang-format on { bc_program_logical(p, inst); BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_READ): // clang-format on { // We want to flush output before // this in case there is a prompt. bc_file_flush(&vm->fout, bc_flush_save); bc_program_read(p); // Because we changed the execution stack and where we are // executing, we have to update all of this. BC_SIG_LOCK; ip = bc_vec_top(&p->stack); func = bc_vec_item(&p->fns, ip->func); code = func->code.v; BC_SIG_UNLOCK; BC_PROG_JUMP(inst, code, ip); } #if BC_ENABLE_EXTRA_MATH // clang-format off BC_PROG_LBL(BC_INST_RAND): // clang-format on { bc_program_rand(p); BC_PROG_JUMP(inst, code, ip); } #endif // BC_ENABLE_EXTRA_MATH // clang-format off BC_PROG_LBL(BC_INST_MAXIBASE): BC_PROG_LBL(BC_INST_MAXOBASE): BC_PROG_LBL(BC_INST_MAXSCALE): #if BC_ENABLE_EXTRA_MATH BC_PROG_LBL(BC_INST_MAXRAND): #endif // BC_ENABLE_EXTRA_MATH // clang-format on { BcBigDig dig = vm->maxes[inst - BC_INST_MAXIBASE]; bc_program_pushBigdig(p, dig, BC_RESULT_TEMP); BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_LINE_LENGTH): #if BC_ENABLED BC_PROG_LBL(BC_INST_GLOBAL_STACKS): #endif // BC_ENABLED #if DC_ENABLED BC_PROG_LBL(BC_INST_EXTENDED_REGISTERS): #endif // DC_ENABLE BC_PROG_LBL(BC_INST_LEADING_ZERO): // clang-format on { bc_program_globalSetting(p, inst); BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_VAR): // clang-format on { bc_program_pushVar(p, code, &ip->idx, false, false); BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_ARRAY_ELEM): BC_PROG_LBL(BC_INST_ARRAY): // clang-format on { bc_program_pushArray(p, code, &ip->idx, inst); BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_IBASE): BC_PROG_LBL(BC_INST_SCALE): BC_PROG_LBL(BC_INST_OBASE): // clang-format on { bc_program_pushGlobal(p, inst); BC_PROG_JUMP(inst, code, ip); } #if BC_ENABLE_EXTRA_MATH // clang-format off BC_PROG_LBL(BC_INST_SEED): // clang-format on { bc_program_pushSeed(p); BC_PROG_JUMP(inst, code, ip); } #endif // BC_ENABLE_EXTRA_MATH // clang-format off BC_PROG_LBL(BC_INST_LENGTH): BC_PROG_LBL(BC_INST_SCALE_FUNC): BC_PROG_LBL(BC_INST_SQRT): BC_PROG_LBL(BC_INST_ABS): BC_PROG_LBL(BC_INST_IS_NUMBER): BC_PROG_LBL(BC_INST_IS_STRING): #if BC_ENABLE_EXTRA_MATH BC_PROG_LBL(BC_INST_IRAND): #endif // BC_ENABLE_EXTRA_MATH // clang-format on { bc_program_builtin(p, inst); BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_ASCIIFY): // clang-format on { bc_program_asciify(p); // Because we changed the execution stack and where we are // executing, we have to update all of this. BC_SIG_LOCK; ip = bc_vec_top(&p->stack); func = bc_vec_item(&p->fns, ip->func); code = func->code.v; BC_SIG_UNLOCK; BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_NUM): // clang-format on { bc_program_const(p, code, &ip->idx); BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_ZERO): BC_PROG_LBL(BC_INST_ONE): #if BC_ENABLED BC_PROG_LBL(BC_INST_LAST): #endif // BC_ENABLED // clang-format on { r.t = BC_RESULT_ZERO + (inst - BC_INST_ZERO); bc_vec_push(&p->results, &r); BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_PRINT): BC_PROG_LBL(BC_INST_PRINT_POP): #if BC_ENABLED BC_PROG_LBL(BC_INST_PRINT_STR): #endif // BC_ENABLED // clang-format on { bc_program_print(p, inst, 0); // We want to flush right away to save the output for history, // if history must preserve it when taking input. bc_file_flush(&vm->fout, bc_flush_save); BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_STR): // clang-format on { // Set up the result and push. r.t = BC_RESULT_STR; bc_num_clear(&r.d.n); r.d.n.scale = bc_program_index(code, &ip->idx); bc_vec_push(&p->results, &r); BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_POWER): BC_PROG_LBL(BC_INST_MULTIPLY): BC_PROG_LBL(BC_INST_DIVIDE): BC_PROG_LBL(BC_INST_MODULUS): BC_PROG_LBL(BC_INST_PLUS): BC_PROG_LBL(BC_INST_MINUS): #if BC_ENABLE_EXTRA_MATH BC_PROG_LBL(BC_INST_PLACES): BC_PROG_LBL(BC_INST_LSHIFT): BC_PROG_LBL(BC_INST_RSHIFT): #endif // BC_ENABLE_EXTRA_MATH // clang-format on { bc_program_op(p, inst); BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_NEG): BC_PROG_LBL(BC_INST_BOOL_NOT): #if BC_ENABLE_EXTRA_MATH BC_PROG_LBL(BC_INST_TRUNC): #endif // BC_ENABLE_EXTRA_MATH // clang-format on { bc_program_unary(p, inst); BC_PROG_JUMP(inst, code, ip); } // clang-format off #if BC_ENABLED BC_PROG_LBL(BC_INST_ASSIGN_POWER): BC_PROG_LBL(BC_INST_ASSIGN_MULTIPLY): BC_PROG_LBL(BC_INST_ASSIGN_DIVIDE): BC_PROG_LBL(BC_INST_ASSIGN_MODULUS): BC_PROG_LBL(BC_INST_ASSIGN_PLUS): BC_PROG_LBL(BC_INST_ASSIGN_MINUS): #if BC_ENABLE_EXTRA_MATH BC_PROG_LBL(BC_INST_ASSIGN_PLACES): BC_PROG_LBL(BC_INST_ASSIGN_LSHIFT): BC_PROG_LBL(BC_INST_ASSIGN_RSHIFT): #endif // BC_ENABLE_EXTRA_MATH BC_PROG_LBL(BC_INST_ASSIGN): BC_PROG_LBL(BC_INST_ASSIGN_POWER_NO_VAL): BC_PROG_LBL(BC_INST_ASSIGN_MULTIPLY_NO_VAL): BC_PROG_LBL(BC_INST_ASSIGN_DIVIDE_NO_VAL): BC_PROG_LBL(BC_INST_ASSIGN_MODULUS_NO_VAL): BC_PROG_LBL(BC_INST_ASSIGN_PLUS_NO_VAL): BC_PROG_LBL(BC_INST_ASSIGN_MINUS_NO_VAL): #if BC_ENABLE_EXTRA_MATH BC_PROG_LBL(BC_INST_ASSIGN_PLACES_NO_VAL): BC_PROG_LBL(BC_INST_ASSIGN_LSHIFT_NO_VAL): BC_PROG_LBL(BC_INST_ASSIGN_RSHIFT_NO_VAL): #endif // BC_ENABLE_EXTRA_MATH #endif // BC_ENABLED BC_PROG_LBL(BC_INST_ASSIGN_NO_VAL): // clang-format on { bc_program_assign(p, inst); BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_POP): // clang-format on { #ifndef BC_PROG_NO_STACK_CHECK // dc must do a stack check, but bc does not. if (BC_IS_DC) { if (BC_ERR(!BC_PROG_STACK(&p->results, 1))) { bc_err(BC_ERR_EXEC_STACK); } } #endif // BC_PROG_NO_STACK_CHECK assert(BC_PROG_STACK(&p->results, 1)); bc_vec_pop(&p->results); BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_SWAP): // clang-format on { BcResult* ptr2; // Check the stack. if (BC_ERR(!BC_PROG_STACK(&p->results, 2))) { bc_err(BC_ERR_EXEC_STACK); } assert(BC_PROG_STACK(&p->results, 2)); // Get the two items. ptr = bc_vec_item_rev(&p->results, 0); ptr2 = bc_vec_item_rev(&p->results, 1); // Swap. It's just easiest to do it this way. // NOLINTNEXTLINE memcpy(&r, ptr, sizeof(BcResult)); // NOLINTNEXTLINE memcpy(ptr, ptr2, sizeof(BcResult)); // NOLINTNEXTLINE memcpy(ptr2, &r, sizeof(BcResult)); BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_MODEXP): // clang-format on { bc_program_modexp(p); BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_DIVMOD): // clang-format on { bc_program_divmod(p); BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_PRINT_STREAM): // clang-format on { bc_program_printStream(p); BC_PROG_JUMP(inst, code, ip); } #if DC_ENABLED // clang-format off BC_PROG_LBL(BC_INST_POP_EXEC): // clang-format on { // If this fails, the dc parser got something wrong. assert(BC_PROG_STACK(&p->stack, 2)); // Pop the execution stack and tail call stack. bc_vec_pop(&p->stack); bc_vec_pop(&p->tail_calls); // Because we changed the execution stack and where we are // executing, we have to update all of this. BC_SIG_LOCK; ip = bc_vec_top(&p->stack); func = bc_vec_item(&p->fns, ip->func); code = func->code.v; BC_SIG_UNLOCK; BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_EXECUTE): BC_PROG_LBL(BC_INST_EXEC_COND): // clang-format on { cond = (inst == BC_INST_EXEC_COND); bc_program_execStr(p, code, &ip->idx, cond, func->code.len); // Because we changed the execution stack and where we are // executing, we have to update all of this. BC_SIG_LOCK; ip = bc_vec_top(&p->stack); func = bc_vec_item(&p->fns, ip->func); code = func->code.v; BC_SIG_UNLOCK; BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_PRINT_STACK): // clang-format on { bc_program_printStack(p); BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_CLEAR_STACK): // clang-format on { bc_vec_popAll(&p->results); BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_REG_STACK_LEN): // clang-format on { bc_program_regStackLen(p, code, &ip->idx); BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_STACK_LEN): // clang-format on { bc_program_stackLen(p); BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_DUPLICATE): // clang-format on { // Check the stack. if (BC_ERR(!BC_PROG_STACK(&p->results, 1))) { bc_err(BC_ERR_EXEC_STACK); } assert(BC_PROG_STACK(&p->results, 1)); // Get the top of the stack. ptr = bc_vec_top(&p->results); BC_SIG_LOCK; // Copy and push. bc_result_copy(&r, ptr); bc_vec_push(&p->results, &r); BC_SIG_UNLOCK; BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_LOAD): BC_PROG_LBL(BC_INST_PUSH_VAR): // clang-format on { bool copy = (inst == BC_INST_LOAD); bc_program_pushVar(p, code, &ip->idx, true, copy); BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_PUSH_TO_VAR): // clang-format on { idx = bc_program_index(code, &ip->idx); bc_program_copyToVar(p, idx, BC_TYPE_VAR); BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_QUIT): BC_PROG_LBL(BC_INST_NQUIT): // clang-format on { bc_program_nquit(p, inst); // Because we changed the execution stack and where we are // executing, we have to update all of this. BC_SIG_LOCK; ip = bc_vec_top(&p->stack); func = bc_vec_item(&p->fns, ip->func); code = func->code.v; BC_SIG_UNLOCK; BC_PROG_JUMP(inst, code, ip); } // clang-format off BC_PROG_LBL(BC_INST_EXEC_STACK_LEN): // clang-format on { bc_program_execStackLen(p); BC_PROG_JUMP(inst, code, ip); } #endif // DC_ENABLED #if BC_HAS_COMPUTED_GOTO // clang-format off BC_PROG_LBL(BC_INST_INVALID): // clang-format on { goto end; } #else // BC_HAS_COMPUTED_GOTO default: { BC_UNREACHABLE #if BC_DEBUG && !BC_CLANG abort(); #endif // BC_DEBUG && !BC_CLANG } #endif // BC_HAS_COMPUTED_GOTO } #if BC_HAS_COMPUTED_GOTO #if BC_CLANG #pragma clang diagnostic warning "-Wgnu-label-as-value" #endif // BC_CLANG #if BC_GCC #pragma GCC diagnostic warning "-Wpedantic" #endif // BC_GCC #else // BC_HAS_COMPUTED_GOTO #if BC_DEBUG // This is to allow me to use a debugger to see the last instruction, // which will point to which function was the problem. But it's also a // good smoke test for error handling changes. assert(jmp_bufs_len == vm->jmp_bufs.len); #endif // BC_DEBUG #endif // BC_HAS_COMPUTED_GOTO } end: BC_SIG_MAYLOCK; // This is here just to print a stack trace on interrupts. This is for // finding infinite loops. if (BC_SIG_INTERRUPT(vm)) { BcStatus s; bc_file_putchar(&vm->ferr, bc_flush_none, '\n'); bc_program_printStackTrace(p); s = bc_file_flushErr(&vm->ferr, bc_flush_err); if (BC_ERR(s != BC_STATUS_SUCCESS && vm->status == BC_STATUS_SUCCESS)) { vm->status = (sig_atomic_t) s; } } BC_LONGJMP_CONT(vm); } #if BC_DEBUG_CODE #if BC_ENABLED && DC_ENABLED void bc_program_printStackDebug(BcProgram* p) { bc_file_puts(&vm->fout, bc_flush_err, "-------------- Stack ----------\n"); bc_program_printStack(p); bc_file_puts(&vm->fout, bc_flush_err, "-------------- Stack End ------\n"); } static void bc_program_printIndex(const char* restrict code, size_t* restrict bgn) { uchar byte, i, bytes = (uchar) code[(*bgn)++]; ulong val = 0; for (byte = 1, i = 0; byte && i < bytes; ++i) { byte = (uchar) code[(*bgn)++]; if (byte) val |= ((ulong) byte) << (CHAR_BIT * i); } bc_vm_printf(" (%lu) ", val); } static void bc_program_printStr(const BcProgram* p, const char* restrict code, size_t* restrict bgn) { size_t idx = bc_program_index(code, bgn); char* s; s = *((char**) bc_vec_item(p->strs, idx)); bc_vm_printf(" (\"%s\") ", s); } void bc_program_printInst(const BcProgram* p, const char* restrict code, size_t* restrict bgn) { uchar inst = (uchar) code[(*bgn)++]; bc_vm_printf("Inst[%zu]: %s [%lu]; ", *bgn - 1, bc_inst_names[inst], (unsigned long) inst); if (inst == BC_INST_VAR || inst == BC_INST_ARRAY_ELEM || inst == BC_INST_ARRAY) { bc_program_printIndex(code, bgn); } else if (inst == BC_INST_STR) bc_program_printStr(p, code, bgn); else if (inst == BC_INST_NUM) { size_t idx = bc_program_index(code, bgn); BcConst* c = bc_vec_item(p->consts, idx); bc_vm_printf("(%s)", c->val); } else if (inst == BC_INST_CALL || (inst > BC_INST_STR && inst <= BC_INST_JUMP_ZERO)) { bc_program_printIndex(code, bgn); if (inst == BC_INST_CALL) bc_program_printIndex(code, bgn); } bc_vm_putchar('\n', bc_flush_err); } void bc_program_code(const BcProgram* p) { BcFunc* f; char* code; BcInstPtr ip; size_t i; for (i = 0; i < p->fns.len; ++i) { ip.idx = ip.len = 0; ip.func = i; f = bc_vec_item(&p->fns, ip.func); code = f->code.v; bc_vm_printf("func[%zu]:\n", ip.func); while (ip.idx < f->code.len) { bc_program_printInst(p, code, &ip.idx); } bc_file_puts(&vm->fout, bc_flush_err, "\n\n"); } } #endif // BC_ENABLED && DC_ENABLED #endif // BC_DEBUG_CODE diff --git a/contrib/bc/src/vm.c b/contrib/bc/src/vm.c index 3a7913e30c86..29c2715d0271 100644 --- a/contrib/bc/src/vm.c +++ b/contrib/bc/src/vm.c @@ -1,1797 +1,1799 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2023 Gavin D. Howard and contributors. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * ***************************************************************************** * * Code common to all of bc and dc. * */ #include #include #include #include #include #include #include #ifndef _WIN32 #include #include #include #else // _WIN32 #define WIN32_LEAN_AND_MEAN #include #include #endif // _WIN32 #include #include #include #include #include #include #if BC_ENABLE_LIBRARY #include #endif // BC_ENABLE_LIBRARY #if !BC_ENABLE_LIBRARY // The actual globals. char output_bufs[BC_VM_BUF_SIZE]; BcVm vm_data; BcVm* vm = &vm_data; #endif // !BC_ENABLE_LIBRARY #if BC_DEBUG_CODE BC_NORETURN void bc_vm_jmp(const char* f) { #else // BC_DEBUG_CODE BC_NORETURN void bc_vm_jmp(void) { #endif #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY assert(BC_SIG_EXC(vm)); BC_SIG_MAYLOCK; #if BC_DEBUG_CODE bc_file_puts(&vm->ferr, bc_flush_none, "Longjmp: "); bc_file_puts(&vm->ferr, bc_flush_none, f); bc_file_putchar(&vm->ferr, bc_flush_none, '\n'); bc_file_flush(&vm->ferr, bc_flush_none); #endif // BC_DEBUG_CODE #if BC_DEBUG assert(vm->jmp_bufs.len - (size_t) vm->sig_pop); #endif // BC_DEBUG if (vm->jmp_bufs.len == 0) abort(); if (vm->sig_pop) bc_vec_pop(&vm->jmp_bufs); else vm->sig_pop = 1; siglongjmp(*((sigjmp_buf*) bc_vec_top(&vm->jmp_bufs)), 1); } #if !BC_ENABLE_LIBRARY /** * Handles signals. This is the signal handler. * @param sig The signal to handle. */ static void bc_vm_sig(int sig) { #if BC_ENABLE_EDITLINE // Editline needs this to resize the terminal. This also needs to come first // because a resize always needs to happen. if (sig == SIGWINCH) { if (BC_TTY) { el_resize(vm->history.el); // If the signal was a SIGWINCH, clear it because we don't need to // print a stack trace in that case. if (vm->sig == SIGWINCH) { vm->sig = 0; } } return; } #endif // BC_ENABLE_EDITLINE // There is already a signal in flight if this is true. if (vm->status == (sig_atomic_t) BC_STATUS_QUIT || vm->sig != 0) { if (!BC_I || sig != SIGINT) vm->status = BC_STATUS_QUIT; return; } // We always want to set this because a stack trace can be printed if we do. vm->sig = sig; // Only reset under these conditions; otherwise, quit. if (sig == SIGINT && BC_SIGINT && BC_I) { int err = errno; #if BC_ENABLE_EDITLINE // Editline needs this, for some unknown reason. if (write(STDOUT_FILENO, "^C", 2) != (ssize_t) 2) { vm->status = BC_STATUS_ERROR_FATAL; } #endif // BC_ENABLE_EDITLINE // Write the message. if (write(STDOUT_FILENO, vm->sigmsg, vm->siglen) != (ssize_t) vm->siglen) { vm->status = BC_STATUS_ERROR_FATAL; } errno = err; } else { #if BC_ENABLE_EDITLINE if (write(STDOUT_FILENO, "^C", 2) != (ssize_t) 2) { vm->status = BC_STATUS_ERROR_FATAL; return; } #endif // BC_ENABLE_EDITLINE vm->status = BC_STATUS_QUIT; } #if BC_ENABLE_LINE_LIB // Readline and Editline need this to actually handle sigints correctly. if (sig == SIGINT && bc_history_inlinelib) { bc_history_inlinelib = 0; siglongjmp(bc_history_jmpbuf, 1); } #endif // BC_ENABLE_LINE_LIB assert(vm->jmp_bufs.len); // Only jump if signals are not locked. The jump will happen by whoever // unlocks signals. if (!vm->sig_lock) BC_JMP; } /** * Sets up signal handling. */ static void bc_vm_sigaction(void) { #ifndef _WIN32 struct sigaction sa; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; // This mess is to silence a warning on Clang with regards to glibc's // sigaction handler, which activates the warning here. #if BC_CLANG #pragma clang diagnostic ignored "-Wdisabled-macro-expansion" #endif // BC_CLANG sa.sa_handler = bc_vm_sig; #if BC_CLANG #pragma clang diagnostic warning "-Wdisabled-macro-expansion" #endif // BC_CLANG sigaction(SIGTERM, &sa, NULL); sigaction(SIGQUIT, &sa, NULL); sigaction(SIGINT, &sa, NULL); #if BC_ENABLE_EDITLINE // Editline needs this to resize the terminal. if (BC_TTY) sigaction(SIGWINCH, &sa, NULL); #endif // BC_ENABLE_EDITLINE #if BC_ENABLE_HISTORY if (BC_TTY) sigaction(SIGHUP, &sa, NULL); #endif // BC_ENABLE_HISTORY #else // _WIN32 signal(SIGTERM, bc_vm_sig); signal(SIGINT, bc_vm_sig); #endif // _WIN32 } void bc_vm_info(const char* const help) { BC_SIG_ASSERT_LOCKED; // Print the banner. bc_file_printf(&vm->fout, "%s %s\n%s", vm->name, BC_VERSION, bc_copyright); // Print the help. if (help != NULL) { bc_file_putchar(&vm->fout, bc_flush_none, '\n'); #if BC_ENABLED if (BC_IS_BC) { const char* const banner = BC_DEFAULT_BANNER ? "to" : "to not"; const char* const sigint = BC_DEFAULT_SIGINT_RESET ? "to reset" : "to exit"; const char* const tty = BC_DEFAULT_TTY_MODE ? "enabled" : "disabled"; const char* const prompt = BC_DEFAULT_PROMPT ? "enabled" : "disabled"; const char* const expr = BC_DEFAULT_EXPR_EXIT ? "to exit" : "to not exit"; const char* const clamp = BC_DEFAULT_DIGIT_CLAMP ? "to clamp" : "to not clamp"; bc_file_printf(&vm->fout, help, vm->name, vm->name, BC_VERSION, BC_BUILD_TYPE, banner, sigint, tty, prompt, expr, clamp); } #endif // BC_ENABLED #if DC_ENABLED if (BC_IS_DC) { const char* const sigint = DC_DEFAULT_SIGINT_RESET ? "to reset" : "to exit"; const char* const tty = DC_DEFAULT_TTY_MODE ? "enabled" : "disabled"; const char* const prompt = DC_DEFAULT_PROMPT ? "enabled" : "disabled"; const char* const expr = DC_DEFAULT_EXPR_EXIT ? "to exit" : "to not exit"; const char* const clamp = DC_DEFAULT_DIGIT_CLAMP ? "to clamp" : "to not clamp"; bc_file_printf(&vm->fout, help, vm->name, vm->name, BC_VERSION, BC_BUILD_TYPE, sigint, tty, prompt, expr, clamp); } #endif // DC_ENABLED } // Flush. bc_file_flush(&vm->fout, bc_flush_none); } #endif // !BC_ENABLE_LIBRARY #if !BC_ENABLE_LIBRARY && !BC_ENABLE_MEMCHECK BC_NORETURN #endif // !BC_ENABLE_LIBRARY && !BC_ENABLE_MEMCHECK void bc_vm_fatalError(BcErr e) { bc_err(e); #if !BC_ENABLE_LIBRARY && !BC_ENABLE_MEMCHECK BC_UNREACHABLE #if !BC_CLANG abort(); #endif // !BC_CLANG #endif // !BC_ENABLE_LIBRARY && !BC_ENABLE_MEMCHECK } #if BC_ENABLE_LIBRARY BC_NORETURN void bc_vm_handleError(BcErr e) { #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY assert(e < BC_ERR_NELEMS); assert(!vm->sig_pop); BC_SIG_LOCK; // If we have a normal error... if (e <= BC_ERR_MATH_DIVIDE_BY_ZERO) { // Set the error. vm->err = (BclError) (e - BC_ERR_MATH_NEGATIVE + BCL_ERROR_MATH_NEGATIVE); } // Abort if we should. else if (vm->abrt) abort(); else if (e == BC_ERR_FATAL_ALLOC_ERR) vm->err = BCL_ERROR_FATAL_ALLOC_ERR; else vm->err = BCL_ERROR_FATAL_UNKNOWN_ERR; BC_JMP; } #else // BC_ENABLE_LIBRARY #if BC_DEBUG void bc_vm_handleError(BcErr e, const char* file, int fline, size_t line, ...) #else // BC_DEBUG void bc_vm_handleError(BcErr e, size_t line, ...) #endif // BC_DEBUG { BcStatus s; va_list args; uchar id = bc_err_ids[e]; const char* err_type = vm->err_ids[id]; sig_atomic_t lock; assert(e < BC_ERR_NELEMS); assert(!vm->sig_pop); #if BC_ENABLED // Figure out if the POSIX error should be an error, a warning, or nothing. if (!BC_S && e >= BC_ERR_POSIX_START) { if (BC_W) { // Make sure to not return an error. id = UCHAR_MAX; err_type = vm->err_ids[BC_ERR_IDX_WARN]; } else return; } #endif // BC_ENABLED BC_SIG_TRYLOCK(lock); // Make sure all of stdout is written first. s = bc_file_flushErr(&vm->fout, bc_flush_err); // Just jump out if the flush failed; there's nothing we can do. if (BC_ERR(s == BC_STATUS_ERROR_FATAL)) { vm->status = (sig_atomic_t) s; BC_JMP; } // Print the error message. va_start(args, line); bc_file_putchar(&vm->ferr, bc_flush_none, '\n'); bc_file_puts(&vm->ferr, bc_flush_none, err_type); bc_file_putchar(&vm->ferr, bc_flush_none, ' '); bc_file_vprintf(&vm->ferr, vm->err_msgs[e], args); va_end(args); // Print the extra information if we have it. if (BC_NO_ERR(vm->file != NULL)) { // This is the condition for parsing vs runtime. // If line is not 0, it is parsing. if (line) { bc_file_puts(&vm->ferr, bc_flush_none, "\n "); bc_file_puts(&vm->ferr, bc_flush_none, vm->file); bc_file_printf(&vm->ferr, ":%zu\n", line); } else { // Print a stack trace. bc_file_putchar(&vm->ferr, bc_flush_none, '\n'); bc_program_printStackTrace(&vm->prog); } } else { bc_file_putchar(&vm->ferr, bc_flush_none, '\n'); } #if BC_DEBUG bc_file_printf(&vm->ferr, "\n %s:%d\n", file, fline); #endif // BC_DEBUG bc_file_puts(&vm->ferr, bc_flush_none, "\n"); s = bc_file_flushErr(&vm->ferr, bc_flush_err); #if !BC_ENABLE_MEMCHECK // Because this function is called by a BC_NORETURN function when fatal // errors happen, we need to make sure to exit on fatal errors. This will // be faster anyway. This function *cannot jump when a fatal error occurs!* if (BC_ERR(id == BC_ERR_IDX_FATAL || s == BC_STATUS_ERROR_FATAL)) { exit(bc_vm_atexit((int) BC_STATUS_ERROR_FATAL)); } #else // !BC_ENABLE_MEMCHECK if (BC_ERR(s == BC_STATUS_ERROR_FATAL)) vm->status = (sig_atomic_t) s; else #endif // !BC_ENABLE_MEMCHECK { vm->status = (sig_atomic_t) (uchar) (id + 1); } // Only jump if there is an error. if (BC_ERR(vm->status)) BC_JMP; BC_SIG_TRYUNLOCK(lock); } char* bc_vm_getenv(const char* var) { char* ret; #ifndef _WIN32 ret = getenv(var); #else // _WIN32 _dupenv_s(&ret, NULL, var); #endif // _WIN32 return ret; } void bc_vm_getenvFree(char* val) { BC_UNUSED(val); #ifdef _WIN32 free(val); #endif // _WIN32 } /** * Sets a flag from an environment variable and the default. * @param var The environment variable. * @param def The default. * @param flag The flag to set. */ static void bc_vm_setenvFlag(const char* const var, int def, uint16_t flag) { // Get the value. char* val = bc_vm_getenv(var); // If there is no value... if (val == NULL) { // Set the default. if (def) vm->flags |= flag; else vm->flags &= ~(flag); } // Parse the value. else if (strtoul(val, NULL, 0)) vm->flags |= flag; else vm->flags &= ~(flag); bc_vm_getenvFree(val); } /** * Parses the arguments in {B,D]C_ENV_ARGS. * @param env_args_name The environment variable to use. * @param scale A pointer to return the scale that the arguments set, * if any. * @param ibase A pointer to return the ibase that the arguments set, * if any. * @param obase A pointer to return the obase that the arguments set, * if any. */ static void bc_vm_envArgs(const char* const env_args_name, BcBigDig* scale, BcBigDig* ibase, BcBigDig* obase) { char *env_args = bc_vm_getenv(env_args_name), *buf, *start; char instr = '\0'; BC_SIG_ASSERT_LOCKED; if (env_args == NULL) return; // Windows already allocates, so we don't need to. #ifndef _WIN32 start = buf = vm->env_args_buffer = bc_vm_strdup(env_args); #else // _WIN32 start = buf = vm->env_args_buffer = env_args; #endif // _WIN32 assert(buf != NULL); // Create two buffers for parsing. These need to stay throughout the entire // execution of bc, unfortunately, because of filenames that might be in // there. bc_vec_init(&vm->env_args, sizeof(char*), BC_DTOR_NONE); bc_vec_push(&vm->env_args, &env_args_name); // While we haven't reached the end of the args... while (*buf) { // If we don't have whitespace... if (!isspace(*buf)) { // If we have the start of a string... if (*buf == '"' || *buf == '\'') { // Set stuff appropriately. instr = *buf; buf += 1; // Check for the empty string. if (*buf == instr) { instr = '\0'; buf += 1; continue; } } // Push the pointer to the args buffer. bc_vec_push(&vm->env_args, &buf); // Parse the string. while (*buf && ((!instr && !isspace(*buf)) || (instr && *buf != instr))) { buf += 1; } // If we did find the end of the string... if (*buf) { if (instr) instr = '\0'; // Reset stuff. *buf = '\0'; buf += 1; start = buf; } else if (instr) bc_error(BC_ERR_FATAL_OPTION, 0, start); } // If we have whitespace, eat it. else buf += 1; } // Make sure to push a NULL pointer at the end. buf = NULL; bc_vec_push(&vm->env_args, &buf); // Parse the arguments. bc_args((int) vm->env_args.len - 1, bc_vec_item(&vm->env_args, 0), false, scale, ibase, obase); } /** * Gets the {B,D}C_LINE_LENGTH. * @param var The environment variable to pull it from. * @return The line length. */ static size_t bc_vm_envLen(const char* var) { char* lenv = bc_vm_getenv(var); size_t i, len = BC_NUM_PRINT_WIDTH; int num; // Return the default with none. if (lenv == NULL) return len; len = strlen(lenv); // Figure out if it's a number. for (num = 1, i = 0; num && i < len; ++i) { num = isdigit(lenv[i]); } // If it is a number... if (num) { // Parse it and clamp it if needed. len = (size_t) atoi(lenv) - 1; if (len == 1 || len >= UINT16_MAX) len = BC_NUM_PRINT_WIDTH; } // Set the default. else len = BC_NUM_PRINT_WIDTH; bc_vm_getenvFree(lenv); return len; } #endif // BC_ENABLE_LIBRARY void bc_vm_shutdown(void) { BC_SIG_ASSERT_LOCKED; #if BC_ENABLE_NLS if (vm->catalog != BC_VM_INVALID_CATALOG) catclose(vm->catalog); #endif // BC_ENABLE_NLS +#if !BC_ENABLE_LIBRARY #if BC_ENABLE_HISTORY // This must always run to ensure that the terminal is back to normal, i.e., // has raw mode disabled. But we should only do it if we did not have a bad // terminal because history was not initialized if it is a bad terminal. if (BC_TTY && !vm->history.badTerm) bc_history_free(&vm->history); #endif // BC_ENABLE_HISTORY +#endif // !BC_ENABLE_LIBRARY #if BC_DEBUG #if !BC_ENABLE_LIBRARY bc_vec_free(&vm->env_args); free(vm->env_args_buffer); bc_vec_free(&vm->files); bc_vec_free(&vm->exprs); if (BC_PARSE_IS_INITED(&vm->read_prs, &vm->prog)) { bc_vec_free(&vm->read_buf); bc_parse_free(&vm->read_prs); } bc_parse_free(&vm->prs); bc_program_free(&vm->prog); bc_slabvec_free(&vm->slabs); #endif // !BC_ENABLE_LIBRARY bc_vm_freeTemps(); #endif // BC_DEBUG #if !BC_ENABLE_LIBRARY // We always want to flush. bc_file_free(&vm->fout); bc_file_free(&vm->ferr); #endif // !BC_ENABLE_LIBRARY } void bc_vm_addTemp(BcDig* num) { #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY BC_SIG_ASSERT_LOCKED; // If we don't have room, just free. if (vm->temps_len == BC_VM_MAX_TEMPS) free(num); else { // Add to the buffer and length. vm->temps_buf[vm->temps_len] = num; vm->temps_len += 1; } } BcDig* bc_vm_takeTemp(void) { #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY BC_SIG_ASSERT_LOCKED; if (!vm->temps_len) return NULL; vm->temps_len -= 1; return vm->temps_buf[vm->temps_len]; } BcDig* bc_vm_getTemp(void) { #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY BC_SIG_ASSERT_LOCKED; if (!vm->temps_len) return NULL; return vm->temps_buf[vm->temps_len - 1]; } void bc_vm_freeTemps(void) { size_t i; #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY BC_SIG_ASSERT_LOCKED; if (!vm->temps_len) return; // Free them all... for (i = 0; i < vm->temps_len; ++i) { free(vm->temps_buf[i]); } vm->temps_len = 0; } #if !BC_ENABLE_LIBRARY size_t bc_vm_numDigits(size_t val) { size_t digits = 0; do { digits += 1; val /= 10; } while (val != 0); return digits; } #endif // !BC_ENABLE_LIBRARY inline size_t bc_vm_arraySize(size_t n, size_t size) { size_t res = n * size; if (BC_ERR(BC_VM_MUL_OVERFLOW(n, size, res))) { bc_vm_fatalError(BC_ERR_FATAL_ALLOC_ERR); } return res; } inline size_t bc_vm_growSize(size_t a, size_t b) { size_t res = a + b; if (BC_ERR(res >= SIZE_MAX || res < a)) { bc_vm_fatalError(BC_ERR_FATAL_ALLOC_ERR); } return res; } void* bc_vm_malloc(size_t n) { void* ptr; BC_SIG_ASSERT_LOCKED; ptr = malloc(n); if (BC_ERR(ptr == NULL)) { bc_vm_freeTemps(); ptr = malloc(n); if (BC_ERR(ptr == NULL)) bc_vm_fatalError(BC_ERR_FATAL_ALLOC_ERR); } return ptr; } void* bc_vm_realloc(void* ptr, size_t n) { void* temp; BC_SIG_ASSERT_LOCKED; temp = realloc(ptr, n); if (BC_ERR(temp == NULL)) { bc_vm_freeTemps(); temp = realloc(ptr, n); if (BC_ERR(temp == NULL)) bc_vm_fatalError(BC_ERR_FATAL_ALLOC_ERR); } return temp; } char* bc_vm_strdup(const char* str) { char* s; BC_SIG_ASSERT_LOCKED; s = strdup(str); if (BC_ERR(s == NULL)) { bc_vm_freeTemps(); s = strdup(str); if (BC_ERR(s == NULL)) bc_vm_fatalError(BC_ERR_FATAL_ALLOC_ERR); } return s; } #if !BC_ENABLE_LIBRARY void bc_vm_printf(const char* fmt, ...) { va_list args; #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #else // BC_ENABLE_LIBRARY sig_atomic_t lock; #endif // BC_ENABLE_LIBRARY BC_SIG_TRYLOCK(lock); va_start(args, fmt); bc_file_vprintf(&vm->fout, fmt, args); va_end(args); vm->nchars = 0; BC_SIG_TRYUNLOCK(lock); } #endif // !BC_ENABLE_LIBRARY void bc_vm_putchar(int c, BcFlushType type) { #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); bc_vec_pushByte(&vm->out, (uchar) c); #else // BC_ENABLE_LIBRARY bc_file_putchar(&vm->fout, type, (uchar) c); vm->nchars = (c == '\n' ? 0 : vm->nchars + 1); #endif // BC_ENABLE_LIBRARY } #if !BC_ENABLE_LIBRARY #ifdef __OpenBSD__ /** * Aborts with a message. This should never be called because I have carefully * made sure that the calls to pledge() and unveil() are correct, but it's here * just in case. * @param msg The message to print. */ BC_NORETURN static void bc_abortm(const char* msg) { bc_file_puts(&vm->ferr, bc_flush_none, msg); bc_file_puts(&vm->ferr, bc_flush_none, "; this is a bug"); bc_file_flush(&vm->ferr, bc_flush_none); abort(); } void bc_pledge(const char* promises, const char* execpromises) { int r = pledge(promises, execpromises); if (r) bc_abortm("pledge() failed"); } #if BC_ENABLE_EXTRA_MATH /** * A convenience and portability function for OpenBSD's unveil(). * @param path The path. * @param permissions The permissions for the path. */ static void bc_unveil(const char* path, const char* permissions) { int r = unveil(path, permissions); if (r) bc_abortm("unveil() failed"); } #endif // BC_ENABLE_EXTRA_MATH #else // __OpenBSD__ void bc_pledge(const char* promises, const char* execpromises) { BC_UNUSED(promises); BC_UNUSED(execpromises); } #if BC_ENABLE_EXTRA_MATH static void bc_unveil(const char* path, const char* permissions) { BC_UNUSED(path); BC_UNUSED(permissions); } #endif // BC_ENABLE_EXTRA_MATH #endif // __OpenBSD__ /** * Cleans unneeded variables, arrays, functions, strings, and constants when * done executing a line of stdin. This is to prevent memory usage growing * without bound. This is an idea from busybox. */ static void bc_vm_clean(void) { BcVec* fns = &vm->prog.fns; BcFunc* f = bc_vec_item(fns, BC_PROG_MAIN); BcInstPtr* ip = bc_vec_item(&vm->prog.stack, 0); bool good = ((vm->status && vm->status != BC_STATUS_QUIT) || vm->sig != 0); BC_SIG_ASSERT_LOCKED; // If all is good, go ahead and reset. if (good) bc_program_reset(&vm->prog); #if BC_ENABLED // bc has this extra condition. If it not satisfied, it is in the middle of // a parse. if (good && BC_IS_BC) good = !BC_PARSE_NO_EXEC(&vm->prs); #endif // BC_ENABLED #if DC_ENABLED // For dc, it is safe only when all of the results on the results stack are // safe, which means that they are temporaries or other things that don't // need strings or constants. if (BC_IS_DC) { size_t i; good = true; for (i = 0; good && i < vm->prog.results.len; ++i) { BcResult* r = (BcResult*) bc_vec_item(&vm->prog.results, i); good = BC_VM_SAFE_RESULT(r); } } #endif // DC_ENABLED // If this condition is true, we can get rid of strings, // constants, and code. if (good && vm->prog.stack.len == 1 && ip->idx == f->code.len) { // XXX: Nothing can be popped in dc. Deal with it. #if BC_ENABLED if (BC_IS_BC) { // XXX: you cannot delete strings, functions, or constants in bc. // Deal with it. bc_vec_popAll(&f->labels); } #endif // BC_ENABLED bc_vec_popAll(&f->code); ip->idx = 0; } } /** * Process a bunch of text. * @param text The text to process. * @param mode The mode to process in. */ static void bc_vm_process(const char* text, BcMode mode) { // Set up the parser. bc_parse_text(&vm->prs, text, mode); while (vm->prs.l.t != BC_LEX_EOF) { // Parsing requires a signal lock. We also don't parse everything; we // want to execute as soon as possible for *everything*. BC_SIG_LOCK; vm->parse(&vm->prs); BC_SIG_UNLOCK; // Execute if possible. if (BC_IS_DC || !BC_PARSE_NO_EXEC(&vm->prs)) bc_program_exec(&vm->prog); assert(BC_IS_DC || vm->prog.results.len == 0); // Flush in interactive mode. if (BC_I) bc_file_flush(&vm->fout, bc_flush_save); } } #if BC_ENABLED /** * Ends a series of if statements. This is to ensure that full parses happen * when a file finishes or stdin has no more data. Without this, bc thinks that * it cannot parse any further. But if we reach the end of a file or stdin has * no more data, we know we can add an empty else clause. */ static void bc_vm_endif(void) { bc_parse_endif(&vm->prs); bc_program_exec(&vm->prog); } #endif // BC_ENABLED /** * Processes a file. * @param file The filename. */ static void bc_vm_file(const char* file) { char* data = NULL; #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY assert(!vm->sig_pop); vm->mode = BC_MODE_FILE; // Set up the lexer. bc_lex_file(&vm->prs.l, file); BC_SIG_LOCK; // Read the file. data = bc_read_file(file); assert(data != NULL); BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; // Process it. bc_vm_process(data, BC_MODE_FILE); #if BC_ENABLED // Make sure to end any open if statements. if (BC_IS_BC) bc_vm_endif(); #endif // BC_ENABLED err: BC_SIG_MAYLOCK; // Cleanup. free(data); bc_vm_clean(); // bc_program_reset(), called by bc_vm_clean(), resets the status. // We want it to clear the sig_pop variable in case it was set. if (vm->status == (sig_atomic_t) BC_STATUS_SUCCESS) BC_LONGJMP_STOP; BC_LONGJMP_CONT(vm); } bool bc_vm_readLine(bool clear) { BcStatus s; bool good; BC_SIG_ASSERT_NOT_LOCKED; // Clear the buffer if desired. if (clear) bc_vec_empty(&vm->buffer); // Empty the line buffer. bc_vec_empty(&vm->line_buf); if (vm->eof) return false; do { // bc_read_line() must always return either BC_STATUS_SUCCESS or // BC_STATUS_EOF. Everything else, it and whatever it calls, must jump // out instead. s = bc_read_line(&vm->line_buf, ">>> "); vm->eof = (s == BC_STATUS_EOF); } while (s == BC_STATUS_SUCCESS && !vm->eof && vm->line_buf.len < 1); good = (vm->line_buf.len > 1); // Concat if we found something. if (good) bc_vec_concat(&vm->buffer, vm->line_buf.v); return good; } /** * Processes text from stdin. */ static void bc_vm_stdin(void) { bool clear; #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY clear = true; vm->mode = BC_MODE_STDIN; // Set up the lexer. bc_lex_file(&vm->prs.l, bc_program_stdin_name); // These are global so that the lexers can access them, but they are // allocated and freed in this function because they should only be used for // stdin and expressions (they are used in bc_vm_exprs() as well). So they // are tied to this function, really. Well, this and bc_vm_readLine(). These // are the reasons that we have vm->is_stdin to tell the lexers if we are // reading from stdin. Well, both lexers care. And the reason they care is // so that if a comment or a string goes across multiple lines, the lexer // can request more data from stdin until the comment or string is ended. BC_SIG_LOCK; bc_vec_init(&vm->buffer, sizeof(uchar), BC_DTOR_NONE); bc_vec_init(&vm->line_buf, sizeof(uchar), BC_DTOR_NONE); BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; // This label exists because errors can cause jumps to end up at the err label // below. If that happens, and the error should be cleared and execution // continue, then we need to jump back. restart: // While we still read data from stdin. while (bc_vm_readLine(clear)) { size_t len = vm->buffer.len - 1; const char* str = vm->buffer.v; // We don't want to clear the buffer when the line ends with a backslash // because a backslash newline is special in bc. clear = (len < 2 || str[len - 2] != '\\' || str[len - 1] != '\n'); if (!clear) continue; // Process the data. bc_vm_process(vm->buffer.v, BC_MODE_STDIN); if (vm->eof) break; else { BC_SIG_LOCK; bc_vm_clean(); BC_SIG_UNLOCK; } } #if BC_ENABLED // End the if statements. if (BC_IS_BC) bc_vm_endif(); #endif // BC_ENABLED err: BC_SIG_MAYLOCK; // Cleanup. bc_vm_clean(); #if !BC_ENABLE_MEMCHECK assert(vm->status != BC_STATUS_ERROR_FATAL); vm->status = vm->status == BC_STATUS_QUIT || !BC_I ? vm->status : BC_STATUS_SUCCESS; #else // !BC_ENABLE_MEMCHECK vm->status = vm->status == BC_STATUS_ERROR_FATAL || vm->status == BC_STATUS_QUIT || !BC_I ? vm->status : BC_STATUS_SUCCESS; #endif // !BC_ENABLE_MEMCHECK if (!vm->status && !vm->eof) { bc_vec_empty(&vm->buffer); BC_LONGJMP_STOP; BC_SIG_UNLOCK; goto restart; } #if BC_DEBUG // Since these are tied to this function, free them here. We only free in // debug mode because stdin is always the last thing read. bc_vec_free(&vm->line_buf); bc_vec_free(&vm->buffer); #endif // BC_DEBUG BC_LONGJMP_CONT(vm); } bool bc_vm_readBuf(bool clear) { size_t len = vm->exprs.len - 1; bool more; BC_SIG_ASSERT_NOT_LOCKED; // Clear the buffer if desired. if (clear) bc_vec_empty(&vm->buffer); // We want to pop the nul byte off because that's what bc_read_buf() // expects. bc_vec_pop(&vm->buffer); // Read one line of expressions. more = bc_read_buf(&vm->buffer, vm->exprs.v, &len); bc_vec_pushByte(&vm->buffer, '\0'); return more; } static void bc_vm_exprs(void) { bool clear; #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY clear = true; vm->mode = BC_MODE_EXPRS; // Prepare the lexer. bc_lex_file(&vm->prs.l, bc_program_exprs_name); // We initialize this so that the lexer can access it in the case that it // needs more data for expressions, such as for a multiline string or // comment. See the comment on the allocation of vm->buffer above in // bc_vm_stdin() for more information. BC_SIG_LOCK; bc_vec_init(&vm->buffer, sizeof(uchar), BC_DTOR_NONE); BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; while (bc_vm_readBuf(clear)) { size_t len = vm->buffer.len - 1; const char* str = vm->buffer.v; // We don't want to clear the buffer when the line ends with a backslash // because a backslash newline is special in bc. clear = (len < 2 || str[len - 2] != '\\' || str[len - 1] != '\n'); if (!clear) continue; // Process the data. bc_vm_process(vm->buffer.v, BC_MODE_EXPRS); } // If we were not supposed to clear, then we should process everything. This // makes sure that errors get reported. if (!clear) bc_vm_process(vm->buffer.v, BC_MODE_EXPRS); err: BC_SIG_MAYLOCK; // Cleanup. bc_vm_clean(); // bc_program_reset(), called by bc_vm_clean(), resets the status. // We want it to clear the sig_pop variable in case it was set. if (vm->status == (sig_atomic_t) BC_STATUS_SUCCESS) BC_LONGJMP_STOP; // Since this is tied to this function, free it here. We always free it here // because bc_vm_stdin() may or may not use it later. bc_vec_free(&vm->buffer); BC_LONGJMP_CONT(vm); } #if BC_ENABLED /** * Loads a math library. * @param name The name of the library. * @param text The text of the source code. */ static void bc_vm_load(const char* name, const char* text) { bc_lex_file(&vm->prs.l, name); bc_parse_text(&vm->prs, text, BC_MODE_FILE); BC_SIG_LOCK; while (vm->prs.l.t != BC_LEX_EOF) { vm->parse(&vm->prs); } BC_SIG_UNLOCK; } #endif // BC_ENABLED /** * Loads the default error messages. */ static void bc_vm_defaultMsgs(void) { size_t i; // Load the error categories. for (i = 0; i < BC_ERR_IDX_NELEMS + BC_ENABLED; ++i) { vm->err_ids[i] = bc_errs[i]; } // Load the error messages. for (i = 0; i < BC_ERR_NELEMS; ++i) { vm->err_msgs[i] = bc_err_msgs[i]; } } /** * Loads the error messages for the locale. If NLS is disabled, this just loads * the default messages. */ static void bc_vm_gettext(void) { #if BC_ENABLE_NLS uchar id = 0; int set, msg = 1; size_t i; // If no locale, load the defaults. if (vm->locale == NULL) { vm->catalog = BC_VM_INVALID_CATALOG; bc_vm_defaultMsgs(); return; } vm->catalog = catopen(BC_MAINEXEC, NL_CAT_LOCALE); // If no catalog, load the defaults. if (vm->catalog == BC_VM_INVALID_CATALOG) { bc_vm_defaultMsgs(); return; } // Load the error categories. for (set = 1; msg <= BC_ERR_IDX_NELEMS + BC_ENABLED; ++msg) { vm->err_ids[msg - 1] = catgets(vm->catalog, set, msg, bc_errs[msg - 1]); } i = 0; id = bc_err_ids[i]; // Load the error messages. In order to understand this loop, you must know // the order of messages and categories in the enum and in the locale files. for (set = id + 2, msg = 1; i < BC_ERR_NELEMS; ++i, ++msg) { if (id != bc_err_ids[i]) { msg = 1; id = bc_err_ids[i]; set = id + 2; } vm->err_msgs[i] = catgets(vm->catalog, set, msg, bc_err_msgs[i]); } #else // BC_ENABLE_NLS bc_vm_defaultMsgs(); #endif // BC_ENABLE_NLS } /** * Starts execution. Really, this is a function of historical accident; it could * probably be combined with bc_vm_boot(), but I don't care enough. Really, this * function starts when execution of bc or dc source code starts. */ static void bc_vm_exec(void) { size_t i; #if DC_ENABLED bool has_file = false; #endif // DC_ENABLED #if BC_ENABLED // Load the math libraries. if (BC_IS_BC && (vm->flags & BC_FLAG_L)) { // Can't allow redefinitions in the builtin library. vm->no_redefine = true; bc_vm_load(bc_lib_name, bc_lib); #if BC_ENABLE_EXTRA_MATH if (!BC_IS_POSIX) bc_vm_load(bc_lib2_name, bc_lib2); #endif // BC_ENABLE_EXTRA_MATH // Make sure to clear this. vm->no_redefine = false; // Execute to ensure that all is hunky dory. Without this, scale can be // set improperly. bc_program_exec(&vm->prog); } #endif // BC_ENABLED // If there are expressions to execute... if (vm->exprs.len) { // Process the expressions. bc_vm_exprs(); // Sometimes, executing expressions means we need to quit. if (!vm->no_exprs && vm->exit_exprs && BC_EXPR_EXIT) return; } // Process files. for (i = 0; i < vm->files.len; ++i) { char* path = *((char**) bc_vec_item(&vm->files, i)); if (!strcmp(path, "")) continue; #if DC_ENABLED has_file = true; #endif // DC_ENABLED bc_vm_file(path); } #if BC_ENABLE_EXTRA_MATH // These are needed for the pseudo-random number generator. bc_unveil("/dev/urandom", "r"); bc_unveil("/dev/random", "r"); bc_unveil(NULL, NULL); #endif // BC_ENABLE_EXTRA_MATH #if BC_ENABLE_HISTORY // We need to keep tty if history is enabled, and we need to keep rpath for // the times when we read from /dev/urandom. if (BC_TTY && !vm->history.badTerm) bc_pledge(bc_pledge_end_history, NULL); else #endif // BC_ENABLE_HISTORY { bc_pledge(bc_pledge_end, NULL); } #if BC_ENABLE_AFL // This is the thing that makes fuzzing with AFL++ so fast. If you move this // back, you won't cause any problems, but fuzzing will slow down. If you // move this forward, you won't fuzz anything because you will be skipping // the reading from stdin. __AFL_INIT(); #endif // BC_ENABLE_AFL // Execute from stdin. bc always does. if (BC_VM_RUN_STDIN(has_file)) bc_vm_stdin(); } void bc_vm_boot(int argc, char* argv[]) { int ttyin, ttyout, ttyerr; bool tty; const char* const env_len = BC_VM_LINE_LENGTH_STR; const char* const env_args = BC_VM_ENV_ARGS_STR; const char* const env_exit = BC_VM_EXPR_EXIT_STR; const char* const env_clamp = BC_VM_DIGIT_CLAMP_STR; int env_exit_def = BC_VM_EXPR_EXIT_DEF; int env_clamp_def = BC_VM_DIGIT_CLAMP_DEF; BcBigDig scale = BC_NUM_BIGDIG_MAX; BcBigDig env_scale = BC_NUM_BIGDIG_MAX; BcBigDig ibase = BC_NUM_BIGDIG_MAX; BcBigDig env_ibase = BC_NUM_BIGDIG_MAX; BcBigDig obase = BC_NUM_BIGDIG_MAX; BcBigDig env_obase = BC_NUM_BIGDIG_MAX; // We need to know which of stdin, stdout, and stderr are tty's. ttyin = isatty(STDIN_FILENO); ttyout = isatty(STDOUT_FILENO); ttyerr = isatty(STDERR_FILENO); tty = (ttyin != 0 && ttyout != 0 && ttyerr != 0); vm->flags |= ttyin ? BC_FLAG_TTYIN : 0; vm->flags |= tty ? BC_FLAG_TTY : 0; vm->flags |= ttyin && ttyout ? BC_FLAG_I : 0; // Set up signals. bc_vm_sigaction(); // Initialize some vm stuff. This is separate to make things easier for the // library. bc_vm_init(); // Explicitly set this in case NULL isn't all zeroes. vm->file = NULL; // Set the error messages. bc_vm_gettext(); #if BC_ENABLE_LINE_LIB // Initialize the output file buffers. bc_file_init(&vm->ferr, stderr); bc_file_init(&vm->fout, stdout); // Set the input buffer. vm->buf = output_bufs; #else // BC_ENABLE_LINE_LIB // Initialize the output file buffers. They each take portions of the global // buffer. stdout gets more because it will probably have more data. bc_file_init(&vm->ferr, STDERR_FILENO, output_bufs + BC_VM_STDOUT_BUF_SIZE, BC_VM_STDERR_BUF_SIZE); bc_file_init(&vm->fout, STDOUT_FILENO, output_bufs, BC_VM_STDOUT_BUF_SIZE); // Set the input buffer to the rest of the global buffer. vm->buf = output_bufs + BC_VM_STDOUT_BUF_SIZE + BC_VM_STDERR_BUF_SIZE; #endif // BC_ENABLE_LINE_LIB // Set the line length by environment variable. vm->line_len = (uint16_t) bc_vm_envLen(env_len); bc_vm_setenvFlag(env_exit, env_exit_def, BC_FLAG_EXPR_EXIT); bc_vm_setenvFlag(env_clamp, env_clamp_def, BC_FLAG_DIGIT_CLAMP); // Clear the files and expressions vectors, just in case. This marks them as // *not* allocated. bc_vec_clear(&vm->files); bc_vec_clear(&vm->exprs); #if !BC_ENABLE_LIBRARY // Initialize the slab vector. bc_slabvec_init(&vm->slabs); #endif // !BC_ENABLE_LIBRARY // Initialize the program and main parser. These have to be in this order // because the program has to be initialized first, since a pointer to it is // passed to the parser. bc_program_init(&vm->prog); bc_parse_init(&vm->prs, &vm->prog, BC_PROG_MAIN); // Set defaults. vm->flags |= BC_TTY ? BC_FLAG_P | BC_FLAG_R : 0; vm->flags |= BC_I ? BC_FLAG_Q : 0; #if BC_ENABLED if (BC_IS_BC) { // bc checks this environment variable to see if it should run in // standard mode. char* var = bc_vm_getenv("POSIXLY_CORRECT"); vm->flags |= BC_FLAG_S * (var != NULL); bc_vm_getenvFree(var); // Set whether we print the banner or not. if (BC_I) bc_vm_setenvFlag("BC_BANNER", BC_DEFAULT_BANNER, BC_FLAG_Q); } #endif // BC_ENABLED // Are we in TTY mode? if (BC_TTY) { const char* const env_tty = BC_VM_TTY_MODE_STR; int env_tty_def = BC_VM_TTY_MODE_DEF; const char* const env_prompt = BC_VM_PROMPT_STR; int env_prompt_def = BC_VM_PROMPT_DEF; // Set flags for TTY mode and prompt. bc_vm_setenvFlag(env_tty, env_tty_def, BC_FLAG_TTY); bc_vm_setenvFlag(env_prompt, tty ? env_prompt_def : 0, BC_FLAG_P); #if BC_ENABLE_HISTORY // If TTY mode is used, activate history. if (BC_TTY) bc_history_init(&vm->history); #endif // BC_ENABLE_HISTORY } // Process environment and command-line arguments. bc_vm_envArgs(env_args, &env_scale, &env_ibase, &env_obase); bc_args(argc, argv, true, &scale, &ibase, &obase); // This section is here because we don't want the math library to stomp on // the user's given value for scale. And we don't want ibase affecting how // the scale is interpreted. Also, it's sectioned off just for this comment. { BC_SIG_UNLOCK; scale = scale == BC_NUM_BIGDIG_MAX ? env_scale : scale; #if BC_ENABLED // Assign the library value only if it is used and no value was set. scale = scale == BC_NUM_BIGDIG_MAX && BC_L ? 20 : scale; #endif // BC_ENABLED obase = obase == BC_NUM_BIGDIG_MAX ? env_obase : obase; ibase = ibase == BC_NUM_BIGDIG_MAX ? env_ibase : ibase; if (scale != BC_NUM_BIGDIG_MAX) { bc_program_assignBuiltin(&vm->prog, true, false, scale); } if (obase != BC_NUM_BIGDIG_MAX) { bc_program_assignBuiltin(&vm->prog, false, true, obase); } // This is last to avoid it affecting the value of the others. if (ibase != BC_NUM_BIGDIG_MAX) { bc_program_assignBuiltin(&vm->prog, false, false, ibase); } BC_SIG_LOCK; } // If we are in interactive mode... if (BC_I) { const char* const env_sigint = BC_VM_SIGINT_RESET_STR; int env_sigint_def = BC_VM_SIGINT_RESET_DEF; // Set whether we reset on SIGINT or not. bc_vm_setenvFlag(env_sigint, env_sigint_def, BC_FLAG_SIGINT); } #if BC_ENABLED // Disable global stacks in POSIX mode. if (BC_IS_POSIX) vm->flags &= ~(BC_FLAG_G); // Print the banner if allowed. We have to be in bc, in interactive mode, // and not be quieted by command-line option or environment variable. if (BC_IS_BC && BC_I && (vm->flags & BC_FLAG_Q)) { bc_vm_info(NULL); bc_file_putchar(&vm->fout, bc_flush_none, '\n'); bc_file_flush(&vm->fout, bc_flush_none); } #endif // BC_ENABLED BC_SIG_UNLOCK; // Start executing. bc_vm_exec(); } #endif // !BC_ENABLE_LIBRARY void bc_vm_init(void) { #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY BC_SIG_ASSERT_LOCKED; #if !BC_ENABLE_LIBRARY // Set up the constant zero. bc_num_setup(&vm->zero, vm->zero_num, BC_VM_ONE_CAP); #endif // !BC_ENABLE_LIBRARY // Set up more constant BcNum's. bc_num_setup(&vm->one, vm->one_num, BC_VM_ONE_CAP); bc_num_one(&vm->one); // Set up more constant BcNum's. // NOLINTNEXTLINE memcpy(vm->max_num, bc_num_bigdigMax, bc_num_bigdigMax_size * sizeof(BcDig)); // NOLINTNEXTLINE memcpy(vm->max2_num, bc_num_bigdigMax2, bc_num_bigdigMax2_size * sizeof(BcDig)); bc_num_setup(&vm->max, vm->max_num, BC_NUM_BIGDIG_LOG10); bc_num_setup(&vm->max2, vm->max2_num, BC_NUM_BIGDIG_LOG10); vm->max.len = bc_num_bigdigMax_size; vm->max2.len = bc_num_bigdigMax2_size; // Set up the maxes for the globals. vm->maxes[BC_PROG_GLOBALS_IBASE] = BC_NUM_MAX_POSIX_IBASE; vm->maxes[BC_PROG_GLOBALS_OBASE] = BC_MAX_OBASE; vm->maxes[BC_PROG_GLOBALS_SCALE] = BC_MAX_SCALE; #if BC_ENABLE_EXTRA_MATH vm->maxes[BC_PROG_MAX_RAND] = ((BcRand) 0) - 1; #endif // BC_ENABLE_EXTRA_MATH #if BC_ENABLED #if !BC_ENABLE_LIBRARY // bc has a higher max ibase when it's not in POSIX mode. if (BC_IS_BC && !BC_IS_POSIX) #endif // !BC_ENABLE_LIBRARY { vm->maxes[BC_PROG_GLOBALS_IBASE] = BC_NUM_MAX_IBASE; } #endif // BC_ENABLED } #if BC_ENABLE_LIBRARY void bc_vm_atexit(void) { #if BC_DEBUG #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY #endif // BC_DEBUG bc_vm_shutdown(); #if BC_DEBUG bc_vec_free(&vm->jmp_bufs); #endif // BC_DEBUG } #else // BC_ENABLE_LIBRARY int bc_vm_atexit(int status) { // Set the status correctly. int s = BC_STATUS_IS_ERROR(status) ? status : BC_STATUS_SUCCESS; bc_vm_shutdown(); #if BC_DEBUG bc_vec_free(&vm->jmp_bufs); #endif // BC_DEBUG return s; } #endif // BC_ENABLE_LIBRARY diff --git a/contrib/bc/tests/bcl.c b/contrib/bc/tests/bcl.c index cea63f457cd4..5bb50c29a753 100644 --- a/contrib/bc/tests/bcl.c +++ b/contrib/bc/tests/bcl.c @@ -1,344 +1,382 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2023 Gavin D. Howard and contributors. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * ***************************************************************************** * * Tests for bcl(3). * */ #include #include #include #include /** * Takes an error code and aborts if it actually is an error. * @param e The error code. */ static void err(BclError e) { if (e != BCL_ERROR_NONE) abort(); } int main(void) { BclError e; BclContext ctxt; size_t scale; - BclNumber n, n2, n3, n4, n5, n6; + BclNumber n, n2, n3, n4, n5, n6, n7; char* res; BclBigDig b = 0; e = bcl_start(); err(e); // We do this twice to test the reference counting code. e = bcl_init(); err(e); e = bcl_init(); err(e); // If bcl is set to abort on fatal error, that is a bug because it should // default to off. if (bcl_abortOnFatalError()) err(BCL_ERROR_FATAL_UNKNOWN_ERR); bcl_setAbortOnFatalError(true); // Now it *should* be set. if (!bcl_abortOnFatalError()) err(BCL_ERROR_FATAL_UNKNOWN_ERR); // We do this twice to test the context stack. ctxt = bcl_ctxt_create(); bcl_pushContext(ctxt); ctxt = bcl_ctxt_create(); bcl_pushContext(ctxt); // Ensure that the scale is properly set. scale = 10; bcl_ctxt_setScale(ctxt, scale); scale = bcl_ctxt_scale(ctxt); if (scale != 10) err(BCL_ERROR_FATAL_UNKNOWN_ERR); scale = 16; bcl_ctxt_setIbase(ctxt, scale); scale = bcl_ctxt_ibase(ctxt); if (scale != 16) err(BCL_ERROR_FATAL_UNKNOWN_ERR); // Now the obase. bcl_ctxt_setObase(ctxt, scale); scale = bcl_ctxt_obase(ctxt); if (scale != 16) err(BCL_ERROR_FATAL_UNKNOWN_ERR); // Set the back for the tests bcl_ctxt_setIbase(ctxt, 10); scale = bcl_ctxt_ibase(ctxt); if (scale != 10) err(BCL_ERROR_FATAL_UNKNOWN_ERR); bcl_ctxt_setObase(ctxt, 10); scale = bcl_ctxt_obase(ctxt); if (scale != 10) err(BCL_ERROR_FATAL_UNKNOWN_ERR); // Ensure that creating, duping, and copying works. n = bcl_num_create(); n2 = bcl_dup(n); bcl_copy(n, n2); // Ensure that parsing works. n3 = bcl_parse("2938"); err(bcl_err(n3)); n4 = bcl_parse("-28390.9108273"); err(bcl_err(n4)); // We also want to be sure that negatives work. This is a special case // because bc and dc generate a negative instruction; they don't actually // parse numbers as negative. if (!bcl_num_neg(n4)) err(BCL_ERROR_FATAL_UNKNOWN_ERR); + // Add them and check the result. + n5 = bcl_add_keep(n3, n4); + err(bcl_err(n5)); + res = bcl_string(n5); + if (res == NULL) err(BCL_ERROR_FATAL_ALLOC_ERR); + if (strcmp(res, "-25452.9108273")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); + + // We want to ensure all memory gets freed because we run this under + // Valgrind. + free(res); + // Add them and check the result. n3 = bcl_add(n3, n4); err(bcl_err(n3)); - res = bcl_string(bcl_dup(n3)); + res = bcl_string_keep(n3); + if (res == NULL) err(BCL_ERROR_FATAL_ALLOC_ERR); if (strcmp(res, "-25452.9108273")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); // We want to ensure all memory gets freed because we run this under // Valgrind. free(res); // Ensure that divmod, a special case, works. n4 = bcl_parse("8937458902.2890347"); err(bcl_err(n4)); - e = bcl_divmod(bcl_dup(n4), n3, &n5, &n6); + e = bcl_divmod_keep(n4, n3, &n5, &n6); err(e); res = bcl_string(n5); - if (strcmp(res, "-351137.0060159482")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); - free(res); res = bcl_string(n6); - if (strcmp(res, ".00000152374405414")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); + free(res); + + // Ensure that divmod, a special case, works. + n4 = bcl_parse("8937458902.2890347"); + err(bcl_err(n4)); + e = bcl_divmod(bcl_dup(n4), n3, &n5, &n6); + err(e); + + res = bcl_string(n5); + if (strcmp(res, "-351137.0060159482")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); + free(res); + res = bcl_string(n6); + if (strcmp(res, ".00000152374405414")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); // Ensure that sqrt works. This is also a special case. The reason is // because it is a one-argument function. Since all binary operators go // through the same code (basically), we can test add and be done. However, // sqrt does not, so we want to specifically test it. n4 = bcl_sqrt(n4); err(bcl_err(n4)); res = bcl_string(bcl_dup(n4)); if (strcmp(res, "94538.1346457028")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); // We want to check that numbers are properly extended... e = bcl_num_setScale(n4, 20); err(e); res = bcl_string(bcl_dup(n4)); if (strcmp(res, "94538.13464570280000000000")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); // ...and truncated. e = bcl_num_setScale(n4, 0); err(e); res = bcl_string(bcl_dup(n4)); if (strcmp(res, "94538")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); // Check conversion to hardware integers... e = bcl_bigdig(n4, &b); err(e); if (b != 94538) err(BCL_ERROR_FATAL_UNKNOWN_ERR); // ...and back. n4 = bcl_bigdig2num(b); err(bcl_err(n4)); res = bcl_string(bcl_dup(n4)); if (strcmp(res, "94538")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); // Check rand. n4 = bcl_frand(10); err(bcl_err(n4)); // Check that no asserts fire in shifting. n4 = bcl_lshift(n4, bcl_bigdig2num(10)); err(bcl_err(n4)); // Repeat. n3 = bcl_irand(n4); err(bcl_err(n3)); + // Repeat. + n2 = bcl_ifrand_keep(n3, 10); + err(bcl_err(n2)); + // Repeat. n2 = bcl_ifrand(bcl_dup(n3), 10); err(bcl_err(n2)); + // Still checking asserts. + e = bcl_rand_seedWithNum_keep(n3); + err(e); + // Still checking asserts. e = bcl_rand_seedWithNum(n3); err(e); // Still checking asserts. n4 = bcl_rand_seed2num(); err(bcl_err(n4)); // Finally, check modexp, yet another special case. n5 = bcl_parse("10"); err(bcl_err(n5)); - n6 = bcl_modexp(bcl_dup(n5), bcl_dup(n5), bcl_dup(n5)); + n6 = bcl_modexp_keep(n5, n5, n5); err(bcl_err(n6)); + n7 = bcl_modexp(bcl_dup(n5), bcl_dup(n5), bcl_dup(n5)); + err(bcl_err(n7)); + // Clean up. bcl_num_free(n); // Test leading zeroes. if (bcl_leadingZeroes()) err(BCL_ERROR_FATAL_UNKNOWN_ERR); n = bcl_parse("0.01"); err(bcl_err(n)); n2 = bcl_parse("-0.01"); err(bcl_err(n2)); n3 = bcl_parse("1.01"); err(bcl_err(n3)); n4 = bcl_parse("-1.01"); err(bcl_err(n4)); + res = bcl_string_keep(n); + if (strcmp(res, ".01")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); + + free(res); + res = bcl_string(bcl_dup(n)); if (strcmp(res, ".01")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); res = bcl_string(bcl_dup(n2)); if (strcmp(res, "-.01")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); res = bcl_string(bcl_dup(n3)); if (strcmp(res, "1.01")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); res = bcl_string(bcl_dup(n4)); if (strcmp(res, "-1.01")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); bcl_setLeadingZeroes(true); if (!bcl_leadingZeroes()) err(BCL_ERROR_FATAL_UNKNOWN_ERR); res = bcl_string(bcl_dup(n)); if (strcmp(res, "0.01")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); res = bcl_string(bcl_dup(n2)); if (strcmp(res, "-0.01")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); res = bcl_string(bcl_dup(n3)); if (strcmp(res, "1.01")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); res = bcl_string(bcl_dup(n4)); if (strcmp(res, "-1.01")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); bcl_setLeadingZeroes(false); if (bcl_leadingZeroes()) err(BCL_ERROR_FATAL_UNKNOWN_ERR); res = bcl_string(n); if (strcmp(res, ".01")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); res = bcl_string(n2); if (strcmp(res, "-.01")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); res = bcl_string(n3); if (strcmp(res, "1.01")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); res = bcl_string(n4); if (strcmp(res, "-1.01")) err(BCL_ERROR_FATAL_UNKNOWN_ERR); free(res); bcl_ctxt_freeNums(ctxt); bcl_gc(); // We need to pop both contexts and free them. bcl_popContext(); bcl_ctxt_free(ctxt); ctxt = bcl_context(); bcl_popContext(); bcl_ctxt_free(ctxt); // Decrement the reference counter to ensure all is freed. bcl_free(); bcl_free(); bcl_end(); return 0; } diff --git a/contrib/bc/tests/read.sh b/contrib/bc/tests/read.sh index d7be18fdcecb..4881c10db58c 100755 --- a/contrib/bc/tests/read.sh +++ b/contrib/bc/tests/read.sh @@ -1,153 +1,166 @@ #! /bin/sh # # SPDX-License-Identifier: BSD-2-Clause # # Copyright (c) 2018-2023 Gavin D. Howard and contributors. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # set -e script="$0" testdir=$(dirname "$script") . "$testdir/../scripts/functions.sh" outputdir=${BC_TEST_OUTPUT_DIR:-$testdir} # Just print the usage and exit with an error. This can receive a message to # print. # @param 1 A message to print. usage() { if [ $# -eq 1 ]; then printf '%s\n\n' "$1" fi printf 'usage: %s dir [exe [args...]]\n' "$script" printf 'valid dirs are:\n' printf '\n' cat "$testdir/all.txt" printf '\n' exit 1 } # Command-line processing. if [ "$#" -lt 1 ]; then usage "Not enough arguments" fi d="$1" shift check_d_arg "$d" if [ "$#" -gt 0 ]; then exe="$1" shift check_exec_arg "$exe" else exe="$testdir/../bin/$d" check_exec_arg "$exe" fi name="$testdir/$d/read.txt" results="$testdir/$d/read_results.txt" errors="$testdir/$d/read_errors.txt" out="$outputdir/${d}_outputs/read_results.txt" +multiple_res="$outputdir/${d}_outputs/read_multiple_results.txt" outdir=$(dirname "$out") # Make sure the directory exists. if [ ! -d "$outdir" ]; then mkdir -p "$outdir" fi exebase=$(basename "$exe") # Set stuff for the correct calculator. if [ "$d" = "bc" ]; then options="-lq" halt="halt" read_call="read()" read_expr="${read_call}\n5+5;" + read_multiple=$(printf '%s\n%s\n%s\n' "3" "2" "1") else options="-x" halt="q" read_call="?" read_expr="${read_call}" + read_multiple=$(printf '%spR\n%spR\n%spR\n' "3" "2" "1") fi # I use these, so unset them to make the tests work. unset BC_ENV_ARGS unset BC_LINE_LENGTH unset DC_ENV_ARGS unset DC_LINE_LENGTH printf 'Running %s read...' "$d" set +e # Run read() on every line. while read line; do printf '%s\n%s\n' "$read_call" "$line" | "$exe" "$@" "$options" > "$out" checktest "$d" "$?" 'read' "$results" "$out" done < "$name" printf 'pass\n' +printf 'Running %s read multiple...' "$d" + +printf '3\n2\n1\n' > "$multiple_res" + +# Run multiple read() calls. +printf '%s\n' "$read_multiple" | "$exe" "$@" "$options" -e "$read_call" -e "$read_call" -e "$read_call" > "$out" +checktest "$d" "$?" 'read multiple' "$multiple_res" "$out" + +printf 'pass\n' + printf 'Running %s read errors...' "$d" # Run read on every line. while read line; do printf '%s\n%s\n' "$read_call" "$line" | "$exe" "$@" "$options" 2> "$out" > /dev/null err="$?" checkerrtest "$d" "$err" "$line" "$out" "$exebase" done < "$errors" printf 'pass\n' printf 'Running %s empty read...' "$d" read_test=$(printf '%s\n' "$read_call") printf '%s\n' "$read_test" | "$exe" "$@" "$opts" 2> "$out" > /dev/null err="$?" checkerrtest "$d" "$err" "$read_test" "$out" "$exebase" printf 'pass\n' printf 'Running %s read EOF...' "$d" read_test=$(printf '%s' "$read_call") printf '%s' "$read_test" | "$exe" "$@" "$opts" 2> "$out" > /dev/null err="$?" checkerrtest "$d" "$err" "$read_test" "$out" "$exebase" exec printf 'pass\n'