diff --git a/contrib/bc/LICENSE.md b/contrib/bc/LICENSE.md index b65095edc26c..74441065df35 100644 --- a/contrib/bc/LICENSE.md +++ b/contrib/bc/LICENSE.md @@ -1,113 +1,113 @@ # License Copyright (c) 2018-2023 Gavin D. Howard 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. ## History The files `src/history.c` and `include/history.h` are under the following copyrights and license: Copyright (c) 2010-2014, Salvatore Sanfilippo
Copyright (c) 2010-2013, Pieter Noordhuis
Copyright (c) 2018 rain-1
Copyright (c) 2018-2023, Gavin D. Howard 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. ## Rand The files `src/rand.c` and `include/rand.h` are under the following copyrights and license: -Copyright (c) 2014-2017 Melissa O'Neill and PCG Project contributors +Copyright (c) 2014-2017 Melissa O'Neill and PCG Project contributors
Copyright (c) 2018-2023 Gavin D. Howard Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## `scripts/safe-install.sh` The file `scripts/safe-install.sh` is under the following copyright and license: Copyright (c) 2021 Rich Felker Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## `scripts/ministat.c` The file `scripts/ministat.c` is under the following license: "THE BEER-WARE LICENSE" (Revision 42): wrote this file. As long as you retain this notice you can do whatever you want with this stuff. If we meet some day, and you think this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp diff --git a/contrib/bc/Makefile.in b/contrib/bc/Makefile.in index f936fc2c6de6..55e2e4a6270a 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%% +CPPFLAGS4 = $(CPPFLAGS3) %%BSD%% %%APPLE%% 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/ 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 44b17b060f5c..de3b35026fea 100644 --- a/contrib/bc/NEWS.md +++ b/contrib/bc/NEWS.md @@ -1,1500 +1,1512 @@ # News +## 6.6.0 + +This is a production release with two bug fixes and one change. + +The first bug fix is to fix the build on Mac OSX. + +The second bug was to remove printing a leading zero in scientific or +engineering output modes. + +The change was that the implementation of `irand()` was improved to call the +PRNG less. + ## 6.5.0 This is a production release that fixes an infinite loop bug in `root()` and `cbrt()`, fixes a bug with `BC_LINE_LENGTH=0`, and adds the `fib()` function to the extended math library to calculate Fibonacci numbers. ## 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/README.md b/contrib/bc/README.md index 9d395f747185..943ca89eee2c 100644 --- a/contrib/bc/README.md +++ b/contrib/bc/README.md @@ -1,502 +1,516 @@ # `bc` ***WARNING: New user registration for is disabled because of spam. If you need to report a bug with `bc`, email gavin at this site minus the `git.` part for an account, and I will create one for you. Or you can report an issue at [GitHub][29].*** ***WARNING: This project has moved to [https://git.gavinhoward.com/][20] for [these reasons][21], though GitHub will remain a mirror.*** This is an implementation of the [POSIX `bc` calculator][12] that implements [GNU `bc`][1] extensions, as well as the period (`.`) extension for the BSD flavor of `bc`. For more information, see this `bc`'s full manual. This `bc` also includes an implementation of `dc` in the same binary, accessible via a symbolic link, which implements all FreeBSD and GNU extensions. (If a standalone `dc` binary is desired, `bc` can be copied and renamed to `dc`.) The `!` command is omitted; I believe this poses security concerns and that such functionality is unnecessary. For more information, see the `dc`'s full manual. This `bc` also provides `bc`'s math as a library with C bindings, called `bcl`. For more information, see the full manual for `bcl`. ## License This `bc` is Free and Open Source Software (FOSS). It is offered under the BSD 2-clause License. Full license text may be found in the [`LICENSE.md`][4] file. ## Prerequisites This `bc` only requires either: 1. Windows 10 or later, or 2. A C99-compatible compiler and a (mostly) POSIX 2008-compatible system with the XSI (X/Open System Interfaces) option group. Since POSIX 2008 with XSI requires the existence of a C99 compiler as `c99`, any POSIX and XSI-compatible system will have everything needed. POSIX-compatible systems that are known to work: * Linux * FreeBSD * OpenBSD * NetBSD * Mac OSX * Solaris* (as long as the Solaris version supports POSIX 2008) * AIX * HP-UX* (except for history) In addition, there is compatibility code to make this `bc` work on Windows. Please submit bug reports if this `bc` does not build out of the box on any system. ## Build This `bc` should build unmodified on any POSIX-compliant system or on Windows starting with Windows 10 (though earlier versions may work). For more complex build requirements than the ones below, see the [build manual][5]. ### Windows There is no guarantee that this `bc` will work on any version of Windows earlier than Windows 10 (I cannot test on earlier versions), but it is guaranteed to work on Windows 10 at least. Also, if building with MSBuild, the MSBuild bundled with Visual Studio is required. **Note**: Unlike the POSIX-compatible platforms, only one build configuration is supported on Windows: extra math and history enabled, NLS (locale support) disabled, with both calculators built. #### `bc` To build `bc`, you can open the `vs/bc.sln` file in Visual Studio, select the configuration, and build. You can also build using MSBuild with the following from the root directory: ``` msbuild -property:Configuration= vs/bc.sln ``` where `` is either one of `Debug` or `Release`. On Windows, the calculators are built as `vs/bin///bc.exe` and `vs/bin///dc.exe`, where `` can be either `Win32` or `x64`, and `` can be `Debug` or `Release`. **Note**: On Windows, `dc.exe` is just copied from `bc.exe`; it is not linked. Patches are welcome for a way to do that. #### `bcl` (Library) To build the library, you can open the `vs/bcl.sln` file in Visual Studio, select the configuration, and build. You can also build using MSBuild with the following from the root directory: ``` msbuild -property:Configuration= vs/bcl.sln ``` where `` is either one of `Debug`, `ReleaseMD`, or `ReleaseMT`. On Windows, the library is built as `vs/lib///bcl.lib`, where `` can be either `Win32` or `x64`, and `` can be `Debug`, `ReleaseMD`, or `ReleaseMT`. ### POSIX-Compatible Systems On POSIX-compatible systems, `bc` is built as `bin/bc` and `dc` is built as `bin/dc` by default. #### Default For the default build with optimization, use the following commands in the root directory: ``` ./configure.sh -O3 make ``` #### One Calculator To only build `bc`, use the following commands: ``` ./configure.sh --disable-dc make ``` To only build `dc`, use the following commands: ``` ./configure.sh --disable-bc make ``` #### Debug For debug builds, use the following commands in the root directory: ``` ./configure.sh -g make ``` #### Install To install, use the following command: ``` make install ``` By default, `bc` and `dc` will be installed in `/usr/local`. For installing in other locations, use the `PREFIX` environment variable when running `configure.sh` or pass the `--prefix=` option to `configure.sh`. See the [build manual][5], or run `./configure.sh --help`, for more details. #### Library To build the math library, pass the `-a` or `--library` options to `configure.sh`: ``` ./configure.sh -a ``` When building the library, the executables are not built. For more information, see the [build manual][5]. The library API can be found in [`manuals/bcl.3.md`][26] or `man bcl` once the library is installed. #### Package and Distro Maintainers This section is for package and distro maintainers. ##### Out-of-Source Builds Out-of-source builds are supported; just call `configure.sh` from the directory where the actual build will happen. For example, if the source is in `bc`, the build should happen in `build`, then call `configure.sh` and `make` like so: ``` ../bc/configure.sh make ``` ***WARNING***: The path to `configure.sh` from the build directory must not have spaces because `make` does not support target names with spaces. ##### Recommended Compiler When I ran benchmarks with my `bc` compiled under `clang`, it performed much better than when compiled under `gcc`. I recommend compiling this `bc` with `clang`. I also recommend building this `bc` with C11 if you can because `bc` will detect a C11 compiler and add `_Noreturn` to any relevant function(s). ##### Recommended Optimizations I wrote this `bc` with Separation of Concerns, which means that there are many small functions that could be inlined. However, they are often called across file boundaries, and the default optimizer can only look at the current file, which means that they are not inlined. Thus, because of the way this `bc` is built, it will automatically be slower than other `bc` implementations when running scripts with no math. (My `bc`'s math is *much* faster, so any non-trivial script should run faster in my `bc`.) Some, or all, of the difference can be made up with the right optimizations. The optimizations I recommend are: 1. `-O3` 2. `-flto` (link-time optimization) in that order. Link-time optimization, in particular, speeds up the `bc` a lot. This is because when link-time optimization is turned on, the optimizer can look across files and inline *much* more heavily. However, I recommend ***NOT*** using `-march=native`. Doing so will reduce this `bc`'s performance, at least when building with link-time optimization. See the [benchmarks][19] for more details. ##### Stripping Binaries By default, non-debug binaries are stripped, but stripping can be disabled with the `-T` option to `configure.sh`. ##### Using This `bc` as an Alternative If this `bc` is packaged as an alternative to an already existing `bc` package, it is possible to rename it in the build to prevent name collision. To prepend to the name, just run the following: ``` EXECPREFIX= ./configure.sh ``` To append to the name, just run the following: ``` EXECSUFFIX= ./configure.sh ``` If a package maintainer wishes to add both a prefix and a suffix, that is allowed. **Note**: The suggested name (and package name) when `bc` is not available is `bc-gh`. ##### Karatsuba Number Package and distro maintainers have one tool at their disposal to build this `bc` in the optimal configuration: `scripts/karatsuba.py`. This script is not a compile-time or runtime prerequisite; it is for package and distro maintainers to run once when a package is being created. It finds the optimal Karatsuba number (see the [algorithms manual][7] for more information) for the machine that it is running on. The easiest way to run this script is with `make karatsuba`. If desired, maintainers can also skip running this script because there is a sane default for the Karatsuba number. ## Status This `bc` is robust. It is well-tested, fuzzed, and fully standards-compliant (though not certified) with POSIX `bc`. The math has been tested with 40+ million random problems, so it is as correct as I can make it. This `bc` can be used as a drop-in replacement for any existing `bc`. This `bc` is also compatible with MinGW toolchains. In addition, this `bc` is considered complete; i.e., there will be no more releases with additional features. However, it *is* actively maintained, so if any bugs are found, they will be fixed in new releases. Also, additional translations will also be added as they are provided. ### Development If I (Gavin D. Howard) get [hit by a bus][27] and future programmers need to handle work themselves, the best place to start is the [Development manual][28]. ## Vim Syntax I have developed (using other people's code to start) [`vim` syntax files][17] for this `bc` and `dc`, including the extensions. ## `bc` Libs I have gathered some excellent [`bc` and `dc` libraries][18]. These libraries may prove useful to any serious users. ## Comparison to GNU `bc` This `bc` compares favorably to GNU `bc`. * This `bc` builds natively on Windows. * It has more extensions, which make this `bc` more useful for scripting. (See [Extensions](#extensions).) * This `bc` is a bit more POSIX compliant. * It has a much less buggy parser. The GNU `bc` will give parse errors for what is actually valid `bc` code, or should be. For example, putting an `else` on a new line after a brace can cause GNU `bc` to give a parse error. * This `bc` has fewer crashes. * GNU `bc` calculates the wrong number of significant digits for `length(x)`. * GNU `bc` will sometimes print numbers incorrectly. For example, when running it on the file `tests/bc/power.txt` in this repo, GNU `bc` gets all the right answers, but it fails to wrap the numbers at the proper place when outputting to a file. * This `bc` is faster. (See [Performance](#performance).) ### Performance Because this `bc` packs more than `1` decimal digit per hardware integer, this `bc` is faster than GNU `bc` and can be *much* faster. Full benchmarks can be found at [manuals/benchmarks.md][19]. There is one instance where this `bc` is slower: if scripts are light on math. This is because this `bc`'s intepreter is slightly slower than GNU `bc`, but that is because it is more robust. See the [benchmarks][19]. ### Extensions Below is a non-comprehensive list of extensions that this `bc` and `dc` have that all others do not. * An extended math library. (See [here][30] for more information.) * A command-line prompt. * Turning on and off digit clamping. (Digit clamping is about how to treat "invalid" digits for a particular base. GNU `bc` uses it, and the BSD `bc` does not. Mine does both.) * A pseudo-random number generator. This includes the ability to set the seed and get reproducible streams of random numbers. * The ability to use stacks for the globals `scale`, `ibase`, and `obase` instead of needing to restore them in *every* function. * The ability to *not* use non-standard keywords. For example, `abs` is a keyword (a built-in function), but if some script actually defines a function called that, it's possible to tell my `bc` to not treat it as a keyword, which will make the script parses correctly. * The ability to turn on and off printing leading zeroes on numbers greater than `-1` and less than `1`. * Outputting in scientific and engineering notation. * Accepting input in scientific and engineering notation. * Passing strings and arrays to the `length()` built-in function. (In `dc`, the `Y` command will do this for arrays, and the `Z` command will do this for both numbers and strings.) * The `abs()` built-in function. (This is the `b` command in `dc`.) * The `is_number()` and `is_string()` built-in functions. (These tell whether a variable is holding a string or a number, for runtime type checking. The commands are `u` and `t` in `dc`.) * For `bc` only, the `divmod()` built-in function for computing a quotient and remainder at the same time. * For `bc` only, the `asciify()` built-in function for converting an array to a string. * The `$` truncation operator. (It's the same in `bc` and `dc`.) * The `@` "set scale" operator. (It's the same in `bc` and `dc`.) * The decimal shift operators. (`<<` and `>>` in `bc`, `H` and `h` in `dc`.) * Built-in functions or commands to get the max of `scale`, `ibase`, and `obase`. * The ability to put strings into variables in `bc`. (This always existed in `dc`.) * The `'` command in `dc` for the depth of the execution stack. * The `y` command in `dc` for the depth of register stacks. * Built-in functions or commands to get the value of certain environment variables that might affect execution. * The `stream` keyword to do the same thing as the `P` command in `dc`. * Defined order of evaluation. * Defined exit statuses. * All environment variables other than `POSIXLY_CORRECT`, `BC_ENV_ARGS`, and `BC_LINE_LENGTH`. * The ability for users to define their own defaults for various options during build. (See [here][31] for more information.) ## Algorithms To see what algorithms this `bc` uses, see the [algorithms manual][7]. ## Locales Currently, there is no locale support on Windows. Additionally, this `bc` only has support for English (and US English), French, German, Portuguese, Dutch, Polish, Russian, Japanese, and Chinese locales. Patches are welcome for translations; use the existing `*.msg` files in `locales/` as a starting point. In addition, patches for improvements are welcome; the last two messages in Portuguese were made with Google Translate, and the Dutch, Polish, Russian, Japanese, and Chinese locales were all generated with [DeepL][22]. The message files provided assume that locales apply to all regions where a language is used, but this might not be true for, e.g., `fr_CA` and `fr_CH`. Any corrections or a confirmation that the current texts are acceptable for those regions would be appreciated, too. ## Other Projects Other projects based on this bc are: * [busybox `bc`][8]. The busybox maintainers have made their own changes, so any bugs in the busybox `bc` should be reported to them. - * [toybox `bc`][9]. The maintainer has also made his own changes, so bugs in the toybox `bc` should be reported there. - * [FreeBSD `bc`][23]. While the `bc` in FreeBSD is kept up-to-date, it is better to [report bugs there][24], as well as [submit patches][25], and the maintainers of the package will contact me if necessary. +* [Mac OSX `bc`][35]. Any bugs in that `bc` should be reported to me, but do + expect bugs because the version is old. +* [Android Open Source `bc`][32]. Any bugs in that `bc` can be reported here. + +This is a non-comprehensive list of Linux distros that use this `bc` as the +system `bc`: + +* [Gentoo][33]; it is a first-class alternative to GNU `bc`, but not exclusive. +* [Linux from Scratch][34]. + +Other Linux distros package it as a second-class alternative, usually as `bc-gh` +or `howard-bc`. ## Language This `bc` is written in pure ISO C99, using POSIX 2008 APIs with custom Windows compatibility code. ## Commit Messages This `bc` uses the commit message guidelines laid out in [this blog post][10]. ## Semantic Versioning This `bc` uses [semantic versioning][11]. ## AI-Free This repository is 100% AI-Free code. ## Contents Items labeled with `(maintainer use only)` are not included in release source tarballs. Files: .gitignore The git ignore file (maintainer use only). .gitattributes The git attributes file (maintainer use only). bcl.pc.in A template pkg-config file for bcl. configure A symlink to configure.sh to make packaging easier. configure.sh The configure script. LICENSE.md A Markdown form of the BSD 2-clause License. Makefile.in The Makefile template. NEWS.md The changelog. NOTICE.md List of contributors and copyright owners. Folders: benchmarks A folder of benchmarks for various aspects of bc performance. gen The bc math library, help texts, and code to generate C source. include All header files. locales Locale files, in .msg format. Patches welcome for translations. manuals Manuals for both programs. src All source code. scripts A bunch of shell scripts to help with development and building. tests All tests. vs Files needed for the build on Windows. [1]: https://www.gnu.org/software/bc/ [4]: ./LICENSE.md [5]: ./manuals/build.md [7]: ./manuals/algorithms.md [8]: https://git.busybox.net/busybox/tree/miscutils/bc.c [9]: https://github.com/landley/toybox/blob/master/toys/pending/bc.c [10]: http://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html [11]: http://semver.org/ [12]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html [17]: https://git.gavinhoward.com/gavin/vim-bc [18]: https://git.gavinhoward.com/gavin/bc_libs [19]: ./manuals/benchmarks.md [20]: https://git.gavinhoward.com/gavin/bc [21]: https://gavinhoward.com/2020/04/i-am-moving-away-from-github/ [22]: https://www.deepl.com/translator [23]: https://cgit.freebsd.org/src/tree/contrib/bc [24]: https://bugs.freebsd.org/ [25]: https://reviews.freebsd.org/ [26]: ./manuals/bcl.3.md [27]: https://en.wikipedia.org/wiki/Bus_factor [28]: ./manuals/development.md [29]: https://github.com/gavinhoward/bc [30]: ./manuals/bc/A.1.md#extended-library [31]: ./manuals/build.md#settings +[32]: https://android.googlesource.com/platform/external/bc/ +[33]: https://github.com/gentoo/gentoo/blob/master/app-alternatives/bc/bc-0.ebuild#L8 +[34]: https://www.linuxfromscratch.org/lfs/view/stable/chapter08/bc.html +[35]: https://github.com/apple-oss-distributions/bc/tree/main/bc diff --git a/contrib/bc/configure.sh b/contrib/bc/configure.sh index 021d30807ffb..4ba957131d52 100755 --- a/contrib/bc/configure.sh +++ b/contrib/bc/configure.sh @@ -1,2111 +1,2131 @@ #! /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" + CFLAGS="-flto -Weverything -Wno-padded -Wno-unsafe-buffer-usage -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" + CFLAGS="-Weverything -Wno-padded -Wno-unsafe-buffer-usage -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" + CPPFLAGS="$CPPFLAGS -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" + CPPFLAGS="$CPPFLAGS -DBC_ENABLE_EDITLINE=0 -DBC_ENABLE_READLINE=1" else - CFLAGS="$CFLAGS -DBC_ENABLE_EDITLINE=0 -DBC_ENABLE_READLINE=0" + CPPFLAGS="$CPPFLAGS -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 Mac OSX. This is not in an if statement because regardless of whatever +# the user says, we need to know if we are on Mac OSX. If we are, we have to set +# _DARWIN_C_SOURCE. +printf 'Testing for Mac OSX...\n' + +flags="-DBC_TEST_APPLE -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 Mac OSX. Using _DARWIN_C_SOURCE.\n\n' + apple="-D_DARWIN_C_SOURCE" +else + printf 'Not on Mac OSX.\n\n' + apple="" +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 +set -e + 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" > "$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" "APPLE" "$apple") 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/num.h b/contrib/bc/include/num.h index 8078809250f8..d24c206cbe51 100644 --- a/contrib/bc/include/num.h +++ b/contrib/bc/include/num.h @@ -1,905 +1,913 @@ /* * ***************************************************************************** * * 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 the num type. * */ #ifndef BC_NUM_H #define BC_NUM_H #include #include #include #include #include #include #include #include /// Everything in bc is base 10.. #define BC_BASE (10) /// Alias. typedef unsigned long ulong; /// This is here because BcBigDig came first, but when I created bcl, it's /// definition has to be defined first. typedef BclBigDig BcBigDig; #if BC_LONG_BIT >= 64 /// The biggest number held by a BcBigDig. #define BC_NUM_BIGDIG_MAX ((BcBigDig) UINT64_MAX) /// The number of decimal digits in one limb. #define BC_BASE_DIGS (9) /// The max number + 1 that one limb can hold. #define BC_BASE_POW (1000000000) /// An alias for portability. #define BC_NUM_BIGDIG_C UINT64_C +/// The max number + 1 that two limbs can hold. This is used for generating +/// numbers because the PRNG can generate a number that will fill two limbs. +#define BC_BASE_RAND_POW (BC_NUM_BIGDIG_C(1000000000000000000)) + /// The actual limb type. typedef int_least32_t BcDig; #elif BC_LONG_BIT >= 32 /// The biggest number held by a BcBigDig. #define BC_NUM_BIGDIG_MAX ((BcBigDig) UINT32_MAX) /// The number of decimal digits in one limb. #define BC_BASE_DIGS (4) /// The max number + 1 that one limb can hold. #define BC_BASE_POW (10000) /// An alias for portability. #define BC_NUM_BIGDIG_C UINT32_C +/// The max number + 1 that two limbs can hold. This is used for generating +/// numbers because the PRNG can generate a number that will fill two limbs. +#define BC_BASE_RAND_POW (UINT64_C(100000000)) + /// The actual limb type. typedef int_least16_t BcDig; #else /// LONG_BIT must be at least 32 on POSIX. We depend on that. #error BC_LONG_BIT must be at least 32 #endif // BC_LONG_BIT >= 64 /// The default (and minimum) number of limbs when allocating a number. #define BC_NUM_DEF_SIZE (8) /// The actual number struct. This is where the magic happens. typedef struct BcNum { /// The limb array. It is restrict because *no* other item should own the /// array. For more information, see the development manual /// (manuals/development.md#numbers). BcDig* restrict num; /// The number of limbs before the decimal (radix) point. This also stores /// the negative bit in the least significant bit since it uses at least two /// bits less than scale. It is also used less than scale. See the /// development manual (manuals/development.md#numbers) for more info. size_t rdx; /// The actual scale of the number. This is different from rdx because there /// are multiple digits in one limb, and in the last limb, only some of the /// digits may be part of the scale. However, scale must always match rdx /// (except when the number is 0), or there is a bug. For more information, /// see the development manual (manuals/development.md#numbers). size_t scale; /// The number of valid limbs in the array. If this is 0, then the number is /// 0 as well. size_t len; /// The capacity of the limbs array. This is how many limbs the number could /// expand to without reallocation. size_t cap; } BcNum; #if BC_ENABLE_EXTRA_MATH // Forward declaration struct BcRNG; #endif // BC_ENABLE_EXTRA_MATH /// The minimum obase. #define BC_NUM_MIN_BASE (BC_NUM_BIGDIG_C(2)) /// The maximum ibase allowed by POSIX. #define BC_NUM_MAX_POSIX_IBASE (BC_NUM_BIGDIG_C(16)) /// The actual ibase supported by this implementation. #define BC_NUM_MAX_IBASE (BC_NUM_BIGDIG_C(36)) /// The max base allowed by bc_num_parseChar(). #define BC_NUM_MAX_LBASE (BC_NUM_BIGDIG_C('Z' + BC_BASE + 1)) /// The default number of characters to print before a backslash newline. #define BC_NUM_PRINT_WIDTH (BC_NUM_BIGDIG_C(69)) /// The base for printing streams from numbers. #define BC_NUM_STREAM_BASE (256) // This sets a default for the Karatsuba length. #ifndef BC_NUM_KARATSUBA_LEN #define BC_NUM_KARATSUBA_LEN (BC_NUM_BIGDIG_C(32)) #elif BC_NUM_KARATSUBA_LEN < 16 #error BC_NUM_KARATSUBA_LEN must be at least 16. #endif // BC_NUM_KARATSUBA_LEN // A crude, but always big enough, calculation of // the size required for ibase and obase BcNum's. #define BC_NUM_BIGDIG_LOG10 (BC_NUM_DEF_SIZE) /** * Returns non-zero if the BcNum @a n is non-zero. * @param n The number to test. * @return Non-zero if @a n is non-zero, zero otherwise. */ #define BC_NUM_NONZERO(n) ((n)->len) /** * Returns true if the BcNum @a n is zero. * @param n The number to test. * @return True if @a n is zero, false otherwise. */ #define BC_NUM_ZERO(n) (!BC_NUM_NONZERO(n)) /** * Returns true if the BcNum @a n is one with no scale. * @param n The number to test. * @return True if @a n equals 1 with no scale, false otherwise. */ #define BC_NUM_ONE(n) ((n)->len == 1 && (n)->rdx == 0 && (n)->num[0] == 1) /** * Converts the letter @a c into a number. * @param c The letter to convert. * @return The number corresponding to the letter. */ #define BC_NUM_NUM_LETTER(c) ((c) - 'A' + BC_BASE) /// The number of allocations done by bc_num_k(). If you change the number of /// allocations, you must change this. This is done in order to allocate them /// all as one allocation and just give them all pointers to different parts. /// Works pretty well, but you have to be careful. #define BC_NUM_KARATSUBA_ALLOCS (6) /** * Rounds @a s (scale) up to the next power of BC_BASE_DIGS. This also check for * overflow and gives a fatal error if that happens because we just can't go * over the limits we have imposed. * @param s The scale to round up. * @return @a s rounded up to the next power of BC_BASE_DIGS. */ #define BC_NUM_ROUND_POW(s) (bc_vm_growSize((s), BC_BASE_DIGS - 1)) /** * Returns the equivalent rdx for the scale @a s. * @param s The scale to convert. * @return The rdx for @a s. */ #define BC_NUM_RDX(s) (BC_NUM_ROUND_POW(s) / BC_BASE_DIGS) /** * Returns the actual rdx of @a n. (It removes the negative bit.) * @param n The number. * @return The real rdx of @a n. */ #define BC_NUM_RDX_VAL(n) ((n)->rdx >> 1) /** * Returns the actual rdx of @a n, where @a n is not a pointer. (It removes the * negative bit.) * @param n The number. * @return The real rdx of @a n. */ #define BC_NUM_RDX_VAL_NP(n) ((n).rdx >> 1) /** * Sets the rdx of @a n to @a v. * @param n The number. * @param v The value to set the rdx to. */ #define BC_NUM_RDX_SET(n, v) \ ((n)->rdx = (((v) << 1) | ((n)->rdx & (BcBigDig) 1))) /** * Sets the rdx of @a n to @a v, where @a n is not a pointer. * @param n The number. * @param v The value to set the rdx to. */ #define BC_NUM_RDX_SET_NP(n, v) \ ((n).rdx = (((v) << 1) | ((n).rdx & (BcBigDig) 1))) /** * Sets the rdx of @a n to @a v and the negative bit to @a neg. * @param n The number. * @param v The value to set the rdx to. * @param neg The value to set the negative bit to. */ #define BC_NUM_RDX_SET_NEG(n, v, neg) ((n)->rdx = (((v) << 1) | (neg))) /** * Returns true if the rdx and scale for @a n match. * @param n The number to test. * @return True if the rdx and scale of @a n match, false otherwise. */ #define BC_NUM_RDX_VALID(n) \ (BC_NUM_ZERO(n) || BC_NUM_RDX_VAL(n) * BC_BASE_DIGS >= (n)->scale) /** * Returns true if the rdx and scale for @a n match, where @a n is not a * pointer. * @param n The number to test. * @return True if the rdx and scale of @a n match, false otherwise. */ #define BC_NUM_RDX_VALID_NP(n) \ ((!(n).len) || BC_NUM_RDX_VAL_NP(n) * BC_BASE_DIGS >= (n).scale) /** * Returns true if @a n is negative, false otherwise. * @param n The number to test. * @return True if @a n is negative, false otherwise. */ #define BC_NUM_NEG(n) ((n)->rdx & ((BcBigDig) 1)) /** * Returns true if @a n is negative, false otherwise, where @a n is not a * pointer. * @param n The number to test. * @return True if @a n is negative, false otherwise. */ #define BC_NUM_NEG_NP(n) ((n).rdx & ((BcBigDig) 1)) /** * Clears the negative bit on @a n. * @param n The number. */ #define BC_NUM_NEG_CLR(n) ((n)->rdx &= ~((BcBigDig) 1)) /** * Clears the negative bit on @a n, where @a n is not a pointer. * @param n The number. */ #define BC_NUM_NEG_CLR_NP(n) ((n).rdx &= ~((BcBigDig) 1)) /** * Sets the negative bit on @a n. * @param n The number. */ #define BC_NUM_NEG_SET(n) ((n)->rdx |= ((BcBigDig) 1)) /** * Toggles the negative bit on @a n. * @param n The number. */ #define BC_NUM_NEG_TGL(n) ((n)->rdx ^= ((BcBigDig) 1)) /** * Toggles the negative bit on @a n, where @a n is not a pointer. * @param n The number. */ #define BC_NUM_NEG_TGL_NP(n) ((n).rdx ^= ((BcBigDig) 1)) /** * Returns the rdx val for @a n if the negative bit is set to @a v. * @param n The number. * @param v The value for the negative bit. * @return The value of the rdx of @a n if the negative bit were set to @a v. */ #define BC_NUM_NEG_VAL(n, v) (((n)->rdx & ~((BcBigDig) 1)) | (v)) /** * Returns the rdx val for @a n if the negative bit is set to @a v, where @a n * is not a pointer. * @param n The number. * @param v The value for the negative bit. * @return The value of the rdx of @a n if the negative bit were set to @a v. */ #define BC_NUM_NEG_VAL_NP(n, v) (((n).rdx & ~((BcBigDig) 1)) | (v)) /** * Returns the size, in bytes, of limb array with @a n limbs. * @param n The number. * @return The size, in bytes, of a limb array with @a n limbs. */ #define BC_NUM_SIZE(n) ((n) * sizeof(BcDig)) // These are for debugging only. #if BC_DEBUG_CODE #define BC_NUM_PRINT(x) fprintf(stderr, "%s = %lu\n", #x, (unsigned long) (x)) #define DUMP_NUM bc_num_dump #else // BC_DEBUG_CODE #undef DUMP_NUM #define DUMP_NUM(x, y) #define BC_NUM_PRINT(x) #endif // BC_DEBUG_CODE /** * A function type for binary operators. * @param a The first parameter. * @param b The second parameter. * @param c The return value. * @param scale The current scale. */ typedef void (*BcNumBinaryOp)(BcNum* a, BcNum* b, BcNum* c, size_t scale); /** * A function type for binary operators *after* @a c has been properly * allocated. At this point, *nothing* should be pointing to @a c (in any way * that matters, anyway). * @param a The first operand. * @param b The second operand. * @param c The return parameter. * @param scale The current scale. */ typedef void (*BcNumBinOp)(BcNum* a, BcNum* b, BcNum* restrict c, size_t scale); /** * A function type for getting the allocation size needed for a binary operator. * Any function used for this *must* return enough space for *all* possible * invocations of the operator. * @param a The first parameter. * @param b The second parameter. * @param scale The current scale. * @return The size of allocation needed for the result of the operator * with @a a, @a b, and @a scale. */ typedef size_t (*BcNumBinaryOpReq)(const BcNum* a, const BcNum* b, size_t scale); /** * A function type for printing a "digit." Functions of this type will print one * digit in a number. Digits are printed differently based on the base, which is * why there is more than one implementation of this function type. * @param n The "digit" to print. * @param len The "length" of the digit, or number of characters that will * need to be printed for the digit. * @param rdx True if a decimal (radix) point should be printed. * @param bslash True if a backslash+newline should be printed if the character * limit for the line is reached, false otherwise. */ typedef void (*BcNumDigitOp)(size_t n, size_t len, bool rdx, bool bslash); /** * A function type to run an operator on @a a and @a b and store the result in * @a a. This is used in karatsuba for faster adds and subtracts at the end. * @param a The first parameter and return value. * @param b The second parameter. * @param len The minimum length of both arrays. */ typedef void (*BcNumShiftAddOp)(BcDig* restrict a, const BcDig* restrict b, size_t len); /** * Initializes @a n with @a req limbs in its array. * @param n The number to initialize. * @param req The number of limbs @a n must have in its limb array. */ void bc_num_init(BcNum* restrict n, size_t req); /** * Initializes (sets up) @a n with the preallocated limb array @a num that has * size @a cap. This is called by @a bc_num_init(), but it is also used by parts * of bc that use statically allocated limb arrays. * @param n The number to initialize. * @param num The preallocated limb array. * @param cap The capacity of @a num. */ void bc_num_setup(BcNum* restrict n, BcDig* restrict num, size_t cap); /** * Copies @a s into @a d. This does a deep copy and requires that @a d is * already a valid and allocated BcNum. * @param d The destination BcNum. * @param s The source BcNum. */ void bc_num_copy(BcNum* d, const BcNum* s); /** * Creates @a d and copies @a s into @a d. This does a deep copy and requires * that @a d is *not* a valid or allocated BcNum. * @param d The destination BcNum. * @param s The source BcNum. */ void bc_num_createCopy(BcNum* d, const BcNum* s); /** * Creates (initializes) @a n and sets its value to the equivalent of @a val. * @a n must *not* be a valid or preallocated BcNum. * @param n The number to initialize and set. * @param val The value to set @a n's value to. */ void bc_num_createFromBigdig(BcNum* restrict n, BcBigDig val); /** * Makes @a n valid for holding strings. @a n must *not* be allocated; this * simply clears some fields, including setting the num field to NULL. * @param n The number to clear. */ void bc_num_clear(BcNum* restrict n); /** * Frees @a num, which is a BcNum as a void pointer. This is a destructor. * @param num The BcNum to free as a void pointer. */ void bc_num_free(void* num); /** * Returns the scale of @a n. * @param n The number. * @return The scale of @a n. */ size_t bc_num_scale(const BcNum* restrict n); /** * Returns the length (in decimal digits) of @a n. This is complicated. First, * if the number is zero, we always return at least one, but we also return the * scale if it exists. Then, If it is not zero, it opens a whole other can of * worms. Read the comments in the definition. * @param n The number. * @return The length of @a n. */ size_t bc_num_len(const BcNum* restrict n); /** * Convert a number to a BcBigDig (hardware integer). This version does error * checking, and if it finds an error, throws it. Otherwise, it calls * bc_num_bigdig2(). * @param n The number to convert. * @return The number as a hardware integer. */ BcBigDig bc_num_bigdig(const BcNum* restrict n); /** * Convert a number to a BcBigDig (hardware integer). This version does no error * checking. * @param n The number to convert. * @return The number as a hardware integer. */ BcBigDig bc_num_bigdig2(const BcNum* restrict n); /** * Sets @a n to the value of @a val. @a n is expected to be a valid and * allocated BcNum. * @param n The number to set. * @param val The value to set the number to. */ void bc_num_bigdig2num(BcNum* restrict n, BcBigDig val); #if BC_ENABLE_EXTRA_MATH /** * Generates a random arbitrary-size integer less than or equal to @a a and * returns it in @a b. This implements irand(). * @param a The limit for the integer to generate. * @param b The return value. * @param rng The pseudo-random number generator. */ void bc_num_irand(BcNum* restrict a, BcNum* restrict b, struct BcRNG* restrict rng); /** * Sets the seed for the PRNG @a rng from @a n. * @param n The new seed for the PRNG. * @param rng The PRNG to set the seed for. */ void bc_num_rng(const BcNum* restrict n, struct BcRNG* rng); /** * Sets @a n to the value produced by the PRNG. This implements rand(). * @param n The number to set. * @param rng The pseudo-random number generator. */ void bc_num_createFromRNG(BcNum* restrict n, struct BcRNG* rng); #endif // BC_ENABLE_EXTRA_MATH /** * The add function. This is a BcNumBinaryOp function. * @param a The first parameter. * @param b The second parameter. * @param c The return value. * @param scale The current scale. */ void bc_num_add(BcNum* a, BcNum* b, BcNum* c, size_t scale); /** * The subtract function. This is a BcNumBinaryOp function. * @param a The first parameter. * @param b The second parameter. * @param c The return value. * @param scale The current scale. */ void bc_num_sub(BcNum* a, BcNum* b, BcNum* c, size_t scale); /** * The multiply function. * @param a The first parameter. This is a BcNumBinaryOp function. * @param b The second parameter. * @param c The return value. * @param scale The current scale. */ void bc_num_mul(BcNum* a, BcNum* b, BcNum* c, size_t scale); /** * The division function. * @param a The first parameter. This is a BcNumBinaryOp function. * @param b The second parameter. * @param c The return value. * @param scale The current scale. */ void bc_num_div(BcNum* a, BcNum* b, BcNum* c, size_t scale); /** * The modulus function. * @param a The first parameter. This is a BcNumBinaryOp function. * @param b The second parameter. * @param c The return value. * @param scale The current scale. */ void bc_num_mod(BcNum* a, BcNum* b, BcNum* c, size_t scale); /** * The power function. * @param a The first parameter. This is a BcNumBinaryOp function. * @param b The second parameter. * @param c The return value. * @param scale The current scale. */ void bc_num_pow(BcNum* a, BcNum* b, BcNum* c, size_t scale); #if BC_ENABLE_EXTRA_MATH /** * The places function (@ operator). This is a BcNumBinaryOp function. * @param a The first parameter. * @param b The second parameter. * @param c The return value. * @param scale The current scale. */ void bc_num_places(BcNum* a, BcNum* b, BcNum* c, size_t scale); /** * The left shift function (<< operator). This is a BcNumBinaryOp function. * @param a The first parameter. * @param b The second parameter. * @param c The return value. * @param scale The current scale. */ void bc_num_lshift(BcNum* a, BcNum* b, BcNum* c, size_t scale); /** * The right shift function (>> operator). This is a BcNumBinaryOp function. * @param a The first parameter. * @param b The second parameter. * @param c The return value. * @param scale The current scale. */ void bc_num_rshift(BcNum* a, BcNum* b, BcNum* c, size_t scale); #endif // BC_ENABLE_EXTRA_MATH /** * Square root. * @param a The first parameter. * @param b The return value. * @param scale The current scale. */ void bc_num_sqrt(BcNum* restrict a, BcNum* restrict b, size_t scale); /** * Divsion and modulus together. This is a dc extension. * @param a The first parameter. * @param b The second parameter. * @param c The first return value (quotient). * @param d The second return value (modulus). * @param scale The current scale. */ void bc_num_divmod(BcNum* a, BcNum* b, BcNum* c, BcNum* d, size_t scale); /** * A function returning the required allocation size for an addition or a * subtraction. This is a BcNumBinaryOpReq function. * @param a The first parameter. * @param b The second parameter. * @param scale The current scale. * @return The size of allocation needed for the result of add or subtract * with @a a, @a b, and @a scale. */ size_t bc_num_addReq(const BcNum* a, const BcNum* b, size_t scale); /** * A function returning the required allocation size for a multiplication. This * is a BcNumBinaryOpReq function. * @param a The first parameter. * @param b The second parameter. * @param scale The current scale. * @return The size of allocation needed for the result of multiplication * with @a a, @a b, and @a scale. */ size_t bc_num_mulReq(const BcNum* a, const BcNum* b, size_t scale); /** * A function returning the required allocation size for a division or modulus. * This is a BcNumBinaryOpReq function. * @param a The first parameter. * @param b The second parameter. * @param scale The current scale. * @return The size of allocation needed for the result of division or * modulus with @a a, @a b, and @a scale. */ size_t bc_num_divReq(const BcNum* a, const BcNum* b, size_t scale); /** * A function returning the required allocation size for an exponentiation. This * is a BcNumBinaryOpReq function. * @param a The first parameter. * @param b The second parameter. * @param scale The current scale. * @return The size of allocation needed for the result of exponentiation * with @a a, @a b, and @a scale. */ size_t bc_num_powReq(const BcNum* a, const BcNum* b, size_t scale); #if BC_ENABLE_EXTRA_MATH /** * A function returning the required allocation size for a places, left shift, * or right shift. This is a BcNumBinaryOpReq function. * @param a The first parameter. * @param b The second parameter. * @param scale The current scale. * @return The size of allocation needed for the result of places, left * shift, or right shift with @a a, @a b, and @a scale. */ size_t bc_num_placesReq(const BcNum* a, const BcNum* b, size_t scale); #endif // BC_ENABLE_EXTRA_MATH /** * Truncate @a n *by* @a places decimal places. This only extends places *after* * the decimal point. * @param n The number to truncate. * @param places The number of places to truncate @a n by. */ void bc_num_truncate(BcNum* restrict n, size_t places); /** * Extend @a n *by* @a places decimal places. This only extends places *after* * the decimal point. * @param n The number to truncate. * @param places The number of places to extend @a n by. */ void bc_num_extend(BcNum* restrict n, size_t places); /** * Shifts @a n right by @a places decimal places. This is the workhorse of the * right shift operator, and would be static to src/num.c, except that * src/library.c uses it for efficiency when executing its frand. * @param n The number to shift right. * @param places The number of decimal places to shift @a n right by. */ void bc_num_shiftRight(BcNum* restrict n, size_t places); /** * Compare a and b and return the result of their comparison as an ssize_t. * Returns >0 if @a a is greater than @a b, <0 if @a a is less than @a b, and =0 * if a == b. * @param a The first number. * @param b The second number. * @return The result of the comparison. */ ssize_t bc_num_cmp(const BcNum* a, const BcNum* b); /** * Modular exponentiation. * @param a The first parameter. * @param b The second parameter. * @param c The third parameter. * @param d The return value. */ void bc_num_modexp(BcNum* a, BcNum* b, BcNum* c, BcNum* restrict d); /** * Sets @a n to zero with a scale of zero. * @param n The number to zero. */ void bc_num_zero(BcNum* restrict n); /** * Sets @a n to one with a scale of zero. * @param n The number to set to one. */ void bc_num_one(BcNum* restrict n); /** * An efficient function to compare @a n to zero. * @param n The number to compare to zero. * @return The result of the comparison. */ ssize_t bc_num_cmpZero(const BcNum* n); /** * Check a number string for validity and return true if it is, false otherwise. * The library needs this to check user-supplied strings, but in bc and dc, this * is only used for debug asserts because the parsers should get the numbers * parsed right, which should ensure they are always valid. * @param val The string to check. * @return True if the string is a valid number, false otherwise. */ bool bc_num_strValid(const char* restrict val); /** * Parses a number string into the number @a n according to @a base. * @param n The number to set to the parsed value. * @param val The number string to parse. * @param base The base to parse the number string by. */ void bc_num_parse(BcNum* restrict n, const char* restrict val, BcBigDig base); /** * Prints the number @a n according to @a base. * @param n The number to print. * @param base The base to print the number by. * @param newline True if a newline should be inserted at the end, false * otherwise. */ void bc_num_print(BcNum* restrict n, BcBigDig base, bool newline); /** * Invert @a into @a b at the current scale. * @param a The number to invert. * @param b The return parameter. This must be preallocated. * @param scale The current scale. */ #define bc_num_inv(a, b, scale) bc_num_div(&vm->one, (a), (b), (scale)) #if !BC_ENABLE_LIBRARY /** * Prints a number as a character stream. * @param n The number to print as a character stream. */ void bc_num_stream(BcNum* restrict n); #endif // !BC_ENABLE_LIBRARY #if BC_DEBUG_CODE /** * Print a number with a label. This is a debug-only function. * @param n The number to print. * @param name The label to print the number with. * @param emptyline True if there should be an empty line after the number. */ void bc_num_printDebug(const BcNum* n, const char* name, bool emptyline); /** * Print the limbs of @a n. This is a debug-only function. * @param n The number to print. * @param len The length of the number. * @param emptyline True if there should be an empty line after the number. */ void bc_num_printDigs(const BcDig* n, size_t len, bool emptyline); /** * Print debug info about @a n along with its limbs. * @param n The number to print. * @param name The label to print the number with. * @param emptyline True if there should be an empty line after the number. */ void bc_num_printWithDigs(const BcNum* n, const char* name, bool emptyline); /** * Dump debug info about a BcNum variable. * @param varname The variable name. * @param n The number. */ void bc_num_dump(const char* varname, const BcNum* n); #endif // BC_DEBUG_CODE /// A reference to an array of hex digits for easy conversion for printing. extern const char bc_num_hex_digits[]; /// An array of powers of 10 for easy conversion from number of digits to /// powers. extern const BcBigDig bc_num_pow10[BC_BASE_DIGS + 1]; /// A reference to a constant array that is the max of a BigDig. extern const BcDig bc_num_bigdigMax[]; /// A reference to a constant size of the above array. extern const size_t bc_num_bigdigMax_size; /// A reference to a constant array that is 2 times the max of a BigDig. extern const BcDig bc_num_bigdigMax2[]; /// A reference to a constant size of the above array. extern const size_t bc_num_bigdigMax2_size; #endif // BC_NUM_H diff --git a/contrib/bc/include/status.h b/contrib/bc/include/status.h index 198cf5704a57..242514edb476 100644 --- a/contrib/bc/include/status.h +++ b/contrib/bc/include/status.h @@ -1,1035 +1,1042 @@ /* * ***************************************************************************** * * 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. * * ***************************************************************************** * * All bc status codes and cross-platform portability. * */ #ifndef BC_STATUS_H #define BC_STATUS_H #ifdef _WIN32 #include #include #include #include #endif // _WIN32 #include #include // This is used by configure.sh to test for OpenBSD. #ifdef BC_TEST_OPENBSD #ifdef __OpenBSD__ #error On OpenBSD without _BSD_SOURCE #endif // __OpenBSD__ #endif // BC_TEST_OPENBSD // This is used by configure.sh to test for FreeBSD. #ifdef BC_TEST_FREEBSD #ifdef __FreeBSD__ #error On FreeBSD with _POSIX_C_SOURCE #endif // __FreeBSD__ #endif // BC_TEST_FREEBSD +// This is used by configure.sh to test for Mac OSX. +#ifdef BC_TEST_APPLE +#ifdef __APPLE__ +#error On Mac OSX without _DARWIN_C_SOURCE +#endif // __APPLE__ +#endif // BC_TEST_APPLE + // Windows has deprecated isatty() and the rest of these. Or doesn't have them. // So these are just fixes for Windows. #ifdef _WIN32 // This one is special. Windows did not like me defining an // inline function that was not given a definition in a header // file. This suppresses that by making inline functions non-inline. #define inline #define restrict __restrict #define strdup _strdup #define write(f, b, s) _write((f), (b), (unsigned int) (s)) #define read(f, b, s) _read((f), (b), (unsigned int) (s)) #define close _close #define open(f, n, m) \ _sopen_s((f), (n), (m) | _O_BINARY, _SH_DENYNO, _S_IREAD | _S_IWRITE) #define sigjmp_buf jmp_buf #define sigsetjmp(j, s) setjmp(j) #define siglongjmp longjmp #define isatty _isatty #define STDIN_FILENO _fileno(stdin) #define STDOUT_FILENO _fileno(stdout) #define STDERR_FILENO _fileno(stderr) #define S_ISDIR(m) ((m) & (_S_IFDIR)) #define O_RDONLY _O_RDONLY #define stat _stat #define fstat _fstat #define BC_FILE_SEP '\\' #else // _WIN32 #define BC_FILE_SEP '/' #endif // _WIN32 #ifndef BC_ENABLED #define BC_ENABLED (1) #endif // BC_ENABLED #ifndef DC_ENABLED #define DC_ENABLED (1) #endif // DC_ENABLED #ifndef BC_ENABLE_EXTRA_MATH #define BC_ENABLE_EXTRA_MATH (1) #endif // BC_ENABLE_EXTRA_MATH #ifndef BC_ENABLE_LIBRARY #define BC_ENABLE_LIBRARY (0) #endif // BC_ENABLE_LIBRARY #ifndef BC_ENABLE_HISTORY #define BC_ENABLE_HISTORY (1) #endif // BC_ENABLE_HISTORY #ifndef BC_ENABLE_EDITLINE #define BC_ENABLE_EDITLINE (0) #endif // BC_ENABLE_EDITLINE #ifndef BC_ENABLE_READLINE #define BC_ENABLE_READLINE (0) #endif // BC_ENABLE_READLINE #ifndef BC_ENABLE_NLS #define BC_ENABLE_NLS (0) #endif // BC_ENABLE_NLS #ifdef __OpenBSD__ #if BC_ENABLE_READLINE #error Cannot use readline on OpenBSD #endif // BC_ENABLE_READLINE #endif // __OpenBSD__ #if BC_ENABLE_EDITLINE && BC_ENABLE_READLINE #error Must enable only one of editline or readline, not both. #endif // BC_ENABLE_EDITLINE && BC_ENABLE_READLINE #if BC_ENABLE_EDITLINE || BC_ENABLE_READLINE #define BC_ENABLE_LINE_LIB (1) #else // BC_ENABLE_EDITLINE || BC_ENABLE_READLINE #define BC_ENABLE_LINE_LIB (0) #endif // BC_ENABLE_EDITLINE || BC_ENABLE_READLINE // This is error checking for fuzz builds. #if BC_ENABLE_AFL #ifndef __AFL_HAVE_MANUAL_CONTROL #error Must compile with afl-clang-fast or afl-clang-lto for fuzzing #endif // __AFL_HAVE_MANUAL_CONTROL #endif // BC_ENABLE_AFL #ifndef BC_ENABLE_MEMCHECK #define BC_ENABLE_MEMCHECK (0) #endif // BC_ENABLE_MEMCHECK /** * Mark a variable as unused. * @param e The variable to mark as unused. */ #define BC_UNUSED(e) ((void) (e)) // If users want, they can define this to something like __builtin_expect(e, 1). // It might give a performance improvement. #ifndef BC_LIKELY /** * Mark a branch expression as likely. * @param e The expression to mark as likely. */ #define BC_LIKELY(e) (e) #endif // BC_LIKELY // If users want, they can define this to something like __builtin_expect(e, 0). // It might give a performance improvement. #ifndef BC_UNLIKELY /** * Mark a branch expression as unlikely. * @param e The expression to mark as unlikely. */ #define BC_UNLIKELY(e) (e) #endif // BC_UNLIKELY /** * Mark a branch expression as an error, if true. * @param e The expression to mark as an error, if true. */ #define BC_ERR(e) BC_UNLIKELY(e) /** * Mark a branch expression as not an error, if true. * @param e The expression to mark as not an error, if true. */ #define BC_NO_ERR(s) BC_LIKELY(s) // Disable extra debug code by default. #ifndef BC_DEBUG_CODE #define BC_DEBUG_CODE (0) #endif // BC_DEBUG_CODE #if defined(__clang__) #define BC_CLANG (1) #else // defined(__clang__) #define BC_CLANG (0) #endif // defined(__clang__) #if defined(__GNUC__) && !BC_CLANG #define BC_GCC (1) #else // defined(__GNUC__) && !BC_CLANG #define BC_GCC (0) #endif // defined(__GNUC__) && !BC_CLANG // We want to be able to use _Noreturn on C11 compilers. #if __STDC_VERSION__ >= 201112L #include #define BC_NORETURN _Noreturn #define BC_C11 (1) #else // __STDC_VERSION__ #if BC_CLANG #if __has_attribute(noreturn) #define BC_NORETURN __attribute((noreturn)) #else // __has_attribute(noreturn) #define BC_NORETURN #endif // __has_attribute(noreturn) #else // BC_CLANG #define BC_NORETURN #endif // BC_CLANG #define BC_MUST_RETURN #define BC_C11 (0) #endif // __STDC_VERSION__ #define BC_HAS_UNREACHABLE (0) #define BC_HAS_COMPUTED_GOTO (0) // GCC and Clang complain if fallthroughs are not marked with their special // attribute. Jerks. This creates a define for marking the fallthroughs that is // nothing on other compilers. #if BC_CLANG || BC_GCC #if defined(__has_attribute) #if __has_attribute(fallthrough) #define BC_FALLTHROUGH __attribute__((fallthrough)); #else // __has_attribute(fallthrough) #define BC_FALLTHROUGH #endif // __has_attribute(fallthrough) #if BC_GCC #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) #undef BC_HAS_UNREACHABLE #define BC_HAS_UNREACHABLE (1) #endif // __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) #else // BC_GCC #if __clang_major__ >= 4 #undef BC_HAS_UNREACHABLE #define BC_HAS_UNREACHABLE (1) #endif // __clang_major__ >= 4 #endif // BC_GCC #else // defined(__has_attribute) #define BC_FALLTHROUGH #endif // defined(__has_attribute) #else // BC_CLANG || BC_GCC #define BC_FALLTHROUGH #endif // BC_CLANG || BC_GCC #if BC_HAS_UNREACHABLE #define BC_UNREACHABLE __builtin_unreachable(); #else // BC_HAS_UNREACHABLE #ifdef _WIN32 #define BC_UNREACHABLE __assume(0); #else // _WIN32 #define BC_UNREACHABLE #endif // _WIN32 #endif // BC_HAS_UNREACHABLE #if BC_GCC #if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) #undef BC_HAS_COMPUTED_GOTO #define BC_HAS_COMPUTED_GOTO (1) #endif // __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5) #endif // BC_GCC #if BC_CLANG #if __clang_major__ >= 4 #undef BC_HAS_COMPUTED_GOTO #define BC_HAS_COMPUTED_GOTO (1) #endif // __clang_major__ >= 4 #endif // BC_CLANG #ifdef BC_NO_COMPUTED_GOTO #undef BC_HAS_COMPUTED_GOTO #define BC_HAS_COMPUTED_GOTO (0) #endif // BC_NO_COMPUTED_GOTO #if BC_GCC #ifdef __OpenBSD__ // The OpenBSD GCC doesn't like inline. #define inline #endif // __OpenBSD__ #endif // BC_GCC // Workarounds for AIX's POSIX incompatibility. #ifndef SIZE_MAX #define SIZE_MAX __SIZE_MAX__ #endif // SIZE_MAX #ifndef UINTMAX_C #define UINTMAX_C __UINTMAX_C #endif // UINTMAX_C #ifndef UINT32_C #define UINT32_C __UINT32_C #endif // UINT32_C #ifndef UINT_FAST32_MAX #define UINT_FAST32_MAX __UINT_FAST32_MAX__ #endif // UINT_FAST32_MAX #ifndef UINT16_MAX #define UINT16_MAX __UINT16_MAX__ #endif // UINT16_MAX #ifndef SIG_ATOMIC_MAX #define SIG_ATOMIC_MAX __SIG_ATOMIC_MAX__ #endif // SIG_ATOMIC_MAX // Yes, this has to be here. #include // All of these set defaults for settings. #if BC_ENABLED #ifndef BC_DEFAULT_BANNER #define BC_DEFAULT_BANNER (0) #endif // BC_DEFAULT_BANNER #endif // BC_ENABLED #ifndef BC_DEFAULT_SIGINT_RESET #define BC_DEFAULT_SIGINT_RESET (1) #endif // BC_DEFAULT_SIGINT_RESET #ifndef BC_DEFAULT_TTY_MODE #define BC_DEFAULT_TTY_MODE (1) #endif // BC_DEFAULT_TTY_MODE #ifndef BC_DEFAULT_PROMPT #define BC_DEFAULT_PROMPT BC_DEFAULT_TTY_MODE #endif // BC_DEFAULT_PROMPT #ifndef BC_DEFAULT_EXPR_EXIT #define BC_DEFAULT_EXPR_EXIT (1) #endif // BC_DEFAULT_EXPR_EXIT #ifndef BC_DEFAULT_DIGIT_CLAMP #define BC_DEFAULT_DIGIT_CLAMP (0) #endif // BC_DEFAULT_DIGIT_CLAMP // All of these set defaults for settings. #ifndef DC_DEFAULT_SIGINT_RESET #define DC_DEFAULT_SIGINT_RESET (1) #endif // DC_DEFAULT_SIGINT_RESET #ifndef DC_DEFAULT_TTY_MODE #define DC_DEFAULT_TTY_MODE (0) #endif // DC_DEFAULT_TTY_MODE #ifndef DC_DEFAULT_HISTORY #define DC_DEFAULT_HISTORY DC_DEFAULT_TTY_MODE #endif // DC_DEFAULT_HISTORY #ifndef DC_DEFAULT_PROMPT #define DC_DEFAULT_PROMPT DC_DEFAULT_TTY_MODE #endif // DC_DEFAULT_PROMPT #ifndef DC_DEFAULT_EXPR_EXIT #define DC_DEFAULT_EXPR_EXIT (1) #endif // DC_DEFAULT_EXPR_EXIT #ifndef DC_DEFAULT_DIGIT_CLAMP #define DC_DEFAULT_DIGIT_CLAMP (0) #endif // DC_DEFAULT_DIGIT_CLAMP /// Statuses, which mark either which category of error happened, or some other /// status that matters. typedef enum BcStatus { /// Normal status. BC_STATUS_SUCCESS = 0, /// Math error. BC_STATUS_ERROR_MATH, /// Parse (and lex) error. BC_STATUS_ERROR_PARSE, /// Runtime error. BC_STATUS_ERROR_EXEC, /// Fatal error. BC_STATUS_ERROR_FATAL, /// EOF status. BC_STATUS_EOF, /// Quit status. This means that bc/dc is in the process of quitting. BC_STATUS_QUIT, } BcStatus; /// Errors, which are more specific errors. typedef enum BcErr { // Math errors. /// Negative number used when not allowed. BC_ERR_MATH_NEGATIVE, /// Non-integer used when not allowed. BC_ERR_MATH_NON_INTEGER, /// Conversion to a hardware integer would overflow. BC_ERR_MATH_OVERFLOW, /// Divide by zero. BC_ERR_MATH_DIVIDE_BY_ZERO, // Fatal errors. /// An allocation or reallocation failed. BC_ERR_FATAL_ALLOC_ERR, /// I/O failure. BC_ERR_FATAL_IO_ERR, /// File error, such as permissions or file does not exist. BC_ERR_FATAL_FILE_ERR, /// File is binary, not text, error. BC_ERR_FATAL_BIN_FILE, /// Attempted to read a directory as a file error. BC_ERR_FATAL_PATH_DIR, /// Invalid option error. BC_ERR_FATAL_OPTION, /// Option with required argument not given an argument. BC_ERR_FATAL_OPTION_NO_ARG, /// Option with no argument given an argument. BC_ERR_FATAL_OPTION_ARG, /// Option argument is invalid. BC_ERR_FATAL_ARG, // Runtime errors. /// Invalid ibase value. BC_ERR_EXEC_IBASE, /// Invalid obase value. BC_ERR_EXEC_OBASE, /// Invalid scale value. BC_ERR_EXEC_SCALE, /// Invalid expression parsed by read(). BC_ERR_EXEC_READ_EXPR, /// read() used within an expression given to a read() call. BC_ERR_EXEC_REC_READ, /// Type error. BC_ERR_EXEC_TYPE, /// Stack has too few elements error. BC_ERR_EXEC_STACK, /// Register stack has too few elements error. BC_ERR_EXEC_STACK_REGISTER, /// Wrong number of arguments error. BC_ERR_EXEC_PARAMS, /// Undefined function error. BC_ERR_EXEC_UNDEF_FUNC, /// Void value used in an expression error. BC_ERR_EXEC_VOID_VAL, // Parse (and lex) errors. /// EOF encountered when not expected error. BC_ERR_PARSE_EOF, /// Invalid character error. BC_ERR_PARSE_CHAR, /// Invalid string (no ending quote) error. BC_ERR_PARSE_STRING, /// Invalid comment (no end found) error. BC_ERR_PARSE_COMMENT, /// Invalid token encountered error. BC_ERR_PARSE_TOKEN, #if BC_ENABLED /// Invalid expression error. BC_ERR_PARSE_EXPR, /// Expression is empty error. BC_ERR_PARSE_EMPTY_EXPR, /// Print statement is invalid error. BC_ERR_PARSE_PRINT, /// Function definition is invalid error. BC_ERR_PARSE_FUNC, /// Assignment is invalid error. BC_ERR_PARSE_ASSIGN, /// No auto identifiers given for an auto statement error. BC_ERR_PARSE_NO_AUTO, /// Duplicate local (parameter or auto) error. BC_ERR_PARSE_DUP_LOCAL, /// Invalid block (within braces) error. BC_ERR_PARSE_BLOCK, /// Invalid return statement for void functions. BC_ERR_PARSE_RET_VOID, /// Reference attached to a variable, not an array, error. BC_ERR_PARSE_REF_VAR, // POSIX-only errors. /// Name length greater than 1 error. BC_ERR_POSIX_NAME_LEN, /// Non-POSIX comment used error. BC_ERR_POSIX_COMMENT, /// Non-POSIX keyword error. BC_ERR_POSIX_KW, /// Non-POSIX . (last) error. BC_ERR_POSIX_DOT, /// Non-POSIX return error. BC_ERR_POSIX_RET, /// Non-POSIX boolean operator used error. BC_ERR_POSIX_BOOL, /// POSIX relation operator used outside if, while, or for statements error. BC_ERR_POSIX_REL_POS, /// Multiple POSIX relation operators used in an if, while, or for statement /// error. BC_ERR_POSIX_MULTIREL, /// Empty statements in POSIX for loop error. BC_ERR_POSIX_FOR, /// POSIX's grammar does not allow a function definition right after a /// semicolon. BC_ERR_POSIX_FUNC_AFTER_SEMICOLON, /// Non-POSIX exponential (scientific or engineering) number used error. BC_ERR_POSIX_EXP_NUM, /// Non-POSIX array reference error. BC_ERR_POSIX_REF, /// Non-POSIX void error. BC_ERR_POSIX_VOID, /// Non-POSIX brace position used error. BC_ERR_POSIX_BRACE, /// String used in expression. BC_ERR_POSIX_EXPR_STRING, #endif // BC_ENABLED // Number of elements. BC_ERR_NELEMS, #if BC_ENABLED /// A marker for the start of POSIX errors. BC_ERR_POSIX_START = BC_ERR_POSIX_NAME_LEN, /// A marker for the end of POSIX errors. BC_ERR_POSIX_END = BC_ERR_POSIX_EXPR_STRING, #endif // BC_ENABLED } BcErr; // The indices of each category of error in bc_errs[], and used in bc_err_ids[] // to associate actual errors with their categories. /// Math error category. #define BC_ERR_IDX_MATH (0) /// Parse (and lex) error category. #define BC_ERR_IDX_PARSE (1) /// Runtime error category. #define BC_ERR_IDX_EXEC (2) /// Fatal error category. #define BC_ERR_IDX_FATAL (3) /// Number of categories. #define BC_ERR_IDX_NELEMS (4) // If bc is enabled, we add an extra category for POSIX warnings. #if BC_ENABLED /// POSIX warning category. #define BC_ERR_IDX_WARN (BC_ERR_IDX_NELEMS) #endif // BC_ENABLED /** * The mode bc is in. This is basically what input it is processing. */ typedef enum BcMode { /// Expressions mode. BC_MODE_EXPRS, /// File mode. BC_MODE_FILE, /// stdin mode. BC_MODE_STDIN, } BcMode; /// Do a longjmp(). This is what to use when activating an "exception", i.e., a /// longjmp(). With debug code, it will print the name of the function it jumped /// from. #if BC_DEBUG_CODE #define BC_JMP bc_vm_jmp(__func__) #else // BC_DEBUG_CODE #define BC_JMP bc_vm_jmp() #endif // BC_DEBUG_CODE #if !BC_ENABLE_LIBRARY /// Returns true if an exception is in flight, false otherwise. #define BC_SIG_EXC(vm) \ BC_UNLIKELY((vm)->status != (sig_atomic_t) BC_STATUS_SUCCESS || (vm)->sig) /// Returns true if there is *no* exception in flight, false otherwise. #define BC_NO_SIG_EXC(vm) \ BC_LIKELY((vm)->status == (sig_atomic_t) BC_STATUS_SUCCESS && !(vm)->sig) #ifndef _WIN32 #define BC_SIG_INTERRUPT(vm) \ BC_UNLIKELY((vm)->sig != 0 && (vm)->sig != SIGWINCH) #else // _WIN32 #define BC_SIG_INTERRUPT(vm) BC_UNLIKELY((vm)->sig != 0) #endif // _WIN32 #if BC_DEBUG /// Assert that signals are locked. There are non-async-signal-safe functions in /// bc, and they *must* have signals locked. Other functions are expected to /// *not* have signals locked, for reasons. So this is a pre-built assert /// (no-op in non-debug mode) that check that signals are locked. #define BC_SIG_ASSERT_LOCKED \ do \ { \ assert(vm->sig_lock); \ } \ while (0) /// Assert that signals are unlocked. There are non-async-signal-safe functions /// in bc, and they *must* have signals locked. Other functions are expected to /// *not* have signals locked, for reasons. So this is a pre-built assert /// (no-op in non-debug mode) that check that signals are unlocked. #define BC_SIG_ASSERT_NOT_LOCKED \ do \ { \ assert(vm->sig_lock == 0); \ } \ while (0) #else // BC_DEBUG /// Assert that signals are locked. There are non-async-signal-safe functions in /// bc, and they *must* have signals locked. Other functions are expected to /// *not* have signals locked, for reasons. So this is a pre-built assert /// (no-op in non-debug mode) that check that signals are locked. #define BC_SIG_ASSERT_LOCKED /// Assert that signals are unlocked. There are non-async-signal-safe functions /// in bc, and they *must* have signals locked. Other functions are expected to /// *not* have signals locked, for reasons. So this is a pre-built assert /// (no-op in non-debug mode) that check that signals are unlocked. #define BC_SIG_ASSERT_NOT_LOCKED #endif // BC_DEBUG /// Locks signals. #define BC_SIG_LOCK \ do \ { \ BC_SIG_ASSERT_NOT_LOCKED; \ vm->sig_lock = 1; \ } \ while (0) /// Unlocks signals. If a signal happened, then this will cause a jump. #define BC_SIG_UNLOCK \ do \ { \ BC_SIG_ASSERT_LOCKED; \ vm->sig_lock = 0; \ if (vm->sig) BC_JMP; \ } \ while (0) /// Locks signals, regardless of if they are already locked. This is really only /// used after labels that longjmp() goes to after the jump because the cleanup /// code must have signals locked, and BC_LONGJMP_CONT will unlock signals if it /// doesn't jump. #define BC_SIG_MAYLOCK \ do \ { \ vm->sig_lock = 1; \ } \ while (0) /// Unlocks signals, regardless of if they were already unlocked. If a signal /// happened, then this will cause a jump. #define BC_SIG_MAYUNLOCK \ do \ { \ vm->sig_lock = 0; \ if (vm->sig) BC_JMP; \ } \ while (0) /** * Locks signals, but stores the old lock state, to be restored later by * BC_SIG_TRYUNLOCK. * @param v The variable to store the old lock state to. */ #define BC_SIG_TRYLOCK(v) \ do \ { \ v = vm->sig_lock; \ vm->sig_lock = 1; \ } \ while (0) /** * Restores the previous state of a signal lock, and if it is now unlocked, * initiates an exception/jump. * @param v The old lock state. */ #define BC_SIG_TRYUNLOCK(v) \ do \ { \ vm->sig_lock = (v); \ if (!(v) && vm->sig) BC_JMP; \ } \ while (0) /// Stops a stack unwinding. Technically, a stack unwinding needs to be done /// manually, but it will always be done unless certain flags are cleared. This /// clears the flags. #define BC_LONGJMP_STOP \ do \ { \ vm->sig_pop = 0; \ vm->sig = 0; \ } \ while (0) /** * Sets a jump like BC_SETJMP, but unlike BC_SETJMP, it assumes signals are * locked and will just set the jump. This does *not* have a call to * bc_vec_grow() because it is assumed that BC_SETJMP_LOCKED(l) is used *after* * the initializations that need the setjmp(). * param l The label to jump to on a longjmp(). */ #define BC_SETJMP_LOCKED(vm, l) \ do \ { \ sigjmp_buf sjb; \ BC_SIG_ASSERT_LOCKED; \ if (sigsetjmp(sjb, 0)) \ { \ assert(BC_SIG_EXC(vm)); \ goto l; \ } \ bc_vec_push(&vm->jmp_bufs, &sjb); \ } \ while (0) /// Used after cleanup labels set by BC_SETJMP and BC_SETJMP_LOCKED to jump to /// the next place. This is what continues the stack unwinding. This basically /// copies BC_SIG_UNLOCK into itself, but that is because its condition for /// jumping is BC_SIG_EXC, not just that a signal happened. #define BC_LONGJMP_CONT(vm) \ do \ { \ BC_SIG_ASSERT_LOCKED; \ if (!vm->sig_pop) bc_vec_pop(&vm->jmp_bufs); \ vm->sig_lock = 0; \ if (BC_SIG_EXC(vm)) BC_JMP; \ } \ while (0) #else // !BC_ENABLE_LIBRARY #define BC_SIG_LOCK #define BC_SIG_UNLOCK #define BC_SIG_MAYLOCK #define BC_SIG_TRYLOCK(lock) #define BC_SIG_TRYUNLOCK(lock) #define BC_SIG_ASSERT_LOCKED /// Returns true if an exception is in flight, false otherwise. #define BC_SIG_EXC(vm) \ BC_UNLIKELY(vm->status != (sig_atomic_t) BC_STATUS_SUCCESS) /// Returns true if there is *no* exception in flight, false otherwise. #define BC_NO_SIG_EXC(vm) \ BC_LIKELY(vm->status == (sig_atomic_t) BC_STATUS_SUCCESS) /// Used after cleanup labels set by BC_SETJMP and BC_SETJMP_LOCKED to jump to /// the next place. This is what continues the stack unwinding. This basically /// copies BC_SIG_UNLOCK into itself, but that is because its condition for /// jumping is BC_SIG_EXC, not just that a signal happened. #define BC_LONGJMP_CONT(vm) \ do \ { \ bc_vec_pop(&vm->jmp_bufs); \ if (BC_SIG_EXC(vm)) BC_JMP; \ } \ while (0) #endif // !BC_ENABLE_LIBRARY /** * Sets a jump, and sets it up as well so that if a longjmp() happens, bc will * immediately goto a label where some cleanup code is. This one assumes that * signals are not locked and will lock them, set the jump, and unlock them. * Setting the jump also includes pushing the jmp_buf onto the jmp_buf stack. * This grows the jmp_bufs vector first to prevent a fatal error from happening * after the setjmp(). This is done because BC_SETJMP(l) is assumed to be used * *before* the actual initialization calls that need the setjmp(). * param l The label to jump to on a longjmp(). */ #define BC_SETJMP(vm, l) \ do \ { \ sigjmp_buf sjb; \ BC_SIG_LOCK; \ bc_vec_grow(&vm->jmp_bufs, 1); \ if (sigsetjmp(sjb, 0)) \ { \ assert(BC_SIG_EXC(vm)); \ goto l; \ } \ bc_vec_push(&vm->jmp_bufs, &sjb); \ BC_SIG_UNLOCK; \ } \ while (0) /// Unsets a jump. It always assumes signals are locked. This basically just /// pops a jmp_buf off of the stack of jmp_bufs, and since the jump mechanism /// always jumps to the location at the top of the stack, this effectively /// undoes a setjmp(). #define BC_UNSETJMP(vm) \ do \ { \ BC_SIG_ASSERT_LOCKED; \ bc_vec_pop(&vm->jmp_bufs); \ } \ while (0) #if BC_ENABLE_LIBRARY #define BC_SETJMP_LOCKED(vm, l) BC_SETJMP(vm, l) // Various convenience macros for calling the bc's error handling routine. /** * Call bc's error handling routine. * @param e The error. * @param l The line of the script that the error happened. * @param ... Extra arguments for error messages as necessary. */ #define bc_error(e, l, ...) (bc_vm_handleError((e))) /** * Call bc's error handling routine. * @param e The error. */ #define bc_err(e) (bc_vm_handleError((e))) /** * Call bc's error handling routine. * @param e The error. */ #define bc_verr(e, ...) (bc_vm_handleError((e))) #else // BC_ENABLE_LIBRARY // Various convenience macros for calling the bc's error handling routine. /** * Call bc's error handling routine. * @param e The error. * @param l The line of the script that the error happened. * @param ... Extra arguments for error messages as necessary. */ #if BC_DEBUG #define bc_error(e, l, ...) \ (bc_vm_handleError((e), __FILE__, __LINE__, (l), __VA_ARGS__)) #else // BC_DEBUG #define bc_error(e, l, ...) (bc_vm_handleError((e), (l), __VA_ARGS__)) #endif // BC_DEBUG /** * Call bc's error handling routine. * @param e The error. */ #if BC_DEBUG #define bc_err(e) (bc_vm_handleError((e), __FILE__, __LINE__, 0)) #else // BC_DEBUG #define bc_err(e) (bc_vm_handleError((e), 0)) #endif // BC_DEBUG /** * Call bc's error handling routine. * @param e The error. */ #if BC_DEBUG #define bc_verr(e, ...) \ (bc_vm_handleError((e), __FILE__, __LINE__, 0, __VA_ARGS__)) #else // BC_DEBUG #define bc_verr(e, ...) (bc_vm_handleError((e), 0, __VA_ARGS__)) #endif // BC_DEBUG #endif // BC_ENABLE_LIBRARY /** * Returns true if status @a s is an error, false otherwise. * @param s The status to test. * @return True if @a s is an error, false otherwise. */ #define BC_STATUS_IS_ERROR(s) \ ((s) >= BC_STATUS_ERROR_MATH && (s) <= BC_STATUS_ERROR_FATAL) // Convenience macros that can be placed at the beginning and exits of functions // for easy marking of where functions are entered and exited. #if BC_DEBUG_CODE #define BC_FUNC_ENTER \ do \ { \ size_t bc_func_enter_i; \ for (bc_func_enter_i = 0; bc_func_enter_i < vm->func_depth; \ ++bc_func_enter_i) \ { \ bc_file_puts(&vm->ferr, bc_flush_none, " "); \ } \ vm->func_depth += 1; \ bc_file_printf(&vm->ferr, "Entering %s\n", __func__); \ bc_file_flush(&vm->ferr, bc_flush_none); \ } \ while (0); #define BC_FUNC_EXIT \ do \ { \ size_t bc_func_enter_i; \ vm->func_depth -= 1; \ for (bc_func_enter_i = 0; bc_func_enter_i < vm->func_depth; \ ++bc_func_enter_i) \ { \ bc_file_puts(&vm->ferr, bc_flush_none, " "); \ } \ bc_file_printf(&vm->ferr, "Leaving %s\n", __func__); \ bc_file_flush(&vm->ferr, bc_flush_none); \ } \ while (0); #else // BC_DEBUG_CODE #define BC_FUNC_ENTER #define BC_FUNC_EXIT #endif // BC_DEBUG_CODE #endif // BC_STATUS_H diff --git a/contrib/bc/include/version.h b/contrib/bc/include/version.h index daa1977c3cb6..a4df383e284a 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.5.0 +#define VERSION 6.6.0 #endif // BC_VERSION_H diff --git a/contrib/bc/src/num.c b/contrib/bc/src/num.c index 8f70c6a409d1..0a59707268df 100644 --- a/contrib/bc/src/num.c +++ b/contrib/bc/src/num.c @@ -1,4406 +1,4459 @@ /* * ***************************************************************************** * * 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 for the number type. * */ #include #include #include #include #include #include #include #include #include #include #if BC_ENABLE_LIBRARY #include #endif // BC_ENABLE_LIBRARY // Before you try to understand this code, see the development manual // (manuals/development.md#numbers). static void bc_num_m(BcNum* a, BcNum* b, BcNum* restrict c, size_t scale); /** * Multiply two numbers and throw a math error if they overflow. * @param a The first operand. * @param b The second operand. * @return The product of the two operands. */ static inline size_t bc_num_mulOverflow(size_t a, size_t b) { size_t res = a * b; if (BC_ERR(BC_VM_MUL_OVERFLOW(a, b, res))) bc_err(BC_ERR_MATH_OVERFLOW); return res; } /** * Conditionally negate @a n based on @a neg. Algorithm taken from * https://graphics.stanford.edu/~seander/bithacks.html#ConditionalNegate . * @param n The value to turn into a signed value and negate. * @param neg The condition to negate or not. */ static inline ssize_t bc_num_neg(size_t n, bool neg) { return (((ssize_t) n) ^ -((ssize_t) neg)) + neg; } /** * Compare a BcNum against zero. * @param n The number to compare. * @return -1 if the number is less than 0, 1 if greater, and 0 if equal. */ ssize_t bc_num_cmpZero(const BcNum* n) { return bc_num_neg((n)->len != 0, BC_NUM_NEG(n)); } /** * Return the number of integer limbs in a BcNum. This is the opposite of rdx. * @param n The number to return the amount of integer limbs for. * @return The amount of integer limbs in @a n. */ static inline size_t bc_num_int(const BcNum* n) { return n->len ? n->len - BC_NUM_RDX_VAL(n) : 0; } /** * Expand a number's allocation capacity to at least req limbs. * @param n The number to expand. * @param req The number limbs to expand the allocation capacity to. */ static void bc_num_expand(BcNum* restrict n, size_t req) { assert(n != NULL); req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE; if (req > n->cap) { BC_SIG_LOCK; n->num = bc_vm_realloc(n->num, BC_NUM_SIZE(req)); n->cap = req; BC_SIG_UNLOCK; } } /** * Set a number to 0 with the specified scale. * @param n The number to set to zero. * @param scale The scale to set the number to. */ static inline void bc_num_setToZero(BcNum* restrict n, size_t scale) { assert(n != NULL); n->scale = scale; n->len = n->rdx = 0; } void bc_num_zero(BcNum* restrict n) { bc_num_setToZero(n, 0); } void bc_num_one(BcNum* restrict n) { bc_num_zero(n); n->len = 1; n->num[0] = 1; } /** * "Cleans" a number, which means reducing the length if the most significant * limbs are zero. * @param n The number to clean. */ static void bc_num_clean(BcNum* restrict n) { // Reduce the length. while (BC_NUM_NONZERO(n) && !n->num[n->len - 1]) { n->len -= 1; } // Special cases. if (BC_NUM_ZERO(n)) n->rdx = 0; else { // len must be at least as much as rdx. size_t rdx = BC_NUM_RDX_VAL(n); if (n->len < rdx) n->len = rdx; } } /** * Returns the log base 10 of @a i. I could have done this with floating-point * math, and in fact, I originally did. However, that was the only * floating-point code in the entire codebase, and I decided I didn't want any. * This is fast enough. Also, it might handle larger numbers better. * @param i The number to return the log base 10 of. * @return The log base 10 of @a i. */ static size_t bc_num_log10(size_t i) { size_t len; for (len = 1; i; i /= BC_BASE, ++len) { continue; } assert(len - 1 <= BC_BASE_DIGS + 1); return len - 1; } /** * Returns the number of decimal digits in a limb that are zero starting at the * most significant digits. This basically returns how much of the limb is used. * @param n The number. * @return The number of decimal digits that are 0 starting at the most * significant digits. */ static inline size_t bc_num_zeroDigits(const BcDig* n) { assert(*n >= 0); assert(((size_t) *n) < BC_BASE_POW); return BC_BASE_DIGS - bc_num_log10((size_t) *n); } /** * Return the total number of integer digits in a number. This is the opposite * of scale, like bc_num_int() is the opposite of rdx. * @param n The number. * @return The number of integer digits in @a n. */ static size_t bc_num_intDigits(const BcNum* n) { size_t digits = bc_num_int(n) * BC_BASE_DIGS; if (digits > 0) digits -= bc_num_zeroDigits(n->num + n->len - 1); return digits; } /** * Returns the number of limbs of a number that are non-zero starting at the * most significant limbs. This expects that there are *no* integer limbs in the * number because it is specifically to figure out how many zero limbs after the * decimal place to ignore. If there are zero limbs after non-zero limbs, they * are counted as non-zero limbs. * @param n The number. * @return The number of non-zero limbs after the decimal point. */ static size_t bc_num_nonZeroLen(const BcNum* restrict n) { size_t i, len = n->len; assert(len == BC_NUM_RDX_VAL(n)); for (i = len - 1; i < len && !n->num[i]; --i) { continue; } assert(i + 1 > 0); return i + 1; } /** * Performs a one-limb add with a carry. * @param a The first limb. * @param b The second limb. * @param carry An in/out parameter; the carry in from the previous add and the * carry out from this add. * @return The resulting limb sum. */ static BcDig bc_num_addDigits(BcDig a, BcDig b, bool* carry) { assert(((BcBigDig) BC_BASE_POW) * 2 == ((BcDig) BC_BASE_POW) * 2); assert(a < BC_BASE_POW && a >= 0); assert(b < BC_BASE_POW && b >= 0); a += b + *carry; *carry = (a >= BC_BASE_POW); if (*carry) a -= BC_BASE_POW; assert(a >= 0); assert(a < BC_BASE_POW); return a; } /** * Performs a one-limb subtract with a carry. * @param a The first limb. * @param b The second limb. * @param carry An in/out parameter; the carry in from the previous subtract * and the carry out from this subtract. * @return The resulting limb difference. */ static BcDig bc_num_subDigits(BcDig a, BcDig b, bool* carry) { assert(a < BC_BASE_POW && a >= 0); assert(b < BC_BASE_POW && b >= 0); b += *carry; *carry = (a < b); if (*carry) a += BC_BASE_POW; assert(a - b >= 0); assert(a - b < BC_BASE_POW); return a - b; } /** * Add two BcDig arrays and store the result in the first array. * @param a The first operand and out array. * @param b The second operand. * @param len The length of @a b. */ static void bc_num_addArrays(BcDig* restrict a, const BcDig* restrict b, size_t len) { size_t i; bool carry = false; for (i = 0; i < len; ++i) { a[i] = bc_num_addDigits(a[i], b[i], &carry); } // Take care of the extra limbs in the bigger array. for (; carry; ++i) { a[i] = bc_num_addDigits(a[i], 0, &carry); } } /** * Subtract two BcDig arrays and store the result in the first array. * @param a The first operand and out array. * @param b The second operand. * @param len The length of @a b. */ static void bc_num_subArrays(BcDig* restrict a, const BcDig* restrict b, size_t len) { size_t i; bool carry = false; for (i = 0; i < len; ++i) { a[i] = bc_num_subDigits(a[i], b[i], &carry); } // Take care of the extra limbs in the bigger array. for (; carry; ++i) { a[i] = bc_num_subDigits(a[i], 0, &carry); } } /** * Multiply a BcNum array by a one-limb number. This is a faster version of * multiplication for when we can use it. * @param a The BcNum to multiply by the one-limb number. * @param b The one limb of the one-limb number. * @param c The return parameter. */ static void bc_num_mulArray(const BcNum* restrict a, BcBigDig b, BcNum* restrict c) { size_t i; BcBigDig carry = 0; assert(b <= BC_BASE_POW); // Make sure the return parameter is big enough. if (a->len + 1 > c->cap) bc_num_expand(c, a->len + 1); // We want the entire return parameter to be zero for cleaning later. // NOLINTNEXTLINE memset(c->num, 0, BC_NUM_SIZE(c->cap)); // Actual multiplication loop. for (i = 0; i < a->len; ++i) { BcBigDig in = ((BcBigDig) a->num[i]) * b + carry; c->num[i] = in % BC_BASE_POW; carry = in / BC_BASE_POW; } assert(carry < BC_BASE_POW); // Finishing touches. c->num[i] = (BcDig) carry; assert(c->num[i] >= 0 && c->num[i] < BC_BASE_POW); c->len = a->len; c->len += (carry != 0); bc_num_clean(c); // Postconditions. assert(!BC_NUM_NEG(c) || BC_NUM_NONZERO(c)); assert(BC_NUM_RDX_VAL(c) <= c->len || !c->len); assert(!c->len || c->num[c->len - 1] || BC_NUM_RDX_VAL(c) == c->len); } /** * Divide a BcNum array by a one-limb number. This is a faster version of divide * for when we can use it. * @param a The BcNum to multiply by the one-limb number. * @param b The one limb of the one-limb number. * @param c The return parameter for the quotient. * @param rem The return parameter for the remainder. */ static void bc_num_divArray(const BcNum* restrict a, BcBigDig b, BcNum* restrict c, BcBigDig* rem) { size_t i; BcBigDig carry = 0; assert(c->cap >= a->len); // Actual division loop. for (i = a->len - 1; i < a->len; --i) { BcBigDig in = ((BcBigDig) a->num[i]) + carry * BC_BASE_POW; assert(in / b < BC_BASE_POW); c->num[i] = (BcDig) (in / b); assert(c->num[i] >= 0 && c->num[i] < BC_BASE_POW); carry = in % b; } // Finishing touches. c->len = a->len; bc_num_clean(c); *rem = carry; // Postconditions. assert(!BC_NUM_NEG(c) || BC_NUM_NONZERO(c)); assert(BC_NUM_RDX_VAL(c) <= c->len || !c->len); assert(!c->len || c->num[c->len - 1] || BC_NUM_RDX_VAL(c) == c->len); } /** * Compare two BcDig arrays and return >0 if @a b is greater, <0 if @a b is * less, and 0 if equal. Both @a a and @a b must have the same length. * @param a The first array. * @param b The second array. * @param len The minimum length of the arrays. */ static ssize_t bc_num_compare(const BcDig* restrict a, const BcDig* restrict b, size_t len) { size_t i; BcDig c = 0; for (i = len - 1; i < len && !(c = a[i] - b[i]); --i) { continue; } return bc_num_neg(i + 1, c < 0); } ssize_t bc_num_cmp(const BcNum* a, const BcNum* b) { size_t i, min, a_int, b_int, diff, ardx, brdx; BcDig* max_num; BcDig* min_num; bool a_max, neg = false; ssize_t cmp; assert(a != NULL && b != NULL); // Same num? Equal. if (a == b) return 0; // Easy cases. if (BC_NUM_ZERO(a)) return bc_num_neg(b->len != 0, !BC_NUM_NEG(b)); if (BC_NUM_ZERO(b)) return bc_num_cmpZero(a); if (BC_NUM_NEG(a)) { if (BC_NUM_NEG(b)) neg = true; else return -1; } else if (BC_NUM_NEG(b)) return 1; // Get the number of int limbs in each number and get the difference. a_int = bc_num_int(a); b_int = bc_num_int(b); a_int -= b_int; // If there's a difference, then just return the comparison. if (a_int) return neg ? -((ssize_t) a_int) : (ssize_t) a_int; // Get the rdx's and figure out the max. ardx = BC_NUM_RDX_VAL(a); brdx = BC_NUM_RDX_VAL(b); a_max = (ardx > brdx); // Set variables based on the above. if (a_max) { min = brdx; diff = ardx - brdx; max_num = a->num + diff; min_num = b->num; } else { min = ardx; diff = brdx - ardx; max_num = b->num + diff; min_num = a->num; } // Do a full limb-by-limb comparison. cmp = bc_num_compare(max_num, min_num, b_int + min); // If we found a difference, return it based on state. if (cmp) return bc_num_neg((size_t) cmp, !a_max == !neg); // If there was no difference, then the final step is to check which number // has greater or lesser limbs beyond the other's. for (max_num -= diff, i = diff - 1; i < diff; --i) { if (max_num[i]) return bc_num_neg(1, !a_max == !neg); } return 0; } void bc_num_truncate(BcNum* restrict n, size_t places) { size_t nrdx, places_rdx; if (!places) return; // Grab these needed values; places_rdx is the rdx equivalent to places like // rdx is to scale. nrdx = BC_NUM_RDX_VAL(n); places_rdx = nrdx ? nrdx - BC_NUM_RDX(n->scale - places) : 0; // We cannot truncate more places than we have. assert(places <= n->scale && (BC_NUM_ZERO(n) || places_rdx <= n->len)); n->scale -= places; BC_NUM_RDX_SET(n, nrdx - places_rdx); // Only when the number is nonzero do we need to do the hard stuff. if (BC_NUM_NONZERO(n)) { size_t pow; // This calculates how many decimal digits are in the least significant // limb. pow = n->scale % BC_BASE_DIGS; pow = pow ? BC_BASE_DIGS - pow : 0; pow = bc_num_pow10[pow]; n->len -= places_rdx; // We have to move limbs to maintain invariants. The limbs must begin at // the beginning of the BcNum array. // NOLINTNEXTLINE memmove(n->num, n->num + places_rdx, BC_NUM_SIZE(n->len)); // Clear the lower part of the last digit. if (BC_NUM_NONZERO(n)) n->num[0] -= n->num[0] % (BcDig) pow; bc_num_clean(n); } } void bc_num_extend(BcNum* restrict n, size_t places) { size_t nrdx, places_rdx; if (!places) return; // Easy case with zero; set the scale. if (BC_NUM_ZERO(n)) { n->scale += places; return; } // Grab these needed values; places_rdx is the rdx equivalent to places like // rdx is to scale. nrdx = BC_NUM_RDX_VAL(n); places_rdx = BC_NUM_RDX(places + n->scale) - nrdx; // This is the hard case. We need to expand the number, move the limbs, and // set the limbs that were just cleared. if (places_rdx) { bc_num_expand(n, bc_vm_growSize(n->len, places_rdx)); // NOLINTNEXTLINE memmove(n->num + places_rdx, n->num, BC_NUM_SIZE(n->len)); // NOLINTNEXTLINE memset(n->num, 0, BC_NUM_SIZE(places_rdx)); } // Finally, set scale and rdx. BC_NUM_RDX_SET(n, nrdx + places_rdx); n->scale += places; n->len += places_rdx; assert(BC_NUM_RDX_VAL(n) == BC_NUM_RDX(n->scale)); } /** * Retires (finishes) a multiplication or division operation. */ static void bc_num_retireMul(BcNum* restrict n, size_t scale, bool neg1, bool neg2) { // Make sure scale is correct. if (n->scale < scale) bc_num_extend(n, scale - n->scale); else bc_num_truncate(n, n->scale - scale); bc_num_clean(n); // We need to ensure rdx is correct. if (BC_NUM_NONZERO(n)) n->rdx = BC_NUM_NEG_VAL(n, !neg1 != !neg2); } /** * Splits a number into two BcNum's. This is used in Karatsuba. * @param n The number to split. * @param idx The index to split at. * @param a An out parameter; the low part of @a n. * @param b An out parameter; the high part of @a n. */ static void bc_num_split(const BcNum* restrict n, size_t idx, BcNum* restrict a, BcNum* restrict b) { // We want a and b to be clear. assert(BC_NUM_ZERO(a)); assert(BC_NUM_ZERO(b)); // The usual case. if (idx < n->len) { // Set the fields first. b->len = n->len - idx; a->len = idx; a->scale = b->scale = 0; BC_NUM_RDX_SET(a, 0); BC_NUM_RDX_SET(b, 0); assert(a->cap >= a->len); assert(b->cap >= b->len); // Copy the arrays. This is not necessary for safety, but it is faster, // for some reason. // NOLINTNEXTLINE memcpy(b->num, n->num + idx, BC_NUM_SIZE(b->len)); // NOLINTNEXTLINE memcpy(a->num, n->num, BC_NUM_SIZE(idx)); bc_num_clean(b); } // If the index is weird, just skip the split. else bc_num_copy(a, n); bc_num_clean(a); } /** * Copies a number into another, but shifts the rdx so that the result number * only sees the integer part of the source number. * @param n The number to copy. * @param r The result number with a shifted rdx, len, and num. */ static void bc_num_shiftRdx(const BcNum* restrict n, BcNum* restrict r) { size_t rdx = BC_NUM_RDX_VAL(n); r->len = n->len - rdx; r->cap = n->cap - rdx; r->num = n->num + rdx; BC_NUM_RDX_SET_NEG(r, 0, BC_NUM_NEG(n)); r->scale = 0; } /** * Shifts a number so that all of the least significant limbs of the number are * skipped. This must be undone by bc_num_unshiftZero(). * @param n The number to shift. */ static size_t bc_num_shiftZero(BcNum* restrict n) { // This is volatile to quiet a GCC warning about longjmp() clobbering. volatile size_t i; // If we don't have an integer, that is a problem, but it's also a bug // because the caller should have set everything up right. assert(!BC_NUM_RDX_VAL(n) || BC_NUM_ZERO(n)); for (i = 0; i < n->len && !n->num[i]; ++i) { continue; } n->len -= i; n->num += i; return i; } /** * Undo the damage done by bc_num_unshiftZero(). This must be called like all * cleanup functions: after a label used by setjmp() and longjmp(). * @param n The number to unshift. * @param places_rdx The amount the number was originally shift. */ static void bc_num_unshiftZero(BcNum* restrict n, size_t places_rdx) { n->len += places_rdx; n->num -= places_rdx; } /** * Shifts the digits right within a number by no more than BC_BASE_DIGS - 1. * This is the final step on shifting numbers with the shift operators. It * depends on the caller to shift the limbs properly because all it does is * ensure that the rdx point is realigned to be between limbs. * @param n The number to shift digits in. * @param dig The number of places to shift right. */ static void bc_num_shift(BcNum* restrict n, BcBigDig dig) { size_t i, len = n->len; BcBigDig carry = 0, pow; BcDig* ptr = n->num; assert(dig < BC_BASE_DIGS); // Figure out the parameters for division. pow = bc_num_pow10[dig]; dig = bc_num_pow10[BC_BASE_DIGS - dig]; // Run a series of divisions and mods with carries across the entire number // array. This effectively shifts everything over. for (i = len - 1; i < len; --i) { BcBigDig in, temp; in = ((BcBigDig) ptr[i]); temp = carry * dig; carry = in % pow; ptr[i] = ((BcDig) (in / pow)) + (BcDig) temp; assert(ptr[i] >= 0 && ptr[i] < BC_BASE_POW); } assert(!carry); } /** * Shift a number left by a certain number of places. This is the workhorse of * the left shift operator. * @param n The number to shift left. * @param places The amount of places to shift @a n left by. */ static void bc_num_shiftLeft(BcNum* restrict n, size_t places) { BcBigDig dig; size_t places_rdx; bool shift; if (!places) return; // Make sure to grow the number if necessary. if (places > n->scale) { size_t size = bc_vm_growSize(BC_NUM_RDX(places - n->scale), n->len); if (size > SIZE_MAX - 1) bc_err(BC_ERR_MATH_OVERFLOW); } // If zero, we can just set the scale and bail. if (BC_NUM_ZERO(n)) { if (n->scale >= places) n->scale -= places; else n->scale = 0; return; } // When I changed bc to have multiple digits per limb, this was the hardest // code to change. This and shift right. Make sure you understand this // before attempting anything. // This is how many limbs we will shift. dig = (BcBigDig) (places % BC_BASE_DIGS); shift = (dig != 0); // Convert places to a rdx value. places_rdx = BC_NUM_RDX(places); // If the number is not an integer, we need special care. The reason an // integer doesn't is because left shift would only extend the integer, // whereas a non-integer might have its fractional part eliminated or only // partially eliminated. if (n->scale) { size_t nrdx = BC_NUM_RDX_VAL(n); // If the number's rdx is bigger, that's the hard case. if (nrdx >= places_rdx) { size_t mod = n->scale % BC_BASE_DIGS, revdig; // We want mod to be in the range [1, BC_BASE_DIGS], not // [0, BC_BASE_DIGS). mod = mod ? mod : BC_BASE_DIGS; // We need to reverse dig to get the actual number of digits. revdig = dig ? BC_BASE_DIGS - dig : 0; // If the two overflow BC_BASE_DIGS, we need to move an extra place. if (mod + revdig > BC_BASE_DIGS) places_rdx = 1; else places_rdx = 0; } else places_rdx -= nrdx; } // If this is non-zero, we need an extra place, so expand, move, and set. if (places_rdx) { bc_num_expand(n, bc_vm_growSize(n->len, places_rdx)); // NOLINTNEXTLINE memmove(n->num + places_rdx, n->num, BC_NUM_SIZE(n->len)); // NOLINTNEXTLINE memset(n->num, 0, BC_NUM_SIZE(places_rdx)); n->len += places_rdx; } // Set the scale appropriately. if (places > n->scale) { n->scale = 0; BC_NUM_RDX_SET(n, 0); } else { n->scale -= places; BC_NUM_RDX_SET(n, BC_NUM_RDX(n->scale)); } // Finally, shift within limbs. if (shift) bc_num_shift(n, BC_BASE_DIGS - dig); bc_num_clean(n); } void bc_num_shiftRight(BcNum* restrict n, size_t places) { BcBigDig dig; size_t places_rdx, scale, scale_mod, int_len, expand; bool shift; if (!places) return; // If zero, we can just set the scale and bail. if (BC_NUM_ZERO(n)) { n->scale += places; bc_num_expand(n, BC_NUM_RDX(n->scale)); return; } // Amount within a limb we have to shift by. dig = (BcBigDig) (places % BC_BASE_DIGS); shift = (dig != 0); scale = n->scale; // Figure out how the scale is affected. scale_mod = scale % BC_BASE_DIGS; scale_mod = scale_mod ? scale_mod : BC_BASE_DIGS; // We need to know the int length and rdx for places. int_len = bc_num_int(n); places_rdx = BC_NUM_RDX(places); // If we are going to shift past a limb boundary or not, set accordingly. if (scale_mod + dig > BC_BASE_DIGS) { expand = places_rdx - 1; places_rdx = 1; } else { expand = places_rdx; places_rdx = 0; } // Clamp expanding. if (expand > int_len) expand -= int_len; else expand = 0; // Extend, expand, and zero. bc_num_extend(n, places_rdx * BC_BASE_DIGS); bc_num_expand(n, bc_vm_growSize(expand, n->len)); // NOLINTNEXTLINE memset(n->num + n->len, 0, BC_NUM_SIZE(expand)); // Set the fields. n->len += expand; n->scale = 0; BC_NUM_RDX_SET(n, 0); // Finally, shift within limbs. if (shift) bc_num_shift(n, dig); n->scale = scale + places; BC_NUM_RDX_SET(n, BC_NUM_RDX(n->scale)); bc_num_clean(n); assert(BC_NUM_RDX_VAL(n) <= n->len && n->len <= n->cap); assert(BC_NUM_RDX_VAL(n) == BC_NUM_RDX(n->scale)); } /** * Tests if a number is a integer with scale or not. Returns true if the number * is not an integer. If it is, its integer shifted form is copied into the * result parameter for use where only integers are allowed. * @param n The integer to test and shift. * @param r The number to store the shifted result into. This number should * *not* be allocated. * @return True if the number is a non-integer, false otherwise. */ static bool bc_num_nonInt(const BcNum* restrict n, BcNum* restrict r) { bool zero; size_t i, rdx = BC_NUM_RDX_VAL(n); if (!rdx) { // NOLINTNEXTLINE memcpy(r, n, sizeof(BcNum)); return false; } zero = true; for (i = 0; zero && i < rdx; ++i) { zero = (n->num[i] == 0); } if (BC_ERR(!zero)) return true; bc_num_shiftRdx(n, r); return false; } #if BC_ENABLE_EXTRA_MATH /** * Execute common code for an operater that needs an integer for the second * operand and return the integer operand as a BcBigDig. * @param a The first operand. * @param b The second operand. * @param c The result operand. * @return The second operand as a hardware integer. */ static BcBigDig bc_num_intop(const BcNum* a, const BcNum* b, BcNum* restrict c) { BcNum temp; #if BC_GCC temp.len = 0; temp.rdx = 0; temp.num = NULL; #endif // BC_GCC if (BC_ERR(bc_num_nonInt(b, &temp))) bc_err(BC_ERR_MATH_NON_INTEGER); bc_num_copy(c, a); return bc_num_bigdig(&temp); } #endif // BC_ENABLE_EXTRA_MATH /** * This is the actual implementation of add *and* subtract. Since this function * doesn't need to use scale (per the bc spec), I am hijacking it to say whether * it's doing an add or a subtract. And then I convert substraction to addition * of negative second operand. This is a BcNumBinOp function. * @param a The first operand. * @param b The second operand. * @param c The return parameter. * @param sub Non-zero for a subtract, zero for an add. */ static void bc_num_as(BcNum* a, BcNum* b, BcNum* restrict c, size_t sub) { BcDig* ptr_c; BcDig* ptr_l; BcDig* ptr_r; size_t i, min_rdx, max_rdx, diff, a_int, b_int, min_len, max_len, max_int; size_t len_l, len_r, ardx, brdx; bool b_neg, do_sub, do_rev_sub, carry, c_neg; if (BC_NUM_ZERO(b)) { bc_num_copy(c, a); return; } if (BC_NUM_ZERO(a)) { bc_num_copy(c, b); c->rdx = BC_NUM_NEG_VAL(c, BC_NUM_NEG(b) != sub); return; } // Invert sign of b if it is to be subtracted. This operation must // precede the tests for any of the operands being zero. b_neg = (BC_NUM_NEG(b) != sub); // Figure out if we will actually add the numbers if their signs are equal // or subtract. do_sub = (BC_NUM_NEG(a) != b_neg); a_int = bc_num_int(a); b_int = bc_num_int(b); max_int = BC_MAX(a_int, b_int); // Figure out which number will have its last limbs copied (for addition) or // subtracted (for subtraction). ardx = BC_NUM_RDX_VAL(a); brdx = BC_NUM_RDX_VAL(b); min_rdx = BC_MIN(ardx, brdx); max_rdx = BC_MAX(ardx, brdx); diff = max_rdx - min_rdx; max_len = max_int + max_rdx; if (do_sub) { // Check whether b has to be subtracted from a or a from b. if (a_int != b_int) do_rev_sub = (a_int < b_int); else if (ardx > brdx) { do_rev_sub = (bc_num_compare(a->num + diff, b->num, b->len) < 0); } else do_rev_sub = (bc_num_compare(a->num, b->num + diff, a->len) <= 0); } else { // The result array of the addition might come out one element // longer than the bigger of the operand arrays. max_len += 1; do_rev_sub = (a_int < b_int); } assert(max_len <= c->cap); // Cache values for simple code later. if (do_rev_sub) { ptr_l = b->num; ptr_r = a->num; len_l = b->len; len_r = a->len; } else { ptr_l = a->num; ptr_r = b->num; len_l = a->len; len_r = b->len; } ptr_c = c->num; carry = false; // This is true if the numbers have a different number of limbs after the // decimal point. if (diff) { // If the rdx values of the operands do not match, the result will // have low end elements that are the positive or negative trailing // elements of the operand with higher rdx value. if ((ardx > brdx) != do_rev_sub) { // !do_rev_sub && ardx > brdx || do_rev_sub && brdx > ardx // The left operand has BcDig values that need to be copied, // either from a or from b (in case of a reversed subtraction). // NOLINTNEXTLINE memcpy(ptr_c, ptr_l, BC_NUM_SIZE(diff)); ptr_l += diff; len_l -= diff; } else { // The right operand has BcDig values that need to be copied // or subtracted from zero (in case of a subtraction). if (do_sub) { // do_sub (do_rev_sub && ardx > brdx || // !do_rev_sub && brdx > ardx) for (i = 0; i < diff; i++) { ptr_c[i] = bc_num_subDigits(0, ptr_r[i], &carry); } } else { // !do_sub && brdx > ardx // NOLINTNEXTLINE memcpy(ptr_c, ptr_r, BC_NUM_SIZE(diff)); } // Future code needs to ignore the limbs we just did. ptr_r += diff; len_r -= diff; } // The return value pointer needs to ignore what we just did. ptr_c += diff; } // This is the length that can be directly added/subtracted. min_len = BC_MIN(len_l, len_r); // After dealing with possible low array elements that depend on only one // operand above, the actual add or subtract can be performed as if the rdx // of both operands was the same. // // Inlining takes care of eliminating constant zero arguments to // addDigit/subDigit (checked in disassembly of resulting bc binary // compiled with gcc and clang). if (do_sub) { // Actual subtraction. for (i = 0; i < min_len; ++i) { ptr_c[i] = bc_num_subDigits(ptr_l[i], ptr_r[i], &carry); } // Finishing the limbs beyond the direct subtraction. for (; i < len_l; ++i) { ptr_c[i] = bc_num_subDigits(ptr_l[i], 0, &carry); } } else { // Actual addition. for (i = 0; i < min_len; ++i) { ptr_c[i] = bc_num_addDigits(ptr_l[i], ptr_r[i], &carry); } // Finishing the limbs beyond the direct addition. for (; i < len_l; ++i) { ptr_c[i] = bc_num_addDigits(ptr_l[i], 0, &carry); } // Addition can create an extra limb. We take care of that here. ptr_c[i] = bc_num_addDigits(0, 0, &carry); } assert(carry == false); // The result has the same sign as a, unless the operation was a // reverse subtraction (b - a). c_neg = BC_NUM_NEG(a) != (do_sub && do_rev_sub); BC_NUM_RDX_SET_NEG(c, max_rdx, c_neg); c->len = max_len; c->scale = BC_MAX(a->scale, b->scale); bc_num_clean(c); } /** * The simple multiplication that karatsuba dishes out to when the length of the * numbers gets low enough. This doesn't use scale because it treats the * operands as though they are integers. * @param a The first operand. * @param b The second operand. * @param c The return parameter. */ static void bc_num_m_simp(const BcNum* a, const BcNum* b, BcNum* restrict c) { size_t i, alen = a->len, blen = b->len, clen; BcDig* ptr_a = a->num; BcDig* ptr_b = b->num; BcDig* ptr_c; BcBigDig sum = 0, carry = 0; assert(sizeof(sum) >= sizeof(BcDig) * 2); assert(!BC_NUM_RDX_VAL(a) && !BC_NUM_RDX_VAL(b)); // Make sure c is big enough. clen = bc_vm_growSize(alen, blen); bc_num_expand(c, bc_vm_growSize(clen, 1)); // If we don't memset, then we might have uninitialized data use later. ptr_c = c->num; // NOLINTNEXTLINE memset(ptr_c, 0, BC_NUM_SIZE(c->cap)); // This is the actual multiplication loop. It uses the lattice form of long // multiplication (see the explanation on the web page at // https://knilt.arcc.albany.edu/What_is_Lattice_Multiplication or the // explanation at Wikipedia). for (i = 0; i < clen; ++i) { ssize_t sidx = (ssize_t) (i - blen + 1); size_t j, k; // These are the start indices. j = (size_t) BC_MAX(0, sidx); k = BC_MIN(i, blen - 1); // On every iteration of this loop, a multiplication happens, then the // sum is automatically calculated. for (; j < alen && k < blen; ++j, --k) { sum += ((BcBigDig) ptr_a[j]) * ((BcBigDig) ptr_b[k]); if (sum >= ((BcBigDig) BC_BASE_POW) * BC_BASE_POW) { carry += sum / BC_BASE_POW; sum %= BC_BASE_POW; } } // Calculate the carry. if (sum >= BC_BASE_POW) { carry += sum / BC_BASE_POW; sum %= BC_BASE_POW; } // Store and set up for next iteration. ptr_c[i] = (BcDig) sum; assert(ptr_c[i] < BC_BASE_POW); sum = carry; carry = 0; } // This should always be true because there should be no carry on the last // digit; multiplication never goes above the sum of both lengths. assert(!sum); c->len = clen; } /** * Does a shifted add or subtract for Karatsuba below. This calls either * bc_num_addArrays() or bc_num_subArrays(). * @param n An in/out parameter; the first operand and return parameter. * @param a The second operand. * @param shift The amount to shift @a n by when adding/subtracting. * @param op The function to call, either bc_num_addArrays() or * bc_num_subArrays(). */ static void bc_num_shiftAddSub(BcNum* restrict n, const BcNum* restrict a, size_t shift, BcNumShiftAddOp op) { assert(n->len >= shift + a->len); assert(!BC_NUM_RDX_VAL(n) && !BC_NUM_RDX_VAL(a)); op(n->num + shift, a->num, a->len); } /** * Implements the Karatsuba algorithm. */ static void bc_num_k(const BcNum* a, const BcNum* b, BcNum* restrict c) { size_t max, max2, total; BcNum l1, h1, l2, h2, m2, m1, z0, z1, z2, temp; BcDig* digs; BcDig* dig_ptr; BcNumShiftAddOp op; bool aone = BC_NUM_ONE(a); #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY assert(BC_NUM_ZERO(c)); if (BC_NUM_ZERO(a) || BC_NUM_ZERO(b)) return; if (aone || BC_NUM_ONE(b)) { bc_num_copy(c, aone ? b : a); if ((aone && BC_NUM_NEG(a)) || BC_NUM_NEG(b)) BC_NUM_NEG_TGL(c); return; } // Shell out to the simple algorithm with certain conditions. if (a->len < BC_NUM_KARATSUBA_LEN || b->len < BC_NUM_KARATSUBA_LEN) { bc_num_m_simp(a, b, c); return; } // We need to calculate the max size of the numbers that can result from the // operations. max = BC_MAX(a->len, b->len); max = BC_MAX(max, BC_NUM_DEF_SIZE); max2 = (max + 1) / 2; // Calculate the space needed for all of the temporary allocations. We do // this to just allocate once. total = bc_vm_arraySize(BC_NUM_KARATSUBA_ALLOCS, max); BC_SIG_LOCK; // Allocate space for all of the temporaries. digs = dig_ptr = bc_vm_malloc(BC_NUM_SIZE(total)); // Set up the temporaries. bc_num_setup(&l1, dig_ptr, max); dig_ptr += max; bc_num_setup(&h1, dig_ptr, max); dig_ptr += max; bc_num_setup(&l2, dig_ptr, max); dig_ptr += max; bc_num_setup(&h2, dig_ptr, max); dig_ptr += max; bc_num_setup(&m1, dig_ptr, max); dig_ptr += max; bc_num_setup(&m2, dig_ptr, max); // Some temporaries need the ability to grow, so we allocate them // separately. max = bc_vm_growSize(max, 1); bc_num_init(&z0, max); bc_num_init(&z1, max); bc_num_init(&z2, max); max = bc_vm_growSize(max, max) + 1; bc_num_init(&temp, max); BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; // First, set up c. bc_num_expand(c, max); c->len = max; // NOLINTNEXTLINE memset(c->num, 0, BC_NUM_SIZE(c->len)); // Split the parameters. bc_num_split(a, max2, &l1, &h1); bc_num_split(b, max2, &l2, &h2); // Do the subtraction. bc_num_sub(&h1, &l1, &m1, 0); bc_num_sub(&l2, &h2, &m2, 0); // The if statements below are there for efficiency reasons. The best way to // understand them is to understand the Karatsuba algorithm because now that // the ollocations and splits are done, the algorithm is pretty // straightforward. if (BC_NUM_NONZERO(&h1) && BC_NUM_NONZERO(&h2)) { assert(BC_NUM_RDX_VALID_NP(h1)); assert(BC_NUM_RDX_VALID_NP(h2)); bc_num_m(&h1, &h2, &z2, 0); bc_num_clean(&z2); bc_num_shiftAddSub(c, &z2, max2 * 2, bc_num_addArrays); bc_num_shiftAddSub(c, &z2, max2, bc_num_addArrays); } if (BC_NUM_NONZERO(&l1) && BC_NUM_NONZERO(&l2)) { assert(BC_NUM_RDX_VALID_NP(l1)); assert(BC_NUM_RDX_VALID_NP(l2)); bc_num_m(&l1, &l2, &z0, 0); bc_num_clean(&z0); bc_num_shiftAddSub(c, &z0, max2, bc_num_addArrays); bc_num_shiftAddSub(c, &z0, 0, bc_num_addArrays); } if (BC_NUM_NONZERO(&m1) && BC_NUM_NONZERO(&m2)) { assert(BC_NUM_RDX_VALID_NP(m1)); assert(BC_NUM_RDX_VALID_NP(m1)); bc_num_m(&m1, &m2, &z1, 0); bc_num_clean(&z1); op = (BC_NUM_NEG_NP(m1) != BC_NUM_NEG_NP(m2)) ? bc_num_subArrays : bc_num_addArrays; bc_num_shiftAddSub(c, &z1, max2, op); } err: BC_SIG_MAYLOCK; free(digs); bc_num_free(&temp); bc_num_free(&z2); bc_num_free(&z1); bc_num_free(&z0); BC_LONGJMP_CONT(vm); } /** * Does checks for Karatsuba. It also changes things to ensure that the * Karatsuba and simple multiplication can treat the numbers as integers. This * is a BcNumBinOp function. * @param a The first operand. * @param b The second operand. * @param c The return parameter. * @param scale The current scale. */ static void bc_num_m(BcNum* a, BcNum* b, BcNum* restrict c, size_t scale) { BcNum cpa, cpb; size_t ascale, bscale, ardx, brdx, zero, len, rscale; // These are meant to quiet warnings on GCC about longjmp() clobbering. // The problem is real here. size_t scale1, scale2, realscale; // These are meant to quiet the GCC longjmp() clobbering, even though it // does not apply here. volatile size_t azero; volatile size_t bzero; #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY assert(BC_NUM_RDX_VALID(a)); assert(BC_NUM_RDX_VALID(b)); bc_num_zero(c); ascale = a->scale; bscale = b->scale; // This sets the final scale according to the bc spec. scale1 = BC_MAX(scale, ascale); scale2 = BC_MAX(scale1, bscale); rscale = ascale + bscale; realscale = BC_MIN(rscale, scale2); // If this condition is true, we can use bc_num_mulArray(), which would be // much faster. if ((a->len == 1 || b->len == 1) && !a->rdx && !b->rdx) { BcNum* operand; BcBigDig dig; // Set the correct operands. if (a->len == 1) { dig = (BcBigDig) a->num[0]; operand = b; } else { dig = (BcBigDig) b->num[0]; operand = a; } bc_num_mulArray(operand, dig, c); // Need to make sure the sign is correct. if (BC_NUM_NONZERO(c)) { c->rdx = BC_NUM_NEG_VAL(c, BC_NUM_NEG(a) != BC_NUM_NEG(b)); } return; } assert(BC_NUM_RDX_VALID(a)); assert(BC_NUM_RDX_VALID(b)); BC_SIG_LOCK; // We need copies because of all of the mutation needed to make Karatsuba // think the numbers are integers. bc_num_init(&cpa, a->len + BC_NUM_RDX_VAL(a)); bc_num_init(&cpb, b->len + BC_NUM_RDX_VAL(b)); BC_SETJMP_LOCKED(vm, init_err); BC_SIG_UNLOCK; bc_num_copy(&cpa, a); bc_num_copy(&cpb, b); assert(BC_NUM_RDX_VALID_NP(cpa)); assert(BC_NUM_RDX_VALID_NP(cpb)); BC_NUM_NEG_CLR_NP(cpa); BC_NUM_NEG_CLR_NP(cpb); assert(BC_NUM_RDX_VALID_NP(cpa)); assert(BC_NUM_RDX_VALID_NP(cpb)); // These are what makes them appear like integers. ardx = BC_NUM_RDX_VAL_NP(cpa) * BC_BASE_DIGS; bc_num_shiftLeft(&cpa, ardx); brdx = BC_NUM_RDX_VAL_NP(cpb) * BC_BASE_DIGS; bc_num_shiftLeft(&cpb, brdx); // We need to reset the jump here because azero and bzero are used in the // cleanup, and local variables are not guaranteed to be the same after a // jump. BC_SIG_LOCK; BC_UNSETJMP(vm); // We want to ignore zero limbs. azero = bc_num_shiftZero(&cpa); bzero = bc_num_shiftZero(&cpb); BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; bc_num_clean(&cpa); bc_num_clean(&cpb); bc_num_k(&cpa, &cpb, c); // The return parameter needs to have its scale set. This is the start. It // also needs to be shifted by the same amount as a and b have limbs after // the decimal point. zero = bc_vm_growSize(azero, bzero); len = bc_vm_growSize(c->len, zero); bc_num_expand(c, len); // Shift c based on the limbs after the decimal point in a and b. bc_num_shiftLeft(c, (len - c->len) * BC_BASE_DIGS); bc_num_shiftRight(c, ardx + brdx); bc_num_retireMul(c, realscale, BC_NUM_NEG(a), BC_NUM_NEG(b)); err: BC_SIG_MAYLOCK; bc_num_unshiftZero(&cpb, bzero); bc_num_unshiftZero(&cpa, azero); init_err: BC_SIG_MAYLOCK; bc_num_free(&cpb); bc_num_free(&cpa); BC_LONGJMP_CONT(vm); } /** * Returns true if the BcDig array has non-zero limbs, false otherwise. * @param a The array to test. * @param len The length of the array. * @return True if @a has any non-zero limbs, false otherwise. */ static bool bc_num_nonZeroDig(BcDig* restrict a, size_t len) { size_t i; for (i = len - 1; i < len; --i) { if (a[i] != 0) return true; } return false; } /** * Compares a BcDig array against a BcNum. This is especially suited for * division. Returns >0 if @a a is greater than @a b, <0 if it is less, and =0 * if they are equal. * @param a The array. * @param b The number. * @param len The length to assume the arrays are. This is always less than the * actual length because of how this is implemented. */ static ssize_t bc_num_divCmp(const BcDig* a, const BcNum* b, size_t len) { ssize_t cmp; if (b->len > len && a[len]) cmp = bc_num_compare(a, b->num, len + 1); else if (b->len <= len) { if (a[len]) cmp = 1; else cmp = bc_num_compare(a, b->num, len); } else cmp = -1; return cmp; } /** * Extends the two operands of a division by BC_BASE_DIGS minus the number of * digits in the divisor estimate. In other words, it is shifting the numbers in * order to force the divisor estimate to fill the limb. * @param a The first operand. * @param b The second operand. * @param divisor The divisor estimate. */ static void bc_num_divExtend(BcNum* restrict a, BcNum* restrict b, BcBigDig divisor) { size_t pow; assert(divisor < BC_BASE_POW); pow = BC_BASE_DIGS - bc_num_log10((size_t) divisor); bc_num_shiftLeft(a, pow); bc_num_shiftLeft(b, pow); } /** * Actually does division. This is a rewrite of my original code by Stefan Esser * from FreeBSD. * @param a The first operand. * @param b The second operand. * @param c The return parameter. * @param scale The current scale. */ static void bc_num_d_long(BcNum* restrict a, BcNum* restrict b, BcNum* restrict c, size_t scale) { BcBigDig divisor; size_t i, rdx; // This is volatile and len 2 and reallen exist to quiet the GCC warning // about clobbering on longjmp(). This one is possible, I think. volatile size_t len; size_t len2, reallen; // This is volatile and realend exists to quiet the GCC warning about // clobbering on longjmp(). This one is possible, I think. volatile size_t end; size_t realend; BcNum cpb; // This is volatile and realnonzero exists to quiet the GCC warning about // clobbering on longjmp(). This one is possible, I think. volatile bool nonzero; bool realnonzero; #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY assert(b->len < a->len); len = b->len; end = a->len - len; assert(len >= 1); // This is a final time to make sure c is big enough and that its array is // properly zeroed. bc_num_expand(c, a->len); // NOLINTNEXTLINE memset(c->num, 0, c->cap * sizeof(BcDig)); // Setup. BC_NUM_RDX_SET(c, BC_NUM_RDX_VAL(a)); c->scale = a->scale; c->len = a->len; // This is pulling the most significant limb of b in order to establish a // good "estimate" for the actual divisor. divisor = (BcBigDig) b->num[len - 1]; // The entire bit of code in this if statement is to tighten the estimate of // the divisor. The condition asks if b has any other non-zero limbs. if (len > 1 && bc_num_nonZeroDig(b->num, len - 1)) { // This takes a little bit of understanding. The "10*BC_BASE_DIGS/6+1" // results in either 16 for 64-bit 9-digit limbs or 7 for 32-bit 4-digit // limbs. Then it shifts a 1 by that many, which in both cases, puts the // result above *half* of the max value a limb can store. Basically, // this quickly calculates if the divisor is greater than half the max // of a limb. nonzero = (divisor > 1 << ((10 * BC_BASE_DIGS) / 6 + 1)); // If the divisor is *not* greater than half the limb... if (!nonzero) { // Extend the parameters by the number of missing digits in the // divisor. bc_num_divExtend(a, b, divisor); // Check bc_num_d(). In there, we grow a again and again. We do it // again here; we *always* want to be sure it is big enough. len2 = BC_MAX(a->len, b->len); bc_num_expand(a, len2 + 1); // Make a have a zero most significant limb to match the len. if (len2 + 1 > a->len) a->len = len2 + 1; // Grab the new divisor estimate, new because the shift has made it // different. reallen = b->len; realend = a->len - reallen; divisor = (BcBigDig) b->num[reallen - 1]; realnonzero = bc_num_nonZeroDig(b->num, reallen - 1); } else { realend = end; realnonzero = nonzero; } } else { realend = end; realnonzero = false; } // If b has other nonzero limbs, we want the divisor to be one higher, so // that it is an upper bound. divisor += realnonzero; // Make sure c can fit the new length. bc_num_expand(c, a->len); // NOLINTNEXTLINE memset(c->num, 0, BC_NUM_SIZE(c->cap)); assert(c->scale >= scale); rdx = BC_NUM_RDX_VAL(c) - BC_NUM_RDX(scale); BC_SIG_LOCK; bc_num_init(&cpb, len + 1); BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; // This is the actual division loop. for (i = realend - 1; i < realend && i >= rdx && BC_NUM_NONZERO(a); --i) { ssize_t cmp; BcDig* n; BcBigDig result; n = a->num + i; assert(n >= a->num); result = 0; cmp = bc_num_divCmp(n, b, len); // This is true if n is greater than b, which means that division can // proceed, so this inner loop is the part that implements one instance // of the division. while (cmp >= 0) { BcBigDig n1, dividend, quotient; // These should be named obviously enough. Just imagine that it's a // division of one limb. Because that's what it is. n1 = (BcBigDig) n[len]; dividend = n1 * BC_BASE_POW + (BcBigDig) n[len - 1]; quotient = (dividend / divisor); // If this is true, then we can just subtract. Remember: setting // quotient to 1 is not bad because we already know that n is // greater than b. if (quotient <= 1) { quotient = 1; bc_num_subArrays(n, b->num, len); } else { assert(quotient <= BC_BASE_POW); // We need to multiply and subtract for a quotient above 1. bc_num_mulArray(b, (BcBigDig) quotient, &cpb); bc_num_subArrays(n, cpb.num, cpb.len); } // The result is the *real* quotient, by the way, but it might take // multiple trips around this loop to get it. result += quotient; assert(result <= BC_BASE_POW); // And here's why it might take multiple trips: n might *still* be // greater than b. So we have to loop again. That's what this is // setting up for: the condition of the while loop. if (realnonzero) cmp = bc_num_divCmp(n, b, len); else cmp = -1; } assert(result < BC_BASE_POW); // Store the actual limb quotient. c->num[i] = (BcDig) result; } err: BC_SIG_MAYLOCK; bc_num_free(&cpb); BC_LONGJMP_CONT(vm); } /** * Implements division. This is a BcNumBinOp function. * @param a The first operand. * @param b The second operand. * @param c The return parameter. * @param scale The current scale. */ static void bc_num_d(BcNum* a, BcNum* b, BcNum* restrict c, size_t scale) { size_t len, cpardx; BcNum cpa, cpb; #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY if (BC_NUM_ZERO(b)) bc_err(BC_ERR_MATH_DIVIDE_BY_ZERO); if (BC_NUM_ZERO(a)) { bc_num_setToZero(c, scale); return; } if (BC_NUM_ONE(b)) { bc_num_copy(c, a); bc_num_retireMul(c, scale, BC_NUM_NEG(a), BC_NUM_NEG(b)); return; } // If this is true, we can use bc_num_divArray(), which would be faster. if (!BC_NUM_RDX_VAL(a) && !BC_NUM_RDX_VAL(b) && b->len == 1 && !scale) { BcBigDig rem; bc_num_divArray(a, (BcBigDig) b->num[0], c, &rem); bc_num_retireMul(c, scale, BC_NUM_NEG(a), BC_NUM_NEG(b)); return; } len = bc_num_divReq(a, b, scale); BC_SIG_LOCK; // Initialize copies of the parameters. We want the length of the first // operand copy to be as big as the result because of the way the division // is implemented. bc_num_init(&cpa, len); bc_num_copy(&cpa, a); bc_num_createCopy(&cpb, b); BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; len = b->len; // Like the above comment, we want the copy of the first parameter to be // larger than the second parameter. if (len > cpa.len) { bc_num_expand(&cpa, bc_vm_growSize(len, 2)); bc_num_extend(&cpa, (len - cpa.len) * BC_BASE_DIGS); } cpardx = BC_NUM_RDX_VAL_NP(cpa); cpa.scale = cpardx * BC_BASE_DIGS; // This is just setting up the scale in preparation for the division. bc_num_extend(&cpa, b->scale); cpardx = BC_NUM_RDX_VAL_NP(cpa) - BC_NUM_RDX(b->scale); BC_NUM_RDX_SET_NP(cpa, cpardx); cpa.scale = cpardx * BC_BASE_DIGS; // Once again, just setting things up, this time to match scale. if (scale > cpa.scale) { bc_num_extend(&cpa, scale); cpardx = BC_NUM_RDX_VAL_NP(cpa); cpa.scale = cpardx * BC_BASE_DIGS; } // Grow if necessary. if (cpa.cap == cpa.len) bc_num_expand(&cpa, bc_vm_growSize(cpa.len, 1)); // We want an extra zero in front to make things simpler. cpa.num[cpa.len++] = 0; // Still setting things up. Why all of these things are needed is not // something that can be easily explained, but it has to do with making the // actual algorithm easier to understand because it can assume a lot of // things. Thus, you should view all of this setup code as establishing // assumptions for bc_num_d_long(), where the actual division happens. if (cpardx == cpa.len) cpa.len = bc_num_nonZeroLen(&cpa); if (BC_NUM_RDX_VAL_NP(cpb) == cpb.len) cpb.len = bc_num_nonZeroLen(&cpb); cpb.scale = 0; BC_NUM_RDX_SET_NP(cpb, 0); bc_num_d_long(&cpa, &cpb, c, scale); bc_num_retireMul(c, scale, BC_NUM_NEG(a), BC_NUM_NEG(b)); err: BC_SIG_MAYLOCK; bc_num_free(&cpb); bc_num_free(&cpa); BC_LONGJMP_CONT(vm); } /** * Implements divmod. This is the actual modulus function; since modulus * requires a division anyway, this returns the quotient and modulus. Either can * be thrown out as desired. * @param a The first operand. * @param b The second operand. * @param c The return parameter for the quotient. * @param d The return parameter for the modulus. * @param scale The current scale. * @param ts The scale that the operation should be done to. Yes, it's not * necessarily the same as scale, per the bc spec. */ static void bc_num_r(BcNum* a, BcNum* b, BcNum* restrict c, BcNum* restrict d, size_t scale, size_t ts) { BcNum temp; // realscale is meant to quiet a warning on GCC about longjmp() clobbering. // This one is real. size_t realscale; bool neg; #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY if (BC_NUM_ZERO(b)) bc_err(BC_ERR_MATH_DIVIDE_BY_ZERO); if (BC_NUM_ZERO(a)) { bc_num_setToZero(c, ts); bc_num_setToZero(d, ts); return; } BC_SIG_LOCK; bc_num_init(&temp, d->cap); BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; // Division. bc_num_d(a, b, c, scale); // We want an extra digit so we can safely truncate. if (scale) realscale = ts + 1; else realscale = scale; assert(BC_NUM_RDX_VALID(c)); assert(BC_NUM_RDX_VALID(b)); // Implement the rest of the (a - (a / b) * b) formula. bc_num_m(c, b, &temp, realscale); bc_num_sub(a, &temp, d, realscale); // Extend if necessary. if (ts > d->scale && BC_NUM_NONZERO(d)) bc_num_extend(d, ts - d->scale); neg = BC_NUM_NEG(d); bc_num_retireMul(d, ts, BC_NUM_NEG(a), BC_NUM_NEG(b)); d->rdx = BC_NUM_NEG_VAL(d, BC_NUM_NONZERO(d) ? neg : false); err: BC_SIG_MAYLOCK; bc_num_free(&temp); BC_LONGJMP_CONT(vm); } /** * Implements modulus/remainder. (Yes, I know they are different, but not in the * context of bc.) This is a BcNumBinOp function. * @param a The first operand. * @param b The second operand. * @param c The return parameter. * @param scale The current scale. */ static void bc_num_rem(BcNum* a, BcNum* b, BcNum* restrict c, size_t scale) { BcNum c1; size_t ts; #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY ts = bc_vm_growSize(scale, b->scale); ts = BC_MAX(ts, a->scale); BC_SIG_LOCK; // Need a temp for the quotient. bc_num_init(&c1, bc_num_mulReq(a, b, ts)); BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; bc_num_r(a, b, &c1, c, scale, ts); err: BC_SIG_MAYLOCK; bc_num_free(&c1); BC_LONGJMP_CONT(vm); } /** * Implements power (exponentiation). This is a BcNumBinOp function. * @param a The first operand. * @param b The second operand. * @param c The return parameter. * @param scale The current scale. */ static void bc_num_p(BcNum* a, BcNum* b, BcNum* restrict c, size_t scale) { BcNum copy, btemp; BcBigDig exp; // realscale is meant to quiet a warning on GCC about longjmp() clobbering. // This one is real. size_t powrdx, resrdx, realscale; bool neg; #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY // This is here to silence a warning from GCC. #if BC_GCC btemp.len = 0; btemp.rdx = 0; btemp.num = NULL; #endif // BC_GCC if (BC_ERR(bc_num_nonInt(b, &btemp))) bc_err(BC_ERR_MATH_NON_INTEGER); assert(btemp.len == 0 || btemp.num != NULL); if (BC_NUM_ZERO(&btemp)) { bc_num_one(c); return; } if (BC_NUM_ZERO(a)) { if (BC_NUM_NEG_NP(btemp)) bc_err(BC_ERR_MATH_DIVIDE_BY_ZERO); bc_num_setToZero(c, scale); return; } if (BC_NUM_ONE(&btemp)) { if (!BC_NUM_NEG_NP(btemp)) bc_num_copy(c, a); else bc_num_inv(a, c, scale); return; } neg = BC_NUM_NEG_NP(btemp); BC_NUM_NEG_CLR_NP(btemp); exp = bc_num_bigdig(&btemp); BC_SIG_LOCK; bc_num_createCopy(©, a); BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; // If this is true, then we do not have to do a division, and we need to // set scale accordingly. if (!neg) { size_t max = BC_MAX(scale, a->scale), scalepow; scalepow = bc_num_mulOverflow(a->scale, exp); realscale = BC_MIN(scalepow, max); } else realscale = scale; // This is only implementing the first exponentiation by squaring, until it // reaches the first time where the square is actually used. for (powrdx = a->scale; !(exp & 1); exp >>= 1) { powrdx <<= 1; assert(BC_NUM_RDX_VALID_NP(copy)); bc_num_mul(©, ©, ©, powrdx); } // Make c a copy of copy for the purpose of saving the squares that should // be saved. bc_num_copy(c, ©); resrdx = powrdx; // Now finish the exponentiation by squaring, this time saving the squares // as necessary. while (exp >>= 1) { powrdx <<= 1; assert(BC_NUM_RDX_VALID_NP(copy)); bc_num_mul(©, ©, ©, powrdx); // If this is true, we want to save that particular square. This does // that by multiplying c with copy. if (exp & 1) { resrdx += powrdx; assert(BC_NUM_RDX_VALID(c)); assert(BC_NUM_RDX_VALID_NP(copy)); bc_num_mul(c, ©, c, resrdx); } } // Invert if necessary. if (neg) bc_num_inv(c, c, realscale); // Truncate if necessary. if (c->scale > realscale) bc_num_truncate(c, c->scale - realscale); bc_num_clean(c); err: BC_SIG_MAYLOCK; bc_num_free(©); BC_LONGJMP_CONT(vm); } #if BC_ENABLE_EXTRA_MATH /** * Implements the places operator. This is a BcNumBinOp function. * @param a The first operand. * @param b The second operand. * @param c The return parameter. * @param scale The current scale. */ static void bc_num_place(BcNum* a, BcNum* b, BcNum* restrict c, size_t scale) { BcBigDig val; BC_UNUSED(scale); val = bc_num_intop(a, b, c); // Just truncate or extend as appropriate. if (val < c->scale) bc_num_truncate(c, c->scale - val); else if (val > c->scale) bc_num_extend(c, val - c->scale); } /** * Implements the left shift operator. This is a BcNumBinOp function. */ static void bc_num_left(BcNum* a, BcNum* b, BcNum* restrict c, size_t scale) { BcBigDig val; BC_UNUSED(scale); val = bc_num_intop(a, b, c); bc_num_shiftLeft(c, (size_t) val); } /** * Implements the right shift operator. This is a BcNumBinOp function. */ static void bc_num_right(BcNum* a, BcNum* b, BcNum* restrict c, size_t scale) { BcBigDig val; BC_UNUSED(scale); val = bc_num_intop(a, b, c); if (BC_NUM_ZERO(c)) return; bc_num_shiftRight(c, (size_t) val); } #endif // BC_ENABLE_EXTRA_MATH /** * Prepares for, and calls, a binary operator function. This is probably the * most important function in the entire file because it establishes assumptions * that make the rest of the code so easy. Those assumptions include: * * - a is not the same pointer as c. * - b is not the same pointer as c. * - there is enough room in c for the result. * * Without these, this whole function would basically have to be duplicated for * *all* binary operators. * * @param a The first operand. * @param b The second operand. * @param c The return parameter. * @param scale The current scale. * @param req The number of limbs needed to fit the result. */ static void bc_num_binary(BcNum* a, BcNum* b, BcNum* c, size_t scale, BcNumBinOp op, size_t req) { BcNum* ptr_a; BcNum* ptr_b; BcNum num2; #if BC_ENABLE_LIBRARY BcVm* vm = NULL; #endif // BC_ENABLE_LIBRARY assert(a != NULL && b != NULL && c != NULL && op != NULL); assert(BC_NUM_RDX_VALID(a)); assert(BC_NUM_RDX_VALID(b)); BC_SIG_LOCK; ptr_a = c == a ? &num2 : a; ptr_b = c == b ? &num2 : b; // Actually reallocate. If we don't reallocate, we want to expand at the // very least. if (c == a || c == b) { #if BC_ENABLE_LIBRARY vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY // NOLINTNEXTLINE memcpy(&num2, c, sizeof(BcNum)); bc_num_init(c, req); // Must prepare for cleanup. We want this here so that locals that got // set stay set since a longjmp() is not guaranteed to preserve locals. BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; } else { BC_SIG_UNLOCK; bc_num_expand(c, req); } // It is okay for a and b to be the same. If a binary operator function does // need them to be different, the binary operator function is responsible // for that. // Call the actual binary operator function. op(ptr_a, ptr_b, c, scale); assert(!BC_NUM_NEG(c) || BC_NUM_NONZERO(c)); assert(BC_NUM_RDX_VAL(c) <= c->len || !c->len); assert(BC_NUM_RDX_VALID(c)); assert(!c->len || c->num[c->len - 1] || BC_NUM_RDX_VAL(c) == c->len); err: // Cleanup only needed if we initialized c to a new number. if (c == a || c == b) { BC_SIG_MAYLOCK; bc_num_free(&num2); BC_LONGJMP_CONT(vm); } } /** * Tests a number string for validity. This function has a history; I originally * wrote it because I did not trust my parser. Over time, however, I came to * trust it, so I was able to relegate this function to debug builds only, and I * used it in assert()'s. But then I created the library, and well, I can't * trust users, so I reused this for yelling at users. * @param val The string to check to see if it's a valid number string. * @return True if the string is a valid number string, false otherwise. */ bool bc_num_strValid(const char* restrict val) { bool radix = false; size_t i, len = strlen(val); // Notice that I don't check if there is a negative sign. That is not part // of a valid number, except in the library. The library-specific code takes // care of that part. // Nothing in the string is okay. if (!len) return true; // Loop through the characters. for (i = 0; i < len; ++i) { BcDig c = val[i]; // If we have found a radix point... if (c == '.') { // We don't allow two radices. if (radix) return false; radix = true; continue; } // We only allow digits and uppercase letters. if (!(isdigit(c) || isupper(c))) return false; } return true; } /** * Parses one character and returns the digit that corresponds to that * character according to the base. * @param c The character to parse. * @param base The base. * @return The character as a digit. */ static BcBigDig bc_num_parseChar(char c, size_t base) { assert(isupper(c) || isdigit(c)); // If a letter... if (isupper(c)) { #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY // This returns the digit that directly corresponds with the letter. c = BC_NUM_NUM_LETTER(c); // If the digit is greater than the base, we clamp. if (BC_DIGIT_CLAMP) { c = ((size_t) c) >= base ? (char) base - 1 : c; } } // Straight convert the digit to a number. else c -= '0'; return (BcBigDig) (uchar) c; } /** * Parses a string as a decimal number. This is separate because it's going to * be the most used, and it can be heavily optimized for decimal only. * @param n The number to parse into and return. Must be preallocated. * @param val The string to parse. */ static void bc_num_parseDecimal(BcNum* restrict n, const char* restrict val) { size_t len, i, temp, mod; const char* ptr; bool zero = true, rdx; #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY // Eat leading zeroes. for (i = 0; val[i] == '0'; ++i) { continue; } val += i; assert(!val[0] || isalnum(val[0]) || val[0] == '.'); // All 0's. We can just return, since this procedure expects a virgin // (already 0) BcNum. if (!val[0]) return; // The length of the string is the length of the number, except it might be // one bigger because of a decimal point. len = strlen(val); // Find the location of the decimal point. ptr = strchr(val, '.'); rdx = (ptr != NULL); // We eat leading zeroes again. These leading zeroes are different because // they will come after the decimal point if they exist, and since that's // the case, they must be preserved. for (i = 0; i < len && (zero = (val[i] == '0' || val[i] == '.')); ++i) { continue; } // Set the scale of the number based on the location of the decimal point. // The casts to uintptr_t is to ensure that bc does not hit undefined // behavior when doing math on the values. n->scale = (size_t) (rdx * (((uintptr_t) (val + len)) - (((uintptr_t) ptr) + 1))); // Set rdx. BC_NUM_RDX_SET(n, BC_NUM_RDX(n->scale)); // Calculate length. First, the length of the integer, then the number of // digits in the last limb, then the length. i = len - (ptr == val ? 0 : i) - rdx; temp = BC_NUM_ROUND_POW(i); mod = n->scale % BC_BASE_DIGS; i = mod ? BC_BASE_DIGS - mod : 0; n->len = ((temp + i) / BC_BASE_DIGS); // Expand and zero. The plus extra is in case the lack of clamping causes // the number to overflow the original bounds. bc_num_expand(n, n->len + !BC_DIGIT_CLAMP); // NOLINTNEXTLINE memset(n->num, 0, BC_NUM_SIZE(n->len + !BC_DIGIT_CLAMP)); if (zero) { // I think I can set rdx directly to zero here because n should be a // new number with sign set to false. n->len = n->rdx = 0; } else { // There is actually stuff to parse if we make it here. Yay... BcBigDig exp, pow; assert(i <= BC_NUM_BIGDIG_MAX); // The exponent and power. exp = (BcBigDig) i; pow = bc_num_pow10[exp]; // Parse loop. We parse backwards because numbers are stored little // endian. for (i = len - 1; i < len; --i, ++exp) { char c = val[i]; // Skip the decimal point. if (c == '.') exp -= 1; else { // The index of the limb. size_t idx = exp / BC_BASE_DIGS; BcBigDig dig; if (isupper(c)) { // Clamp for the base. if (!BC_DIGIT_CLAMP) c = BC_NUM_NUM_LETTER(c); else c = 9; } else c -= '0'; // Add the digit to the limb. This takes care of overflow from // lack of clamping. dig = ((BcBigDig) n->num[idx]) + ((BcBigDig) c) * pow; if (dig >= BC_BASE_POW) { // We cannot go over BC_BASE_POW with clamping. assert(!BC_DIGIT_CLAMP); n->num[idx + 1] = (BcDig) (dig / BC_BASE_POW); n->num[idx] = (BcDig) (dig % BC_BASE_POW); assert(n->num[idx] >= 0 && n->num[idx] < BC_BASE_POW); assert(n->num[idx + 1] >= 0 && n->num[idx + 1] < BC_BASE_POW); } else { n->num[idx] = (BcDig) dig; assert(n->num[idx] >= 0 && n->num[idx] < BC_BASE_POW); } // Adjust the power and exponent. if ((exp + 1) % BC_BASE_DIGS == 0) pow = 1; else pow *= BC_BASE; } } } // Make sure to add one to the length if needed from lack of clamping. n->len += (!BC_DIGIT_CLAMP && n->num[n->len] != 0); } /** * Parse a number in any base (besides decimal). * @param n The number to parse into and return. Must be preallocated. * @param val The string to parse. * @param base The base to parse as. */ static void bc_num_parseBase(BcNum* restrict n, const char* restrict val, BcBigDig base) { BcNum temp, mult1, mult2, result1, result2; BcNum* m1; BcNum* m2; BcNum* ptr; char c = 0; bool zero = true; BcBigDig v; size_t digs, len = strlen(val); // This is volatile to quiet a warning on GCC about longjmp() clobbering. volatile size_t i; #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY // If zero, just return because the number should be virgin (already 0). for (i = 0; zero && i < len; ++i) { zero = (val[i] == '.' || val[i] == '0'); } if (zero) return; BC_SIG_LOCK; bc_num_init(&temp, BC_NUM_BIGDIG_LOG10); bc_num_init(&mult1, BC_NUM_BIGDIG_LOG10); BC_SETJMP_LOCKED(vm, int_err); BC_SIG_UNLOCK; // We split parsing into parsing the integer and parsing the fractional // part. // Parse the integer part. This is the easy part because we just multiply // the number by the base, then add the digit. for (i = 0; i < len && (c = val[i]) && c != '.'; ++i) { // Convert the character to a digit. v = bc_num_parseChar(c, base); // Multiply the number. bc_num_mulArray(n, base, &mult1); // Convert the digit to a number and add. bc_num_bigdig2num(&temp, v); bc_num_add(&mult1, &temp, n, 0); } // If this condition is true, then we are done. We still need to do cleanup // though. if (i == len && !val[i]) goto int_err; // If we get here, we *must* be at the radix point. assert(val[i] == '.'); BC_SIG_LOCK; // Unset the jump to reset in for these new initializations. BC_UNSETJMP(vm); bc_num_init(&mult2, BC_NUM_BIGDIG_LOG10); bc_num_init(&result1, BC_NUM_DEF_SIZE); bc_num_init(&result2, BC_NUM_DEF_SIZE); bc_num_one(&mult1); BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; // Pointers for easy switching. m1 = &mult1; m2 = &mult2; // Parse the fractional part. This is the hard part. for (i += 1, digs = 0; i < len && (c = val[i]); ++i, ++digs) { size_t rdx; // Convert the character to a digit. v = bc_num_parseChar(c, base); // We keep growing result2 according to the base because the more digits // after the radix, the more significant the digits close to the radix // should be. bc_num_mulArray(&result1, base, &result2); // Convert the digit to a number. bc_num_bigdig2num(&temp, v); // Add the digit into the fraction part. bc_num_add(&result2, &temp, &result1, 0); // Keep growing m1 and m2 for use after the loop. bc_num_mulArray(m1, base, m2); rdx = BC_NUM_RDX_VAL(m2); if (m2->len < rdx) m2->len = rdx; // Switch. ptr = m1; m1 = m2; m2 = ptr; } // This one cannot be a divide by 0 because mult starts out at 1, then is // multiplied by base, and base cannot be 0, so mult cannot be 0. And this // is the reason we keep growing m1 and m2; this division is what converts // the parsed fractional part from an integer to a fractional part. bc_num_div(&result1, m1, &result2, digs * 2); // Pretruncate. bc_num_truncate(&result2, digs); // The final add of the integer part to the fractional part. bc_num_add(n, &result2, n, digs); // Basic cleanup. if (BC_NUM_NONZERO(n)) { if (n->scale < digs) bc_num_extend(n, digs - n->scale); } else bc_num_zero(n); err: BC_SIG_MAYLOCK; bc_num_free(&result2); bc_num_free(&result1); bc_num_free(&mult2); int_err: BC_SIG_MAYLOCK; bc_num_free(&mult1); bc_num_free(&temp); BC_LONGJMP_CONT(vm); } /** * Prints a backslash+newline combo if the number of characters needs it. This * is really a convenience function. */ static inline void bc_num_printNewline(void) { #if !BC_ENABLE_LIBRARY if (vm->nchars >= vm->line_len - 1 && vm->line_len) { bc_vm_putchar('\\', bc_flush_none); bc_vm_putchar('\n', bc_flush_err); } #endif // !BC_ENABLE_LIBRARY } /** * Prints a character after a backslash+newline, if needed. * @param c The character to print. * @param bslash Whether to print a backslash+newline. */ static void bc_num_putchar(int c, bool bslash) { if (c != '\n' && bslash) bc_num_printNewline(); bc_vm_putchar(c, bc_flush_save); } #if !BC_ENABLE_LIBRARY /** * Prints a character for a number's digit. This is for printing for dc's P * command. This function does not need to worry about radix points. This is a * BcNumDigitOp. * @param n The "digit" to print. * @param len The "length" of the digit, or number of characters that will * need to be printed for the digit. * @param rdx True if a decimal (radix) point should be printed. * @param bslash True if a backslash+newline should be printed if the character * limit for the line is reached, false otherwise. */ static void bc_num_printChar(size_t n, size_t len, bool rdx, bool bslash) { BC_UNUSED(rdx); BC_UNUSED(len); BC_UNUSED(bslash); assert(len == 1); bc_vm_putchar((uchar) n, bc_flush_save); } #endif // !BC_ENABLE_LIBRARY /** * Prints a series of characters for large bases. This is for printing in bases * above hexadecimal. This is a BcNumDigitOp. * @param n The "digit" to print. * @param len The "length" of the digit, or number of characters that will * need to be printed for the digit. * @param rdx True if a decimal (radix) point should be printed. * @param bslash True if a backslash+newline should be printed if the character * limit for the line is reached, false otherwise. */ static void bc_num_printDigits(size_t n, size_t len, bool rdx, bool bslash) { size_t exp, pow; // If needed, print the radix; otherwise, print a space to separate digits. bc_num_putchar(rdx ? '.' : ' ', true); // Calculate the exponent and power. for (exp = 0, pow = 1; exp < len - 1; ++exp, pow *= BC_BASE) { continue; } // Print each character individually. for (exp = 0; exp < len; pow /= BC_BASE, ++exp) { // The individual subdigit. size_t dig = n / pow; // Take the subdigit away. n -= dig * pow; // Print the subdigit. bc_num_putchar(((uchar) dig) + '0', bslash || exp != len - 1); } } /** * Prints a character for a number's digit. This is for printing in bases for * hexadecimal and below because they always print only one character at a time. * This is a BcNumDigitOp. * @param n The "digit" to print. * @param len The "length" of the digit, or number of characters that will * need to be printed for the digit. * @param rdx True if a decimal (radix) point should be printed. * @param bslash True if a backslash+newline should be printed if the character * limit for the line is reached, false otherwise. */ static void bc_num_printHex(size_t n, size_t len, bool rdx, bool bslash) { BC_UNUSED(len); BC_UNUSED(bslash); assert(len == 1); if (rdx) bc_num_putchar('.', true); bc_num_putchar(bc_num_hex_digits[n], bslash); } /** * Prints a decimal number. This is specially written for optimization since * this will be used the most and because bc's numbers are already in decimal. * @param n The number to print. * @param newline Whether to print backslash+newlines on long enough lines. */ static void bc_num_printDecimal(const BcNum* restrict n, bool newline) { size_t i, j, rdx = BC_NUM_RDX_VAL(n); bool zero = true; size_t buffer[BC_BASE_DIGS]; // Print loop. for (i = n->len - 1; i < n->len; --i) { BcDig n9 = n->num[i]; size_t temp; bool irdx = (i == rdx - 1); // Calculate the number of digits in the limb. zero = (zero & !irdx); temp = n->scale % BC_BASE_DIGS; temp = i || !temp ? 0 : BC_BASE_DIGS - temp; // NOLINTNEXTLINE memset(buffer, 0, BC_BASE_DIGS * sizeof(size_t)); // Fill the buffer with individual digits. for (j = 0; n9 && j < BC_BASE_DIGS; ++j) { buffer[j] = ((size_t) n9) % BC_BASE; n9 /= BC_BASE; } // Print the digits in the buffer. for (j = BC_BASE_DIGS - 1; j < BC_BASE_DIGS && j >= temp; --j) { // Figure out whether to print the decimal point. bool print_rdx = (irdx & (j == BC_BASE_DIGS - 1)); // The zero variable helps us skip leading zero digits in the limb. zero = (zero && buffer[j] == 0); if (!zero) { // While the first three arguments should be self-explanatory, // the last needs explaining. I don't want to print a newline // when the last digit to be printed could take the place of the // backslash rather than being pushed, as a single character, to // the next line. That's what that last argument does for bc. bc_num_printHex(buffer[j], 1, print_rdx, !newline || (j > temp || i != 0)); } } } } #if BC_ENABLE_EXTRA_MATH /** * Prints a number in scientific or engineering format. When doing this, we are * always printing in decimal. * @param n The number to print. * @param eng True if we are in engineering mode. * @param newline Whether to print backslash+newlines on long enough lines. */ static void bc_num_printExponent(const BcNum* restrict n, bool eng, bool newline) { size_t places, mod, nrdx = BC_NUM_RDX_VAL(n); bool neg = (n->len <= nrdx); BcNum temp, exp; BcDig digs[BC_NUM_BIGDIG_LOG10]; #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY BC_SIG_LOCK; bc_num_createCopy(&temp, n); BC_SETJMP_LOCKED(vm, exit); BC_SIG_UNLOCK; // We need to calculate the exponents, and they change based on whether the // number is all fractional or not, obviously. if (neg) { // Figure out how many limbs after the decimal point is zero. size_t i, idx = bc_num_nonZeroLen(n) - 1; places = 1; // Figure out how much in the last limb is zero. for (i = BC_BASE_DIGS - 1; i < BC_BASE_DIGS; --i) { if (bc_num_pow10[i] > (BcBigDig) n->num[idx]) places += 1; else break; } // Calculate the combination of zero limbs and zero digits in the last // limb. places += (nrdx - (idx + 1)) * BC_BASE_DIGS; mod = places % 3; // Calculate places if we are in engineering mode. if (eng && mod != 0) places += 3 - mod; // Shift the temp to the right place. bc_num_shiftLeft(&temp, places); } else { // This is the number of digits that we are supposed to put behind the // decimal point. places = bc_num_intDigits(n) - 1; // Calculate the true number based on whether engineering mode is // activated. mod = places % 3; if (eng && mod != 0) places -= 3 - (3 - mod); // Shift the temp to the right place. bc_num_shiftRight(&temp, places); } // Print the shifted number. bc_num_printDecimal(&temp, newline); // Print the e. bc_num_putchar('e', !newline); // Need to explicitly print a zero exponent. if (!places) { bc_num_printHex(0, 1, false, !newline); goto exit; } // Need to print sign for the exponent. if (neg) bc_num_putchar('-', true); // Create a temporary for the exponent... bc_num_setup(&exp, digs, BC_NUM_BIGDIG_LOG10); bc_num_bigdig2num(&exp, (BcBigDig) places); /// ..and print it. bc_num_printDecimal(&exp, newline); exit: BC_SIG_MAYLOCK; bc_num_free(&temp); BC_LONGJMP_CONT(vm); } #endif // BC_ENABLE_EXTRA_MATH /** * Converts a number from limbs with base BC_BASE_POW to base @a pow, where * @a pow is obase^N. * @param n The number to convert. * @param rem BC_BASE_POW - @a pow. * @param pow The power of obase we will convert the number to. * @param idx The index of the number to start converting at. Doing the * conversion is O(n^2); we have to sweep through starting at the * least significant limb */ static void bc_num_printFixup(BcNum* restrict n, BcBigDig rem, BcBigDig pow, size_t idx) { size_t i, len = n->len - idx; BcBigDig acc; BcDig* a = n->num + idx; // Ignore if there's just one limb left. This is the part that requires the // extra loop after the one calling this function in bc_num_printPrepare(). if (len < 2) return; // Loop through the remaining limbs and convert. We start at the second limb // because we pull the value from the previous one as well. for (i = len - 1; i > 0; --i) { // Get the limb and add it to the previous, along with multiplying by // the remainder because that's the proper overflow. "acc" means // "accumulator," by the way. acc = ((BcBigDig) a[i]) * rem + ((BcBigDig) a[i - 1]); // Store a value in base pow in the previous limb. a[i - 1] = (BcDig) (acc % pow); // Divide by the base and accumulate the remaining value in the limb. acc /= pow; acc += (BcBigDig) a[i]; // If the accumulator is greater than the base... if (acc >= BC_BASE_POW) { // Do we need to grow? if (i == len - 1) { // Grow. len = bc_vm_growSize(len, 1); bc_num_expand(n, bc_vm_growSize(len, idx)); // Update the pointer because it may have moved. a = n->num + idx; // Zero out the last limb. a[len - 1] = 0; } // Overflow into the next limb since we are over the base. a[i + 1] += acc / BC_BASE_POW; acc %= BC_BASE_POW; } assert(acc < BC_BASE_POW); // Set the limb. a[i] = (BcDig) acc; } // We may have grown the number, so adjust the length. n->len = len + idx; } /** * Prepares a number for printing in a base that is not a divisor of * BC_BASE_POW. This basically converts the number from having limbs of base * BC_BASE_POW to limbs of pow, where pow is obase^N. * @param n The number to prepare for printing. * @param rem The remainder of BC_BASE_POW when divided by a power of the base. * @param pow The power of the base. */ static void bc_num_printPrepare(BcNum* restrict n, BcBigDig rem, BcBigDig pow) { size_t i; // Loop from the least significant limb to the most significant limb and // convert limbs in each pass. for (i = 0; i < n->len; ++i) { bc_num_printFixup(n, rem, pow, i); } // bc_num_printFixup() does not do everything it is supposed to, so we do // the last bit of cleanup here. That cleanup is to ensure that each limb // is less than pow and to expand the number to fit new limbs as necessary. for (i = 0; i < n->len; ++i) { assert(pow == ((BcBigDig) ((BcDig) pow))); // If the limb needs fixing... if (n->num[i] >= (BcDig) pow) { // Do we need to grow? if (i + 1 == n->len) { // Grow the number. n->len = bc_vm_growSize(n->len, 1); bc_num_expand(n, n->len); // Without this, we might use uninitialized data. n->num[i + 1] = 0; } assert(pow < BC_BASE_POW); // Overflow into the next limb. n->num[i + 1] += n->num[i] / ((BcDig) pow); n->num[i] %= (BcDig) pow; } } } static void bc_num_printNum(BcNum* restrict n, BcBigDig base, size_t len, BcNumDigitOp print, bool newline) { BcVec stack; BcNum intp, fracp1, fracp2, digit, flen1, flen2; BcNum* n1; BcNum* n2; BcNum* temp; BcBigDig dig = 0, acc, exp; BcBigDig* ptr; size_t i, j, nrdx, idigits; bool radix; BcDig digit_digs[BC_NUM_BIGDIG_LOG10 + 1]; #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY assert(base > 1); // Easy case. Even with scale, we just print this. if (BC_NUM_ZERO(n)) { print(0, len, false, !newline); return; } // This function uses an algorithm that Stefan Esser came // up with to print the integer part of a number. What it does is convert // intp into a number of the specified base, but it does it directly, // instead of just doing a series of divisions and printing the remainders // in reverse order. // // Let me explain in a bit more detail: // // The algorithm takes the current least significant limb (after intp has // been converted to an integer) and the next to least significant limb, and // it converts the least significant limb into one of the specified base, // putting any overflow into the next to least significant limb. It iterates // through the whole number, from least significant to most significant, // doing this conversion. At the end of that iteration, the least // significant limb is converted, but the others are not, so it iterates // again, starting at the next to least significant limb. It keeps doing // that conversion, skipping one more limb than the last time, until all // limbs have been converted. Then it prints them in reverse order. // // That is the gist of the algorithm. It leaves out several things, such as // the fact that limbs are not always converted into the specified base, but // into something close, basically a power of the specified base. In // Stefan's words, "You could consider BcDigs to be of base 10^BC_BASE_DIGS // in the normal case and obase^N for the largest value of N that satisfies // obase^N <= 10^BC_BASE_DIGS. [This means that] the result is not in base // "obase", but in base "obase^N", which happens to be printable as a number // of base "obase" without consideration for neighbouring BcDigs." This fact // is what necessitates the existence of the loop later in this function. // // The conversion happens in bc_num_printPrepare() where the outer loop // happens and bc_num_printFixup() where the inner loop, or actual // conversion, happens. In other words, bc_num_printPrepare() is where the // loop that starts at the least significant limb and goes to the most // significant limb. Then, on every iteration of its loop, it calls // bc_num_printFixup(), which has the inner loop of actually converting // the limbs it passes into limbs of base obase^N rather than base // BC_BASE_POW. nrdx = BC_NUM_RDX_VAL(n); BC_SIG_LOCK; // The stack is what allows us to reverse the digits for printing. bc_vec_init(&stack, sizeof(BcBigDig), BC_DTOR_NONE); bc_num_init(&fracp1, nrdx); // intp will be the "integer part" of the number, so copy it. bc_num_createCopy(&intp, n); BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; // Make intp an integer. bc_num_truncate(&intp, intp.scale); // Get the fractional part out. bc_num_sub(n, &intp, &fracp1, 0); // If the base is not the same as the last base used for printing, we need // to update the cached exponent and power. Yes, we cache the values of the // exponent and power. That is to prevent us from calculating them every // time because printing will probably happen multiple times on the same // base. if (base != vm->last_base) { vm->last_pow = 1; vm->last_exp = 0; // Calculate the exponent and power. while (vm->last_pow * base <= BC_BASE_POW) { vm->last_pow *= base; vm->last_exp += 1; } // Also, the remainder and base itself. vm->last_rem = BC_BASE_POW - vm->last_pow; vm->last_base = base; } exp = vm->last_exp; // If vm->last_rem is 0, then the base we are printing in is a divisor of // BC_BASE_POW, which is the easy case because it means that BC_BASE_POW is // a power of obase, and no conversion is needed. If it *is* 0, then we have // the hard case, and we have to prepare the number for the base. if (vm->last_rem != 0) { bc_num_printPrepare(&intp, vm->last_rem, vm->last_pow); } // After the conversion comes the surprisingly easy part. From here on out, // this is basically naive code that I wrote, adjusted for the larger bases. // Fill the stack of digits for the integer part. for (i = 0; i < intp.len; ++i) { // Get the limb. acc = (BcBigDig) intp.num[i]; // Turn the limb into digits of base obase. for (j = 0; j < exp && (i < intp.len - 1 || acc != 0); ++j) { // This condition is true if we are not at the last digit. if (j != exp - 1) { dig = acc % base; acc /= base; } else { dig = acc; acc = 0; } assert(dig < base); // Push the digit onto the stack. bc_vec_push(&stack, &dig); } assert(acc == 0); } // Go through the stack backwards and print each digit. for (i = 0; i < stack.len; ++i) { ptr = bc_vec_item_rev(&stack, i); assert(ptr != NULL); // While the first three arguments should be self-explanatory, the last // needs explaining. I don't want to print a newline when the last digit // to be printed could take the place of the backslash rather than being // pushed, as a single character, to the next line. That's what that // last argument does for bc. print(*ptr, len, false, !newline || (n->scale != 0 || i == stack.len - 1)); } // We are done if there is no fractional part. if (!n->scale) goto err; BC_SIG_LOCK; // Reset the jump because some locals are changing. BC_UNSETJMP(vm); bc_num_init(&fracp2, nrdx); bc_num_setup(&digit, digit_digs, sizeof(digit_digs) / sizeof(BcDig)); bc_num_init(&flen1, BC_NUM_BIGDIG_LOG10); bc_num_init(&flen2, BC_NUM_BIGDIG_LOG10); BC_SETJMP_LOCKED(vm, frac_err); BC_SIG_UNLOCK; bc_num_one(&flen1); radix = true; // Pointers for easy switching. n1 = &flen1; n2 = &flen2; fracp2.scale = n->scale; BC_NUM_RDX_SET_NP(fracp2, BC_NUM_RDX(fracp2.scale)); // As long as we have not reached the scale of the number, keep printing. while ((idigits = bc_num_intDigits(n1)) <= n->scale) { // These numbers will keep growing. bc_num_expand(&fracp2, fracp1.len + 1); bc_num_mulArray(&fracp1, base, &fracp2); nrdx = BC_NUM_RDX_VAL_NP(fracp2); // Ensure an invariant. if (fracp2.len < nrdx) fracp2.len = nrdx; // fracp is guaranteed to be non-negative and small enough. dig = bc_num_bigdig2(&fracp2); // Convert the digit to a number and subtract it from the number. bc_num_bigdig2num(&digit, dig); bc_num_sub(&fracp2, &digit, &fracp1, 0); // While the first three arguments should be self-explanatory, the last // needs explaining. I don't want to print a newline when the last digit // to be printed could take the place of the backslash rather than being // pushed, as a single character, to the next line. That's what that // last argument does for bc. print(dig, len, radix, !newline || idigits != n->scale); // Update the multipliers. bc_num_mulArray(n1, base, n2); radix = false; // Switch. temp = n1; n1 = n2; n2 = temp; } frac_err: BC_SIG_MAYLOCK; bc_num_free(&flen2); bc_num_free(&flen1); bc_num_free(&fracp2); err: BC_SIG_MAYLOCK; bc_num_free(&fracp1); bc_num_free(&intp); bc_vec_free(&stack); BC_LONGJMP_CONT(vm); } /** * Prints a number in the specified base, or rather, figures out which function * to call to print the number in the specified base and calls it. * @param n The number to print. * @param base The base to print in. * @param newline Whether to print backslash+newlines on long enough lines. */ static void bc_num_printBase(BcNum* restrict n, BcBigDig base, bool newline) { size_t width; BcNumDigitOp print; bool neg = BC_NUM_NEG(n); // Clear the sign because it makes the actual printing easier when we have // to do math. BC_NUM_NEG_CLR(n); // Bases at hexadecimal and below are printed as one character, larger bases // are printed as a series of digits separated by spaces. if (base <= BC_NUM_MAX_POSIX_IBASE) { width = 1; print = bc_num_printHex; } else { assert(base <= BC_BASE_POW); width = bc_num_log10(base - 1); print = bc_num_printDigits; } // Print. bc_num_printNum(n, base, width, print, newline); // Reset the sign. n->rdx = BC_NUM_NEG_VAL(n, neg); } #if !BC_ENABLE_LIBRARY void bc_num_stream(BcNum* restrict n) { bc_num_printNum(n, BC_NUM_STREAM_BASE, 1, bc_num_printChar, false); } #endif // !BC_ENABLE_LIBRARY void bc_num_setup(BcNum* restrict n, BcDig* restrict num, size_t cap) { assert(n != NULL); n->num = num; n->cap = cap; bc_num_zero(n); } void bc_num_init(BcNum* restrict n, size_t req) { BcDig* num; BC_SIG_ASSERT_LOCKED; assert(n != NULL); // BC_NUM_DEF_SIZE is set to be about the smallest allocation size that // malloc() returns in practice, so just use it. req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE; // If we can't use a temp, allocate. if (req != BC_NUM_DEF_SIZE) num = bc_vm_malloc(BC_NUM_SIZE(req)); else { num = bc_vm_getTemp() == NULL ? bc_vm_malloc(BC_NUM_SIZE(req)) : bc_vm_takeTemp(); } bc_num_setup(n, num, req); } void bc_num_clear(BcNum* restrict n) { n->num = NULL; n->cap = 0; } void bc_num_free(void* num) { BcNum* n = (BcNum*) num; BC_SIG_ASSERT_LOCKED; assert(n != NULL); if (n->cap == BC_NUM_DEF_SIZE) bc_vm_addTemp(n->num); else free(n->num); } void bc_num_copy(BcNum* d, const BcNum* s) { assert(d != NULL && s != NULL); if (d == s) return; bc_num_expand(d, s->len); d->len = s->len; // I can just copy directly here because the sign *and* rdx will be // properly preserved. d->rdx = s->rdx; d->scale = s->scale; // NOLINTNEXTLINE memcpy(d->num, s->num, BC_NUM_SIZE(d->len)); } void bc_num_createCopy(BcNum* d, const BcNum* s) { BC_SIG_ASSERT_LOCKED; bc_num_init(d, s->len); bc_num_copy(d, s); } void bc_num_createFromBigdig(BcNum* restrict n, BcBigDig val) { BC_SIG_ASSERT_LOCKED; bc_num_init(n, BC_NUM_BIGDIG_LOG10); bc_num_bigdig2num(n, val); } size_t bc_num_scale(const BcNum* restrict n) { return n->scale; } size_t bc_num_len(const BcNum* restrict n) { size_t len = n->len; // Always return at least 1. if (BC_NUM_ZERO(n)) return n->scale ? n->scale : 1; // If this is true, there is no integer portion of the number. if (BC_NUM_RDX_VAL(n) == len) { // We have to take into account the fact that some of the digits right // after the decimal could be zero. If that is the case, we need to // ignore them until we hit the first non-zero digit. size_t zero, scale; // The number of limbs with non-zero digits. len = bc_num_nonZeroLen(n); // Get the number of digits in the last limb. scale = n->scale % BC_BASE_DIGS; scale = scale ? scale : BC_BASE_DIGS; // Get the number of zero digits. zero = bc_num_zeroDigits(n->num + len - 1); // Calculate the true length. len = len * BC_BASE_DIGS - zero - (BC_BASE_DIGS - scale); } // Otherwise, count the number of int digits and return that plus the scale. else len = bc_num_intDigits(n) + n->scale; return len; } void bc_num_parse(BcNum* restrict n, const char* restrict val, BcBigDig base) { #if BC_DEBUG #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY #endif // BC_DEBUG assert(n != NULL && val != NULL && base); assert(base >= BC_NUM_MIN_BASE && base <= vm->maxes[BC_PROG_GLOBALS_IBASE]); assert(bc_num_strValid(val)); // A one character number is *always* parsed as though the base was the // maximum allowed ibase, per the bc spec. if (!val[1]) { BcBigDig dig = bc_num_parseChar(val[0], BC_NUM_MAX_LBASE); bc_num_bigdig2num(n, dig); } else if (base == BC_BASE) bc_num_parseDecimal(n, val); else bc_num_parseBase(n, val, base); assert(BC_NUM_RDX_VALID(n)); } void bc_num_print(BcNum* restrict n, BcBigDig base, bool newline) { assert(n != NULL); assert(BC_ENABLE_EXTRA_MATH || base >= BC_NUM_MIN_BASE); // We may need a newline, just to start. bc_num_printNewline(); if (BC_NUM_NONZERO(n)) { #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY // Print the sign. if (BC_NUM_NEG(n)) bc_num_putchar('-', true); - // Print the leading zero if necessary. - if (BC_Z && BC_NUM_RDX_VAL(n) == n->len) + // Print the leading zero if necessary. We don't print when using + // scientific or engineering modes. + if (BC_Z && BC_NUM_RDX_VAL(n) == n->len && base != 0 && base != 1) { bc_num_printHex(0, 1, false, !newline); } } // Short-circuit 0. if (BC_NUM_ZERO(n)) bc_num_printHex(0, 1, false, !newline); else if (base == BC_BASE) bc_num_printDecimal(n, newline); #if BC_ENABLE_EXTRA_MATH else if (base == 0 || base == 1) { bc_num_printExponent(n, base != 0, newline); } #endif // BC_ENABLE_EXTRA_MATH else bc_num_printBase(n, base, newline); if (newline) bc_num_putchar('\n', false); } BcBigDig bc_num_bigdig2(const BcNum* restrict n) { #if BC_DEBUG #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY #endif // BC_DEBUG // This function returns no errors because it's guaranteed to succeed if // its preconditions are met. Those preconditions include both n needs to // be non-NULL, n being non-negative, and n being less than vm->max. If all // of that is true, then we can just convert without worrying about negative // errors or overflow. BcBigDig r = 0; size_t nrdx = BC_NUM_RDX_VAL(n); assert(n != NULL); assert(!BC_NUM_NEG(n)); assert(bc_num_cmp(n, &vm->max) < 0); assert(n->len - nrdx <= 3); // There is a small speed win from unrolling the loop here, and since it // only adds 53 bytes, I decided that it was worth it. switch (n->len - nrdx) { case 3: { r = (BcBigDig) n->num[nrdx + 2]; // Fallthrough. BC_FALLTHROUGH } case 2: { r = r * BC_BASE_POW + (BcBigDig) n->num[nrdx + 1]; // Fallthrough. BC_FALLTHROUGH } case 1: { r = r * BC_BASE_POW + (BcBigDig) n->num[nrdx]; } } return r; } BcBigDig bc_num_bigdig(const BcNum* restrict n) { #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY assert(n != NULL); // This error checking is extremely important, and if you do not have a // guarantee that converting a number will always succeed in a particular // case, you *must* call this function to get these error checks. This // includes all instances of numbers inputted by the user or calculated by // the user. Otherwise, you can call the faster bc_num_bigdig2(). if (BC_ERR(BC_NUM_NEG(n))) bc_err(BC_ERR_MATH_NEGATIVE); if (BC_ERR(bc_num_cmp(n, &vm->max) >= 0)) bc_err(BC_ERR_MATH_OVERFLOW); return bc_num_bigdig2(n); } void bc_num_bigdig2num(BcNum* restrict n, BcBigDig val) { BcDig* ptr; size_t i; assert(n != NULL); bc_num_zero(n); // Already 0. if (!val) return; // Expand first. This is the only way this function can fail, and it's a // fatal error. bc_num_expand(n, BC_NUM_BIGDIG_LOG10); // The conversion is easy because numbers are laid out in little-endian // order. for (ptr = n->num, i = 0; val; ++i, val /= BC_BASE_POW) { ptr[i] = val % BC_BASE_POW; } n->len = i; } #if BC_ENABLE_EXTRA_MATH void bc_num_rng(const BcNum* restrict n, BcRNG* rng) { BcNum temp, temp2, intn, frac; BcRand state1, state2, inc1, inc2; size_t nrdx = BC_NUM_RDX_VAL(n); #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY // This function holds the secret of how I interpret a seed number for the // PRNG. Well, it's actually in the development manual // (manuals/development.md#pseudo-random-number-generator), so look there // before you try to understand this. BC_SIG_LOCK; bc_num_init(&temp, n->len); bc_num_init(&temp2, n->len); bc_num_init(&frac, nrdx); bc_num_init(&intn, bc_num_int(n)); BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; assert(BC_NUM_RDX_VALID_NP(vm->max)); // NOLINTNEXTLINE memcpy(frac.num, n->num, BC_NUM_SIZE(nrdx)); frac.len = nrdx; BC_NUM_RDX_SET_NP(frac, nrdx); frac.scale = n->scale; assert(BC_NUM_RDX_VALID_NP(frac)); assert(BC_NUM_RDX_VALID_NP(vm->max2)); // Multiply the fraction and truncate so that it's an integer. The // truncation is what clamps it, by the way. bc_num_mul(&frac, &vm->max2, &temp, 0); bc_num_truncate(&temp, temp.scale); bc_num_copy(&frac, &temp); // Get the integer. // NOLINTNEXTLINE memcpy(intn.num, n->num + nrdx, BC_NUM_SIZE(bc_num_int(n))); intn.len = bc_num_int(n); // This assert is here because it has to be true. It is also here to justify // some optimizations. assert(BC_NUM_NONZERO(&vm->max)); // If there *was* a fractional part... if (BC_NUM_NONZERO(&frac)) { // This divmod splits frac into the two state parts. bc_num_divmod(&frac, &vm->max, &temp, &temp2, 0); // frac is guaranteed to be smaller than vm->max * vm->max (pow). // This means that when dividing frac by vm->max, as above, the // quotient and remainder are both guaranteed to be less than vm->max, // which means we can use bc_num_bigdig2() here and not worry about // overflow. state1 = (BcRand) bc_num_bigdig2(&temp2); state2 = (BcRand) bc_num_bigdig2(&temp); } else state1 = state2 = 0; // If there *was* an integer part... if (BC_NUM_NONZERO(&intn)) { // This divmod splits intn into the two inc parts. bc_num_divmod(&intn, &vm->max, &temp, &temp2, 0); // Because temp2 is the mod of vm->max, from above, it is guaranteed // to be small enough to use bc_num_bigdig2(). inc1 = (BcRand) bc_num_bigdig2(&temp2); // Clamp the second inc part. if (bc_num_cmp(&temp, &vm->max) >= 0) { bc_num_copy(&temp2, &temp); bc_num_mod(&temp2, &vm->max, &temp, 0); } // The if statement above ensures that temp is less than vm->max, which // means that we can use bc_num_bigdig2() here. inc2 = (BcRand) bc_num_bigdig2(&temp); } else inc1 = inc2 = 0; bc_rand_seed(rng, state1, state2, inc1, inc2); err: BC_SIG_MAYLOCK; bc_num_free(&intn); bc_num_free(&frac); bc_num_free(&temp2); bc_num_free(&temp); BC_LONGJMP_CONT(vm); } void bc_num_createFromRNG(BcNum* restrict n, BcRNG* rng) { BcRand s1, s2, i1, i2; BcNum conv, temp1, temp2, temp3; BcDig temp1_num[BC_RAND_NUM_SIZE], temp2_num[BC_RAND_NUM_SIZE]; BcDig conv_num[BC_NUM_BIGDIG_LOG10]; #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY BC_SIG_LOCK; bc_num_init(&temp3, 2 * BC_RAND_NUM_SIZE); BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; bc_num_setup(&temp1, temp1_num, sizeof(temp1_num) / sizeof(BcDig)); bc_num_setup(&temp2, temp2_num, sizeof(temp2_num) / sizeof(BcDig)); bc_num_setup(&conv, conv_num, sizeof(conv_num) / sizeof(BcDig)); // This assert is here because it has to be true. It is also here to justify // the assumption that vm->max is not zero. assert(BC_NUM_NONZERO(&vm->max)); // Because this is true, we can just ignore math errors that would happen // otherwise. assert(BC_NUM_NONZERO(&vm->max2)); bc_rand_getRands(rng, &s1, &s2, &i1, &i2); // Put the second piece of state into a number. bc_num_bigdig2num(&conv, (BcBigDig) s2); assert(BC_NUM_RDX_VALID_NP(conv)); // Multiply by max to make room for the first piece of state. bc_num_mul(&conv, &vm->max, &temp1, 0); // Add in the first piece of state. bc_num_bigdig2num(&conv, (BcBigDig) s1); bc_num_add(&conv, &temp1, &temp2, 0); // Divide to make it an entirely fractional part. bc_num_div(&temp2, &vm->max2, &temp3, BC_RAND_STATE_BITS); // Now start on the increment parts. It's the same process without the // divide, so put the second piece of increment into a number. bc_num_bigdig2num(&conv, (BcBigDig) i2); assert(BC_NUM_RDX_VALID_NP(conv)); // Multiply by max to make room for the first piece of increment. bc_num_mul(&conv, &vm->max, &temp1, 0); // Add in the first piece of increment. bc_num_bigdig2num(&conv, (BcBigDig) i1); bc_num_add(&conv, &temp1, &temp2, 0); // Now add the two together. bc_num_add(&temp2, &temp3, n, 0); assert(BC_NUM_RDX_VALID(n)); err: BC_SIG_MAYLOCK; bc_num_free(&temp3); BC_LONGJMP_CONT(vm); } void bc_num_irand(BcNum* restrict a, BcNum* restrict b, BcRNG* restrict rng) { BcNum atemp; - size_t i, len; + size_t i; assert(a != b); if (BC_ERR(BC_NUM_NEG(a))) bc_err(BC_ERR_MATH_NEGATIVE); // If either of these are true, then the numbers are integers. if (BC_NUM_ZERO(a) || BC_NUM_ONE(a)) return; #if BC_GCC // This is here in GCC to quiet the "maybe-uninitialized" warning. atemp.num = NULL; atemp.len = 0; #endif // BC_GCC if (BC_ERR(bc_num_nonInt(a, &atemp))) bc_err(BC_ERR_MATH_NON_INTEGER); assert(atemp.num != NULL); assert(atemp.len); - len = atemp.len - 1; + if (atemp.len > 2) + { + size_t len; + + len = atemp.len - 2; - // Just generate a random number for each limb. - for (i = 0; i < len; ++i) + // Just generate a random number for each limb. + for (i = 0; i < len; i += 2) + { + BcRand dig; + + dig = bc_rand_bounded(rng, BC_BASE_RAND_POW); + + b->num[i] = (BcDig) (dig % BC_BASE_POW); + b->num[i + 1] = (BcDig) (dig / BC_BASE_POW); + } + } + else { - b->num[i] = (BcDig) bc_rand_bounded(rng, BC_BASE_POW); + // We need this set. + i = 0; } - // Do the last digit explicitly because the bound must be right. But only - // do it if the limb does not equal 1. If it does, we have already hit the - // limit. - if (atemp.num[i] != 1) + // This will be true if there's one full limb after the two limb groups. + if (i == atemp.len - 2) { - b->num[i] = (BcDig) bc_rand_bounded(rng, (BcRand) atemp.num[i]); - b->len = atemp.len; + // Increment this for easy use. + i += 1; + + // If the last digit is not one, we need to set a bound for it + // explicitly. Since there's still an empty limb, we need to fill that. + if (atemp.num[i] != 1) + { + BcRand dig; + BcRand bound; + + // Set the bound to the bound of the last limb times the amount + // needed to fill the second-to-last limb as well. + bound = ((BcRand) atemp.num[i]) * BC_BASE_POW; + + dig = bc_rand_bounded(rng, bound); + + // Fill the last two. + b->num[i - 1] = (BcDig) (dig % BC_BASE_POW); + b->num[i] = (BcDig) (dig / BC_BASE_POW); + + // Ensure that the length will be correct. If the last limb is zero, + // then the length needs to be one less than the bound. + b->len = atemp.len - (b->num[i] == 0); + } + // Here the last limb *is* one, which means the last limb does *not* + // need to be filled. Also, the length needs to be one less because the + // last limb is 0. + else + { + b->num[i - 1] = (BcDig) bc_rand_bounded(rng, BC_BASE_POW); + b->len = atemp.len - 1; + } + } + // Here, there is only one limb to fill. + else + { + // See above for how this works. + if (atemp.num[i] != 1) + { + b->num[i] = (BcDig) bc_rand_bounded(rng, (BcRand) atemp.num[i]); + b->len = atemp.len - (b->num[i] == 0); + } + else b->len = atemp.len - 1; } - // We want 1 less len in the case where we skip the last limb. - else b->len = len; bc_num_clean(b); assert(BC_NUM_RDX_VALID(b)); } #endif // BC_ENABLE_EXTRA_MATH size_t bc_num_addReq(const BcNum* a, const BcNum* b, size_t scale) { size_t aint, bint, ardx, brdx; // Addition and subtraction require the max of the length of the two numbers // plus 1. BC_UNUSED(scale); ardx = BC_NUM_RDX_VAL(a); aint = bc_num_int(a); assert(aint <= a->len && ardx <= a->len); brdx = BC_NUM_RDX_VAL(b); bint = bc_num_int(b); assert(bint <= b->len && brdx <= b->len); ardx = BC_MAX(ardx, brdx); aint = BC_MAX(aint, bint); return bc_vm_growSize(bc_vm_growSize(ardx, aint), 1); } size_t bc_num_mulReq(const BcNum* a, const BcNum* b, size_t scale) { size_t max, rdx; // Multiplication requires the sum of the lengths of the numbers. rdx = bc_vm_growSize(BC_NUM_RDX_VAL(a), BC_NUM_RDX_VAL(b)); max = BC_NUM_RDX(scale); max = bc_vm_growSize(BC_MAX(max, rdx), 1); rdx = bc_vm_growSize(bc_vm_growSize(bc_num_int(a), bc_num_int(b)), max); return rdx; } size_t bc_num_divReq(const BcNum* a, const BcNum* b, size_t scale) { size_t max, rdx; // Division requires the length of the dividend plus the scale. rdx = bc_vm_growSize(BC_NUM_RDX_VAL(a), BC_NUM_RDX_VAL(b)); max = BC_NUM_RDX(scale); max = bc_vm_growSize(BC_MAX(max, rdx), 1); rdx = bc_vm_growSize(bc_num_int(a), max); return rdx; } size_t bc_num_powReq(const BcNum* a, const BcNum* b, size_t scale) { BC_UNUSED(scale); return bc_vm_growSize(bc_vm_growSize(a->len, b->len), 1); } #if BC_ENABLE_EXTRA_MATH size_t bc_num_placesReq(const BcNum* a, const BcNum* b, size_t scale) { BC_UNUSED(scale); return a->len + b->len - BC_NUM_RDX_VAL(a) - BC_NUM_RDX_VAL(b); } #endif // BC_ENABLE_EXTRA_MATH void bc_num_add(BcNum* a, BcNum* b, BcNum* c, size_t scale) { assert(BC_NUM_RDX_VALID(a)); assert(BC_NUM_RDX_VALID(b)); bc_num_binary(a, b, c, false, bc_num_as, bc_num_addReq(a, b, scale)); } void bc_num_sub(BcNum* a, BcNum* b, BcNum* c, size_t scale) { assert(BC_NUM_RDX_VALID(a)); assert(BC_NUM_RDX_VALID(b)); bc_num_binary(a, b, c, true, bc_num_as, bc_num_addReq(a, b, scale)); } void bc_num_mul(BcNum* a, BcNum* b, BcNum* c, size_t scale) { assert(BC_NUM_RDX_VALID(a)); assert(BC_NUM_RDX_VALID(b)); bc_num_binary(a, b, c, scale, bc_num_m, bc_num_mulReq(a, b, scale)); } void bc_num_div(BcNum* a, BcNum* b, BcNum* c, size_t scale) { assert(BC_NUM_RDX_VALID(a)); assert(BC_NUM_RDX_VALID(b)); bc_num_binary(a, b, c, scale, bc_num_d, bc_num_divReq(a, b, scale)); } void bc_num_mod(BcNum* a, BcNum* b, BcNum* c, size_t scale) { assert(BC_NUM_RDX_VALID(a)); assert(BC_NUM_RDX_VALID(b)); bc_num_binary(a, b, c, scale, bc_num_rem, bc_num_divReq(a, b, scale)); } void bc_num_pow(BcNum* a, BcNum* b, BcNum* c, size_t scale) { assert(BC_NUM_RDX_VALID(a)); assert(BC_NUM_RDX_VALID(b)); bc_num_binary(a, b, c, scale, bc_num_p, bc_num_powReq(a, b, scale)); } #if BC_ENABLE_EXTRA_MATH void bc_num_places(BcNum* a, BcNum* b, BcNum* c, size_t scale) { assert(BC_NUM_RDX_VALID(a)); assert(BC_NUM_RDX_VALID(b)); bc_num_binary(a, b, c, scale, bc_num_place, bc_num_placesReq(a, b, scale)); } void bc_num_lshift(BcNum* a, BcNum* b, BcNum* c, size_t scale) { assert(BC_NUM_RDX_VALID(a)); assert(BC_NUM_RDX_VALID(b)); bc_num_binary(a, b, c, scale, bc_num_left, bc_num_placesReq(a, b, scale)); } void bc_num_rshift(BcNum* a, BcNum* b, BcNum* c, size_t scale) { assert(BC_NUM_RDX_VALID(a)); assert(BC_NUM_RDX_VALID(b)); bc_num_binary(a, b, c, scale, bc_num_right, bc_num_placesReq(a, b, scale)); } #endif // BC_ENABLE_EXTRA_MATH void bc_num_sqrt(BcNum* restrict a, BcNum* restrict b, size_t scale) { BcNum num1, num2, half, f, fprime; BcNum* x0; BcNum* x1; BcNum* temp; // realscale is meant to quiet a warning on GCC about longjmp() clobbering. // This one is real. size_t pow, len, rdx, req, resscale, realscale; BcDig half_digs[1]; #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY assert(a != NULL && b != NULL && a != b); if (BC_ERR(BC_NUM_NEG(a))) bc_err(BC_ERR_MATH_NEGATIVE); // We want to calculate to a's scale if it is bigger so that the result will // truncate properly. if (a->scale > scale) realscale = a->scale; else realscale = scale; // Set parameters for the result. len = bc_vm_growSize(bc_num_intDigits(a), 1); rdx = BC_NUM_RDX(realscale); // Square root needs half of the length of the parameter. req = bc_vm_growSize(BC_MAX(rdx, BC_NUM_RDX_VAL(a)), len >> 1); BC_SIG_LOCK; // Unlike the binary operators, this function is the only single parameter // function and is expected to initialize the result. This means that it // expects that b is *NOT* preallocated. We allocate it here. bc_num_init(b, bc_vm_growSize(req, 1)); BC_SIG_UNLOCK; assert(a != NULL && b != NULL && a != b); assert(a->num != NULL && b->num != NULL); // Easy case. if (BC_NUM_ZERO(a)) { bc_num_setToZero(b, realscale); return; } // Another easy case. if (BC_NUM_ONE(a)) { bc_num_one(b); bc_num_extend(b, realscale); return; } // Set the parameters again. rdx = BC_NUM_RDX(realscale); rdx = BC_MAX(rdx, BC_NUM_RDX_VAL(a)); len = bc_vm_growSize(a->len, rdx); BC_SIG_LOCK; bc_num_init(&num1, len); bc_num_init(&num2, len); bc_num_setup(&half, half_digs, sizeof(half_digs) / sizeof(BcDig)); // There is a division by two in the formula. We setup a number that's 1/2 // so that we can use multiplication instead of heavy division. bc_num_one(&half); half.num[0] = BC_BASE_POW / 2; half.len = 1; BC_NUM_RDX_SET_NP(half, 1); half.scale = 1; bc_num_init(&f, len); bc_num_init(&fprime, len); BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; // Pointers for easy switching. x0 = &num1; x1 = &num2; // Start with 1. bc_num_one(x0); // The power of the operand is needed for the estimate. pow = bc_num_intDigits(a); // The code in this if statement calculates the initial estimate. First, if // a is less than 0, then 0 is a good estimate. Otherwise, we want something // in the same ballpark. That ballpark is pow. if (pow) { // An odd number is served by starting with 2^((pow-1)/2), and an even // number is served by starting with 6^((pow-2)/2). Why? Because math. if (pow & 1) x0->num[0] = 2; else x0->num[0] = 6; pow -= 2 - (pow & 1); bc_num_shiftLeft(x0, pow / 2); } // I can set the rdx here directly because neg should be false. x0->scale = x0->rdx = 0; resscale = (realscale + BC_BASE_DIGS) + 2; // This is the calculation loop. This compare goes to 0 eventually as the // difference between the two numbers gets smaller than resscale. while (bc_num_cmp(x1, x0)) { assert(BC_NUM_NONZERO(x0)); // This loop directly corresponds to the iteration in Newton's method. // If you know the formula, this loop makes sense. Go study the formula. bc_num_div(a, x0, &f, resscale); bc_num_add(x0, &f, &fprime, resscale); assert(BC_NUM_RDX_VALID_NP(fprime)); assert(BC_NUM_RDX_VALID_NP(half)); bc_num_mul(&fprime, &half, x1, resscale); // Switch. temp = x0; x0 = x1; x1 = temp; } // Copy to the result and truncate. bc_num_copy(b, x0); if (b->scale > realscale) bc_num_truncate(b, b->scale - realscale); assert(!BC_NUM_NEG(b) || BC_NUM_NONZERO(b)); assert(BC_NUM_RDX_VALID(b)); assert(BC_NUM_RDX_VAL(b) <= b->len || !b->len); assert(!b->len || b->num[b->len - 1] || BC_NUM_RDX_VAL(b) == b->len); err: BC_SIG_MAYLOCK; bc_num_free(&fprime); bc_num_free(&f); bc_num_free(&num2); bc_num_free(&num1); BC_LONGJMP_CONT(vm); } void bc_num_divmod(BcNum* a, BcNum* b, BcNum* c, BcNum* d, size_t scale) { size_t ts, len; BcNum *ptr_a, num2; // This is volatile to quiet a warning on GCC about clobbering with // longjmp(). volatile bool init = false; #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY // The bulk of this function is just doing what bc_num_binary() does for the // binary operators. However, it assumes that only c and a can be equal. // Set up the parameters. ts = BC_MAX(scale + b->scale, a->scale); len = bc_num_mulReq(a, b, ts); assert(a != NULL && b != NULL && c != NULL && d != NULL); assert(c != d && a != d && b != d && b != c); // Initialize or expand as necessary. if (c == a) { // NOLINTNEXTLINE memcpy(&num2, c, sizeof(BcNum)); ptr_a = &num2; BC_SIG_LOCK; bc_num_init(c, len); init = true; BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; } else { ptr_a = a; bc_num_expand(c, len); } // Do the quick version if possible. if (BC_NUM_NONZERO(a) && !BC_NUM_RDX_VAL(a) && !BC_NUM_RDX_VAL(b) && b->len == 1 && !scale) { BcBigDig rem; bc_num_divArray(ptr_a, (BcBigDig) b->num[0], c, &rem); assert(rem < BC_BASE_POW); d->num[0] = (BcDig) rem; d->len = (rem != 0); } // Do the slow method. else bc_num_r(ptr_a, b, c, d, scale, ts); assert(!BC_NUM_NEG(c) || BC_NUM_NONZERO(c)); assert(BC_NUM_RDX_VALID(c)); assert(BC_NUM_RDX_VAL(c) <= c->len || !c->len); assert(!c->len || c->num[c->len - 1] || BC_NUM_RDX_VAL(c) == c->len); assert(!BC_NUM_NEG(d) || BC_NUM_NONZERO(d)); assert(BC_NUM_RDX_VALID(d)); assert(BC_NUM_RDX_VAL(d) <= d->len || !d->len); assert(!d->len || d->num[d->len - 1] || BC_NUM_RDX_VAL(d) == d->len); err: // Only cleanup if we initialized. if (init) { BC_SIG_MAYLOCK; bc_num_free(&num2); BC_LONGJMP_CONT(vm); } } void bc_num_modexp(BcNum* a, BcNum* b, BcNum* c, BcNum* restrict d) { BcNum base, exp, two, temp, atemp, btemp, ctemp; BcDig two_digs[2]; #if BC_ENABLE_LIBRARY BcVm* vm = bcl_getspecific(); #endif // BC_ENABLE_LIBRARY assert(a != NULL && b != NULL && c != NULL && d != NULL); assert(a != d && b != d && c != d); if (BC_ERR(BC_NUM_ZERO(c))) bc_err(BC_ERR_MATH_DIVIDE_BY_ZERO); if (BC_ERR(BC_NUM_NEG(b))) bc_err(BC_ERR_MATH_NEGATIVE); #if BC_DEBUG || BC_GCC // This is entirely for quieting a useless scan-build error. btemp.len = 0; ctemp.len = 0; #endif // BC_DEBUG || BC_GCC // Eliminate fractional parts that are zero or error if they are not zero. if (BC_ERR(bc_num_nonInt(a, &atemp) || bc_num_nonInt(b, &btemp) || bc_num_nonInt(c, &ctemp))) { bc_err(BC_ERR_MATH_NON_INTEGER); } bc_num_expand(d, ctemp.len); BC_SIG_LOCK; bc_num_init(&base, ctemp.len); bc_num_setup(&two, two_digs, sizeof(two_digs) / sizeof(BcDig)); bc_num_init(&temp, btemp.len + 1); bc_num_createCopy(&exp, &btemp); BC_SETJMP_LOCKED(vm, err); BC_SIG_UNLOCK; bc_num_one(&two); two.num[0] = 2; bc_num_one(d); // We already checked for 0. bc_num_rem(&atemp, &ctemp, &base, 0); // If you know the algorithm I used, the memory-efficient method, then this // loop should be self-explanatory because it is the calculation loop. while (BC_NUM_NONZERO(&exp)) { // Num two cannot be 0, so no errors. bc_num_divmod(&exp, &two, &exp, &temp, 0); if (BC_NUM_ONE(&temp) && !BC_NUM_NEG_NP(temp)) { assert(BC_NUM_RDX_VALID(d)); assert(BC_NUM_RDX_VALID_NP(base)); bc_num_mul(d, &base, &temp, 0); // We already checked for 0. bc_num_rem(&temp, &ctemp, d, 0); } assert(BC_NUM_RDX_VALID_NP(base)); bc_num_mul(&base, &base, &temp, 0); // We already checked for 0. bc_num_rem(&temp, &ctemp, &base, 0); } err: BC_SIG_MAYLOCK; bc_num_free(&exp); bc_num_free(&temp); bc_num_free(&base); BC_LONGJMP_CONT(vm); assert(!BC_NUM_NEG(d) || d->len); assert(BC_NUM_RDX_VALID(d)); assert(!d->len || d->num[d->len - 1] || BC_NUM_RDX_VAL(d) == d->len); } #if BC_DEBUG_CODE void bc_num_printDebug(const BcNum* n, const char* name, bool emptyline) { bc_file_puts(&vm->fout, bc_flush_none, name); bc_file_puts(&vm->fout, bc_flush_none, ": "); bc_num_printDecimal(n, true); bc_file_putchar(&vm->fout, bc_flush_err, '\n'); if (emptyline) bc_file_putchar(&vm->fout, bc_flush_err, '\n'); vm->nchars = 0; } void bc_num_printDigs(const BcDig* n, size_t len, bool emptyline) { size_t i; for (i = len - 1; i < len; --i) { bc_file_printf(&vm->fout, " %lu", (unsigned long) n[i]); } bc_file_putchar(&vm->fout, bc_flush_err, '\n'); if (emptyline) bc_file_putchar(&vm->fout, bc_flush_err, '\n'); vm->nchars = 0; } void bc_num_printWithDigs(const BcNum* n, const char* name, bool emptyline) { bc_file_puts(&vm->fout, bc_flush_none, name); bc_file_printf(&vm->fout, " len: %zu, rdx: %zu, scale: %zu\n", name, n->len, BC_NUM_RDX_VAL(n), n->scale); bc_num_printDigs(n->num, n->len, emptyline); } void bc_num_dump(const char* varname, const BcNum* n) { ulong i, scale = n->scale; bc_file_printf(&vm->ferr, "\n%s = %s", varname, n->len ? (BC_NUM_NEG(n) ? "-" : "+") : "0 "); for (i = n->len - 1; i < n->len; --i) { if (i + 1 == BC_NUM_RDX_VAL(n)) { bc_file_puts(&vm->ferr, bc_flush_none, ". "); } if (scale / BC_BASE_DIGS != BC_NUM_RDX_VAL(n) - i - 1) { bc_file_printf(&vm->ferr, "%lu ", (unsigned long) n->num[i]); } else { int mod = scale % BC_BASE_DIGS; int d = BC_BASE_DIGS - mod; BcDig div; if (mod != 0) { div = n->num[i] / ((BcDig) bc_num_pow10[(ulong) d]); bc_file_printf(&vm->ferr, "%lu", (unsigned long) div); } div = n->num[i] % ((BcDig) bc_num_pow10[(ulong) d]); bc_file_printf(&vm->ferr, " ' %lu ", (unsigned long) div); } } bc_file_printf(&vm->ferr, "(%zu | %zu.%zu / %zu) %lu\n", n->scale, n->len, BC_NUM_RDX_VAL(n), n->cap, (unsigned long) (void*) n->num); bc_file_flush(&vm->ferr, bc_flush_err); } #endif // BC_DEBUG_CODE diff --git a/contrib/bc/src/program.c b/contrib/bc/src/program.c index 243f827fe98c..2f26589166e3 100644 --- a/contrib/bc/src/program.c +++ b/contrib/bc/src/program.c @@ -1,3835 +1,3844 @@ /* * ***************************************************************************** * * 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); } 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 (inst == BC_INST_LINE_LENGTH) + { + val = (BcBigDig) vm->line_len; + } #if BC_ENABLED - else if (inst == BC_INST_GLOBAL_STACKS) val = (BC_G != 0); + 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); + 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/rand.c b/contrib/bc/src/rand.c index 11c22cd507c3..560e494214ad 100644 --- a/contrib/bc/src/rand.c +++ b/contrib/bc/src/rand.c @@ -1,638 +1,641 @@ /* * ***************************************************************************** * * Parts of this code are adapted from the following: * * PCG, A Family of Better Random Number Generators. * * You can find the original source code at: * https://github.com/imneme/pcg-c * * ----------------------------------------------------------------------------- * * This code is under the following license: * * Copyright (c) 2014-2017 Melissa O'Neill and PCG Project contributors * Copyright (c) 2018-2023 Gavin D. Howard and contributors. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * ***************************************************************************** * * Code for the RNG. * */ #include #include #include #include #include #ifndef _WIN32 #include #else // _WIN32 #include #include #endif // _WIN32 #include #include #include #if BC_ENABLE_EXTRA_MATH #if !BC_RAND_BUILTIN /** * Adds two 64-bit values and preserves the overflow. * @param a The first operand. * @param b The second operand. * @return The sum, including overflow. */ static BcRandState bc_rand_addition(uint_fast64_t a, uint_fast64_t b) { BcRandState res; res.lo = a + b; res.hi = (res.lo < a); return res; } /** * Adds two 128-bit values and discards the overflow. * @param a The first operand. * @param b The second operand. * @return The sum, without overflow. */ static BcRandState bc_rand_addition2(BcRandState a, BcRandState b) { BcRandState temp, res; res = bc_rand_addition(a.lo, b.lo); temp = bc_rand_addition(a.hi, b.hi); res.hi += temp.lo; return res; } /** * Multiplies two 64-bit values and preserves the overflow. * @param a The first operand. * @param b The second operand. * @return The product, including overflow. */ static BcRandState bc_rand_multiply(uint_fast64_t a, uint_fast64_t b) { uint_fast64_t al, ah, bl, bh, c0, c1, c2, c3; BcRandState carry, res; al = BC_RAND_TRUNC32(a); ah = BC_RAND_CHOP32(a); bl = BC_RAND_TRUNC32(b); bh = BC_RAND_CHOP32(b); c0 = al * bl; c1 = al * bh; c2 = ah * bl; c3 = ah * bh; carry = bc_rand_addition(c1, c2); res = bc_rand_addition(c0, (BC_RAND_TRUNC32(carry.lo)) << 32); res.hi += BC_RAND_CHOP32(carry.lo) + c3 + (carry.hi << 32); return res; } /** * Multiplies two 128-bit values and discards the overflow. * @param a The first operand. * @param b The second operand. * @return The product, without overflow. */ static BcRandState bc_rand_multiply2(BcRandState a, BcRandState b) { BcRandState c0, c1, c2, carry; c0 = bc_rand_multiply(a.lo, b.lo); c1 = bc_rand_multiply(a.lo, b.hi); c2 = bc_rand_multiply(a.hi, b.lo); carry = bc_rand_addition2(c1, c2); carry.hi = carry.lo; carry.lo = 0; return bc_rand_addition2(c0, carry); } #endif // BC_RAND_BUILTIN /** * Marks a PRNG as modified. This is important for properly maintaining the * stack of PRNG's. * @param r The PRNG to mark as modified. */ static void bc_rand_setModified(BcRNGData* r) { #if BC_RAND_BUILTIN r->inc |= (BcRandState) 1UL; #else // BC_RAND_BUILTIN r->inc.lo |= (uint_fast64_t) 1UL; #endif // BC_RAND_BUILTIN } /** * Marks a PRNG as not modified. This is important for properly maintaining the * stack of PRNG's. * @param r The PRNG to mark as not modified. */ static void bc_rand_clearModified(BcRNGData* r) { #if BC_RAND_BUILTIN r->inc &= ~((BcRandState) 1UL); #else // BC_RAND_BUILTIN r->inc.lo &= ~(1UL); #endif // BC_RAND_BUILTIN } /** * Copies a PRNG to another and marks the copy as modified if it already was or * marks it modified if it already was. * @param d The destination PRNG. * @param s The source PRNG. */ static void bc_rand_copy(BcRNGData* d, BcRNGData* s) { bool unmod = BC_RAND_NOTMODIFIED(d); // NOLINTNEXTLINE memcpy(d, s, sizeof(BcRNGData)); if (!unmod) bc_rand_setModified(d); else if (!BC_RAND_NOTMODIFIED(s)) bc_rand_clearModified(d); } #ifndef _WIN32 /** * Reads random data from a file. * @param ptr A pointer to the file, as a void pointer. * @return The random data as an unsigned long. */ static ulong bc_rand_frand(void* ptr) { ulong buf[1]; int fd; ssize_t nread; assert(ptr != NULL); fd = *((int*) ptr); nread = read(fd, buf, sizeof(ulong)); if (BC_ERR(nread != sizeof(ulong))) bc_vm_fatalError(BC_ERR_FATAL_IO_ERR); return *((ulong*) buf); } #else // _WIN32 /** * Reads random data from BCryptGenRandom(). * @param ptr An unused parameter. * @return The random data as an unsigned long. */ static ulong bc_rand_winrand(void* ptr) { ulong buf[1]; NTSTATUS s; BC_UNUSED(ptr); buf[0] = 0; s = BCryptGenRandom(NULL, (char*) buf, sizeof(ulong), BCRYPT_USE_SYSTEM_PREFERRED_RNG); if (BC_ERR(!BCRYPT_SUCCESS(s))) buf[0] = 0; return buf[0]; } #endif // _WIN32 /** * Reads random data from rand(), byte-by-byte because rand() is only guaranteed * to return 15 bits of random data. This is the final fallback and is not * preferred as it is possible to access cryptographically-secure PRNG's on most * systems. * @param ptr An unused parameter. * @return The random data as an unsigned long. */ static ulong bc_rand_rand(void* ptr) { size_t i; ulong res = 0; BC_UNUSED(ptr); // Fill up the unsigned long byte-by-byte. for (i = 0; i < sizeof(ulong); ++i) { res |= ((ulong) (rand() & BC_RAND_SRAND_BITS)) << (i * CHAR_BIT); } return res; } /** * Returns the actual increment of the PRNG, including the required last odd * bit. * @param r The PRNG. * @return The increment of the PRNG, including the last odd bit. */ static BcRandState bc_rand_inc(BcRNGData* r) { BcRandState inc; #if BC_RAND_BUILTIN inc = r->inc | 1; #else // BC_RAND_BUILTIN inc.lo = r->inc.lo | 1; inc.hi = r->inc.hi; #endif // BC_RAND_BUILTIN return inc; } /** * Sets up the increment for the PRNG. * @param r The PRNG whose increment will be set up. */ static void bc_rand_setupInc(BcRNGData* r) { #if BC_RAND_BUILTIN r->inc <<= 1UL; #else // BC_RAND_BUILTIN r->inc.hi <<= 1UL; r->inc.hi |= (r->inc.lo & (1UL << (BC_LONG_BIT - 1))) >> (BC_LONG_BIT - 1); r->inc.lo <<= 1UL; #endif // BC_RAND_BUILTIN } /** * Seeds the state of a PRNG. * @param state The return parameter; the state to seed. * @param val1 The lower half of the state. * @param val2 The upper half of the state. */ static void bc_rand_seedState(BcRandState* state, ulong val1, ulong val2) { #if BC_RAND_BUILTIN *state = ((BcRandState) val1) | ((BcRandState) val2) << (BC_LONG_BIT); #else // BC_RAND_BUILTIN state->lo = val1; state->hi = val2; #endif // BC_RAND_BUILTIN } /** * Seeds a PRNG. * @param r The return parameter; the PRNG to seed. * @param state1 The lower half of the state. * @param state2 The upper half of the state. * @param inc1 The lower half of the increment. * @param inc2 The upper half of the increment. */ static void bc_rand_seedRNG(BcRNGData* r, ulong state1, ulong state2, ulong inc1, ulong inc2) { bc_rand_seedState(&r->state, state1, state2); bc_rand_seedState(&r->inc, inc1, inc2); bc_rand_setupInc(r); } /** * Fills a PRNG with random data to seed it. * @param r The PRNG. * @param fulong The function to fill an unsigned long. * @param ptr The parameter to pass to @a fulong. */ static void bc_rand_fill(BcRNGData* r, BcRandUlong fulong, void* ptr) { ulong state1, state2, inc1, inc2; state1 = fulong(ptr); state2 = fulong(ptr); inc1 = fulong(ptr); inc2 = fulong(ptr); bc_rand_seedRNG(r, state1, state2, inc1, inc2); } /** * Executes the "step" portion of a PCG udpate. * @param r The PRNG. */ static void bc_rand_step(BcRNGData* r) { BcRandState temp = bc_rand_mul2(r->state, bc_rand_multiplier); r->state = bc_rand_add2(temp, bc_rand_inc(r)); } /** * Returns the new output of PCG. * @param r The PRNG. * @return The new output from the PRNG. */ static BcRand bc_rand_output(BcRNGData* r) { return BC_RAND_ROT(BC_RAND_FOLD(r->state), BC_RAND_ROTAMT(r->state)); } /** * Seeds every PRNG on the PRNG stack between the top and @a idx that has not * been seeded. * @param r The PRNG stack. * @param rng The PRNG on the top of the stack. Must have been seeded. */ static void bc_rand_seedZeroes(BcRNG* r, BcRNGData* rng, size_t idx) { BcRNGData* rng2; // Just return if there are none to do. if (r->v.len <= idx) return; // Get the first PRNG that might need to be seeded. rng2 = bc_vec_item_rev(&r->v, idx); // Does it need seeding? Then it, and maybe more, do. if (BC_RAND_ZERO(rng2)) { size_t i; // Seed the ones that need seeding. for (i = 1; i < r->v.len; ++i) { bc_rand_copy(bc_vec_item_rev(&r->v, i), rng); } } } void bc_rand_srand(BcRNGData* rng) { int fd = 0; BC_SIG_LOCK; #ifndef _WIN32 // Try /dev/urandom first. fd = open("/dev/urandom", O_RDONLY); if (BC_NO_ERR(fd >= 0)) { bc_rand_fill(rng, bc_rand_frand, &fd); close(fd); } else { // Try /dev/random second. fd = open("/dev/random", O_RDONLY); if (BC_NO_ERR(fd >= 0)) { bc_rand_fill(rng, bc_rand_frand, &fd); close(fd); } } #else // _WIN32 // Try BCryptGenRandom first. bc_rand_fill(rng, bc_rand_winrand, NULL); #endif // _WIN32 // Fallback to rand() until the thing is seeded. while (BC_ERR(BC_RAND_ZERO(rng))) { bc_rand_fill(rng, bc_rand_rand, NULL); } BC_SIG_UNLOCK; } /** * Propagates a change to the PRNG to all PRNG's in the stack that should have * it. The ones that should have it are laid out in the manpages. * @param r The PRNG stack. * @param rng The PRNG that will be used to seed the others. */ static void bc_rand_propagate(BcRNG* r, BcRNGData* rng) { // Just return if there are none to do. if (r->v.len <= 1) return; // If the PRNG has not been modified... if (BC_RAND_NOTMODIFIED(rng)) { size_t i; bool go = true; // Find the first PRNG that is modified and seed the others. for (i = 1; go && i < r->v.len; ++i) { BcRNGData* rng2 = bc_vec_item_rev(&r->v, i); go = BC_RAND_NOTMODIFIED(rng2); bc_rand_copy(rng2, rng); } // Seed everything else. bc_rand_seedZeroes(r, rng, i); } // Seed everything. else bc_rand_seedZeroes(r, rng, 1); } BcRand bc_rand_int(BcRNG* r) { // Get the actual PRNG. BcRNGData* rng = bc_vec_top(&r->v); BcRand res; // Make sure the PRNG is seeded. if (BC_ERR(BC_RAND_ZERO(rng))) bc_rand_srand(rng); BC_SIG_LOCK; // This is the important part of the PRNG. This is the stuff from PCG. bc_rand_step(rng); bc_rand_propagate(r, rng); res = bc_rand_output(rng); BC_SIG_UNLOCK; return res; } BcRand bc_rand_bounded(BcRNG* r, BcRand bound) { + BcRand rand; + BcRand threshold; + // Calculate the threshold below which we have to try again. - BcRand rand, threshold = (0 - bound) % bound; + threshold = (0 - bound) % bound; do { rand = bc_rand_int(r); } while (rand < threshold); return rand % bound; } void bc_rand_seed(BcRNG* r, ulong state1, ulong state2, ulong inc1, ulong inc2) { // Get the actual PRNG. BcRNGData* rng = bc_vec_top(&r->v); // Seed and set up the PRNG's increment. bc_rand_seedState(&rng->inc, inc1, inc2); bc_rand_setupInc(rng); bc_rand_setModified(rng); // If the state is 0, use the increment as the state. Otherwise, seed it // with the state. if (!state1 && !state2) { // NOLINTNEXTLINE memcpy(&rng->state, &rng->inc, sizeof(BcRandState)); bc_rand_step(rng); } else bc_rand_seedState(&rng->state, state1, state2); // Propagate the change to PRNG's that need it. bc_rand_propagate(r, rng); } /** * Returns the increment in the PRNG *without* the odd bit and also with being * shifted one bit down. * @param r The PRNG. * @return The increment without the odd bit and with being shifted one bit * down. */ static BcRandState bc_rand_getInc(BcRNGData* r) { BcRandState res; #if BC_RAND_BUILTIN res = r->inc >> 1; #else // BC_RAND_BUILTIN res = r->inc; res.lo >>= 1; res.lo |= (res.hi & 1) << (BC_LONG_BIT - 1); res.hi >>= 1; #endif // BC_RAND_BUILTIN return res; } void bc_rand_getRands(BcRNG* r, BcRand* s1, BcRand* s2, BcRand* i1, BcRand* i2) { BcRandState inc; BcRNGData* rng = bc_vec_top(&r->v); if (BC_ERR(BC_RAND_ZERO(rng))) bc_rand_srand(rng); // Get the increment. inc = bc_rand_getInc(rng); // Chop the state. *s1 = BC_RAND_TRUNC(rng->state); *s2 = BC_RAND_CHOP(rng->state); // Chop the increment. *i1 = BC_RAND_TRUNC(inc); *i2 = BC_RAND_CHOP(inc); } void bc_rand_push(BcRNG* r) { BcRNGData* rng = bc_vec_pushEmpty(&r->v); // Make sure the PRNG is properly zeroed because that marks it as needing to // be seeded. // NOLINTNEXTLINE memset(rng, 0, sizeof(BcRNGData)); // If there is another item, copy it too. if (r->v.len > 1) bc_rand_copy(rng, bc_vec_item_rev(&r->v, 1)); } void bc_rand_pop(BcRNG* r, bool reset) { bc_vec_npop(&r->v, reset ? r->v.len - 1 : 1); } void bc_rand_init(BcRNG* r) { BC_SIG_ASSERT_LOCKED; bc_vec_init(&r->v, sizeof(BcRNGData), BC_DTOR_NONE); bc_rand_push(r); } #if BC_RAND_USE_FREE void bc_rand_free(BcRNG* r) { BC_SIG_ASSERT_LOCKED; bc_vec_free(&r->v); } #endif // BC_RAND_USE_FREE #endif // BC_ENABLE_EXTRA_MATH diff --git a/contrib/bc/tests/bc/all.txt b/contrib/bc/tests/bc/all.txt index 3d0ea05ba7c0..c710534aac1b 100644 --- a/contrib/bc/tests/bc/all.txt +++ b/contrib/bc/tests/bc/all.txt @@ -1,61 +1,62 @@ decimal print parse lib2 print2 length scale shift add subtract multiply divide modulus power sqrt trunc places vars boolean comp abs assignments functions scientific engineering globals strings strings2 letters exponent log pi arctangent sine cosine bessel fib arrays misc misc1 misc2 misc3 misc4 misc5 misc6 misc7 misc8 void rand +rand_limits recursive_arrays divmod modexp bitfuncs leadingzero is_number is_string asciify_array line_by_line1 line_by_line2 line_loop_quit1 line_loop_quit2 diff --git a/contrib/bc/tests/bc/rand_limits.txt b/contrib/bc/tests/bc/rand_limits.txt new file mode 100644 index 000000000000..9f6848739e3b --- /dev/null +++ b/contrib/bc/tests/bc/rand_limits.txt @@ -0,0 +1,284 @@ +seed = 12183415694832323910165063565742029266.78201143488173352403523006\ + 17939450703787369504276248076613097826033345478457018711188931947\ + 5643844725709641352295875549316406250 + +if (maxrand() >= 2^64 - 1) { + + for (i = 1; i <= 37; ++i) + { + irand(10^i) + } + + 1 + 77 + 914 + 8200 + 44887 + 866441 + 2358358 + 13559535 + 416767986 + 9276295152 + 89383616490 + 954770306600 + 8117340260822 + 90441255304792 + 123091484400148 + 673234816385761 + 33144762500773628 + 741775860680476044 + 4715856253932519349 + 44722685516799788803 + 691627564627043533689 + 3601367765145373281202 + 27535154823004408648947 + 51478009115008961612866 + 4031778740698066425486191 + 95653217339584215257144674 + 426302455455598639876532628 + 1216686741117783240797844143 + 17705719185928989853748208134 + 784851648926334033332776172502 + 3120413811981279690501349408357 + 38214388551463331616358091659583 + 720453131307667144268209805308554 + 8939221360785849706894139937864130 + 10262211588802126422696984407808741 + 267283013443362846268603285132432016 + 2034014520976339794036584994364919660 +} +else { + + 5 + 15 + 701 + 8215 + 98794 + 602366 + 2027255 + 74687524 + 830825144 + 6081336208 + 24314055735 + 838559932276 + 6866719060925 + 36806875401211 + 406827598340727 + 5356006452532004 + 38220052834497507 + 337361587138720056 + 1181974760686154481 + 16008532535003488966 + 951908092544652236970 + 90730737551380302703 + 46492092840194767743061 + 188697840939074129889664 + 3963332393372745718515074 + 78044317381361304314479194 + 257814131633376797403093774 + 5383100889234097635148206308 + 39812361752905775691804497289 + 222434065196674291290714932718 + 4942298796724199168854529657788 + 30804146383811856719866376789543 + 817977187096950760817419359822004 + 922359768927341898905002631901715 + 84002847212517205019842390182209654 + 423700247670879534125867432896848815 + 982360002329187383971171836321012954 + + for (i = 1; i <= 37; ++i) + { + irand(10^i) + } +} + +seed = 12183415694832323910165063565742029266.82951754507405817776622978\ + 09630984098584076072986006731059784797092101840727292180396879039\ + 9608224106486886739730834960937500000 + +if (maxrand() >= 2^64 - 1) { + + for (i = 1; i <= 37; ++i) + { + irand(10^i) + } + + 9 + 84 + 802 + 9765 + 80115 + 246589 + 4463508 + 85992729 + 977135 + 4189279533 + 68755431294 + 107950335674 + 9675253977558 + 87867459318681 + 801765066192715 + 2162649050595056 + 2892195376814570 + 134060417012729962 + 7176764836888537721 + 5273685153052366176 + 461774434438273613889 + 152344588818260411506 + 11709967193759556155964 + 533206453770793013516792 + 2511508581949736433569969 + 1573162243991468106989339 + 215826582488545888127004159 + 1480805837640270183994742134 + 61049958584446767740466194227 + 145231395106326027295263107581 + 7023255505921253691380349839502 + 48606431941187693512006850149822 + 87214859605659588002413450479944 + 7949773868584392220935704452065706 + 4544031206641768922348422844031232 + 37285268346623956247142903563298469 + 696722030777467416877847444483018982 +} +else { + + 9 + 73 + 468 + 1781 + 79556 + 166610 + 9336284 + 96403025 + 23318279 + 1074901232 + 30659049590 + 125915951725 + 3123436435684 + 52610031172756 + 445020218860038 + 87520306151384 + 47213087211849485 + 154045322058555704 + 9488624282418036451 + 12849313140308039019 + 828063328914872193931 + 2956454855398834052902 + 87417046449320418408586 + 165187095179884370295407 + 3602892678245454556711806 + 88079064510429999588220544 + 376741359503002189591164726 + 56633499559885161310029862 + 11172900796387700171428233596 + 473873806840427957175182603343 + 824290276873152640168308384248 + 36092351141101218267245025967581 + 39973475177812910298579659860850 + 7364670182480566996610562443888661 + 51592684301602944329896812066058114 + 951444349069518195584787848316744461 + 3234933598293500107173129970384252570 + + for (i = 1; i <= 37; ++i) + { + irand(10^i) + } +} + +seed = 149423560533592712773538909996244073918.2952752612544959208642520\ + 06505634103779572918483064082477106507620297186161725006312917321\ + 53815843275879160501062870025634765625 + +if (maxrand() >= 2^64 - 1) { + + for (i = 1; i <= 37; ++i) + { + irand(10^i) + } + + 0 + 94 + 825 + 907 + 62512 + 633399 + 3539412 + 65712557 + 329618801 + 9052319971 + 50117657456 + 719515050973 + 396081658001 + 98762199564287 + 537857673363391 + 5701380917944903 + 16144997029797264 + 918603142053856533 + 4437053492025674148 + 76125560050255946142 + 262504846798815931770 + 688599520356200914010 + 77509440962809216890090 + 889672321539369676198789 + 5795540531885308263478299 + 88374255397211092706329509 + 118231692173643319720953958 + 6218036129497143746927154520 + 3236727278542723274070894570 + 72098882691751515204435662053 + 8305331942254135876823981226459 + 33980292322856768815329277766669 + 154632353482145519952015208333866 + 192400848794451940507964192401413 + 69666401739718540927805290639731997 + 545814355378177567662640611917018958 + 4986776343571879972263664198494529846 +} +else { + + 6 + 47 + 709 + 350 + 45155 + 117711 + 6147313 + 26359748 + 56878412 + 930721373 + 47052494689 + 84216331603 + 1874946867051 + 30417072907659 + 157776263741438 + 3325742508233965 + 39500653878059614 + 278676289794009775 + 3342139004245631096 + 63313724143310202591 + 647891168358497623537 + 5925769871143510986759 + 3051401096746445704645 + 761857520743586046415633 + 9077595326394996332524977 + 2159936754163773508122732 + 426809670586105698135317225 + 3294516277260755029991322796 + 14749983115477586453985047494 + 692100641365100970093726483540 + 9502478720578852594268790479747 + 9062487417784678956874793130476 + 352159971921852073191742323073689 + 2270803770328639487517517910897872 + 35166631277333300065883628523569361 + 596441689792333324819903835359197616 + 6933582360405829608479430394981956723 + + for (i = 1; i <= 37; ++i) + { + irand(10^i) + } +} diff --git a/contrib/bc/tests/bc/rand_limits_results.txt b/contrib/bc/tests/bc/rand_limits_results.txt new file mode 100644 index 000000000000..7950429c5e67 --- /dev/null +++ b/contrib/bc/tests/bc/rand_limits_results.txt @@ -0,0 +1,222 @@ +5 +15 +701 +8215 +98794 +602366 +2027255 +74687524 +830825144 +6081336208 +24314055735 +838559932276 +6866719060925 +36806875401211 +406827598340727 +5356006452532004 +38220052834497507 +337361587138720056 +1181974760686154481 +16008532535003488966 +951908092544652236970 +90730737551380302703 +46492092840194767743061 +188697840939074129889664 +3963332393372745718515074 +78044317381361304314479194 +257814131633376797403093774 +5383100889234097635148206308 +39812361752905775691804497289 +222434065196674291290714932718 +4942298796724199168854529657788 +30804146383811856719866376789543 +817977187096950760817419359822004 +922359768927341898905002631901715 +84002847212517205019842390182209654 +423700247670879534125867432896848815 +982360002329187383971171836321012954 +1 +77 +914 +8200 +44887 +866441 +2358358 +13559535 +416767986 +9276295152 +89383616490 +954770306600 +8117340260822 +90441255304792 +123091484400148 +673234816385761 +33144762500773628 +741775860680476044 +4715856253932519349 +44722685516799788803 +691627564627043533689 +3601367765145373281202 +27535154823004408648947 +51478009115008961612866 +4031778740698066425486191 +95653217339584215257144674 +426302455455598639876532628 +1216686741117783240797844143 +17705719185928989853748208134 +784851648926334033332776172502 +3120413811981279690501349408357 +38214388551463331616358091659583 +720453131307667144268209805308554 +8939221360785849706894139937864130 +10262211588802126422696984407808741 +267283013443362846268603285132432016 +2034014520976339794036584994364919660 +9 +73 +468 +1781 +79556 +166610 +9336284 +96403025 +23318279 +1074901232 +30659049590 +125915951725 +3123436435684 +52610031172756 +445020218860038 +87520306151384 +47213087211849485 +154045322058555704 +9488624282418036451 +12849313140308039019 +828063328914872193931 +2956454855398834052902 +87417046449320418408586 +165187095179884370295407 +3602892678245454556711806 +88079064510429999588220544 +376741359503002189591164726 +56633499559885161310029862 +11172900796387700171428233596 +473873806840427957175182603343 +824290276873152640168308384248 +36092351141101218267245025967581 +39973475177812910298579659860850 +7364670182480566996610562443888661 +51592684301602944329896812066058114 +951444349069518195584787848316744461 +3234933598293500107173129970384252570 +9 +84 +802 +9765 +80115 +246589 +4463508 +85992729 +977135 +4189279533 +68755431294 +107950335674 +9675253977558 +87867459318681 +801765066192715 +2162649050595056 +2892195376814570 +134060417012729962 +7176764836888537721 +5273685153052366176 +461774434438273613889 +152344588818260411506 +11709967193759556155964 +533206453770793013516792 +2511508581949736433569969 +1573162243991468106989339 +215826582488545888127004159 +1480805837640270183994742134 +61049958584446767740466194227 +145231395106326027295263107581 +7023255505921253691380349839502 +48606431941187693512006850149822 +87214859605659588002413450479944 +7949773868584392220935704452065706 +4544031206641768922348422844031232 +37285268346623956247142903563298469 +696722030777467416877847444483018982 +6 +47 +709 +350 +45155 +117711 +6147313 +26359748 +56878412 +930721373 +47052494689 +84216331603 +1874946867051 +30417072907659 +157776263741438 +3325742508233965 +39500653878059614 +278676289794009775 +3342139004245631096 +63313724143310202591 +647891168358497623537 +5925769871143510986759 +3051401096746445704645 +761857520743586046415633 +9077595326394996332524977 +2159936754163773508122732 +426809670586105698135317225 +3294516277260755029991322796 +14749983115477586453985047494 +692100641365100970093726483540 +9502478720578852594268790479747 +9062487417784678956874793130476 +352159971921852073191742323073689 +2270803770328639487517517910897872 +35166631277333300065883628523569361 +596441689792333324819903835359197616 +6933582360405829608479430394981956723 +0 +94 +825 +907 +62512 +633399 +3539412 +65712557 +329618801 +9052319971 +50117657456 +719515050973 +396081658001 +98762199564287 +537857673363391 +5701380917944903 +16144997029797264 +918603142053856533 +4437053492025674148 +76125560050255946142 +262504846798815931770 +688599520356200914010 +77509440962809216890090 +889672321539369676198789 +5795540531885308263478299 +88374255397211092706329509 +118231692173643319720953958 +6218036129497143746927154520 +3236727278542723274070894570 +72098882691751515204435662053 +8305331942254135876823981226459 +33980292322856768815329277766669 +154632353482145519952015208333866 +192400848794451940507964192401413 +69666401739718540927805290639731997 +545814355378177567662640611917018958 +4986776343571879972263664198494529846 diff --git a/contrib/bc/tests/extra_required.txt b/contrib/bc/tests/extra_required.txt index c498802ffaea..038e6775d644 100644 --- a/contrib/bc/tests/extra_required.txt +++ b/contrib/bc/tests/extra_required.txt @@ -1,10 +1,11 @@ engineering lib2 fib places rand +rand_limits scientific shift trunc bitfuncs leadingzero diff --git a/contrib/bc/tests/script.sh b/contrib/bc/tests/script.sh index fef0c5290615..c38cbabe9adc 100755 --- a/contrib/bc/tests/script.sh +++ b/contrib/bc/tests/script.sh @@ -1,221 +1,227 @@ #! /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 script [run_extra_tests] [run_stack_tests] [generate_tests] [time_tests] [exec args...]\n' "$script" exit 1 } # Command-line processing. if [ "$#" -lt 2 ]; then usage "Not enough arguments; expect 2 arguments" fi d="$1" shift check_d_arg "$d" scriptdir="$testdir/$d/scripts" f="$1" shift check_file_arg "$scriptdir/$f" if [ "$#" -gt 0 ]; then run_extra_tests="$1" shift check_bool_arg "$run_extra_tests" else run_extra_tests=1 check_bool_arg "$run_extra_tests" fi if [ "$#" -gt 0 ]; then run_stack_tests="$1" shift check_bool_arg "$run_stack_tests" else run_stack_tests=1 check_bool_arg "$run_stack_tests" fi if [ "$#" -gt 0 ]; then generate="$1" shift check_bool_arg "$generate" else generate=1 check_bool_arg "$generate" fi if [ "$#" -gt 0 ]; then time_tests="$1" shift check_bool_arg "$time_tests" else time_tests=0 check_bool_arg "$generate" fi if [ "$#" -gt 0 ]; then exe="$1" shift check_exec_arg "$exe" else exe="$testdir/../bin/$d" fi # Set stuff for the correct calculator. if [ "$d" = "bc" ]; then if [ "$run_stack_tests" -ne 0 ]; then options="-lgqC" else options="-lqC" fi halt="halt" else options="-xC" halt="q" fi name="${f%.*}" # We specifically want to skip this because it is handled specially. if [ "$f" = "timeconst.bc" ]; then exit 0 fi # Skip the tests that require extra math if we don't have it. if [ "$run_extra_tests" -eq 0 ]; then if [ "$f" = "rand.bc" ] || [ "$f" = "root.bc" ]; then printf 'Skipping %s script: %s\n' "$d" "$f" exit 0 fi fi # Skip the tests that require global stacks flag if we are not allowed to run # them. if [ "$run_stack_tests" -eq 0 ]; then if [ "$f" = "globals.bc" ] || [ "$f" = "references.bc" ] || [ "$f" = "rand.bc" ]; then printf 'Skipping %s script: %s\n' "$d" "$f" exit 0 fi fi out="$outputdir/${d}_outputs/${name}_script_results.txt" outdir=$(dirname "$out") # Make sure the directory exists. if [ ! -d "$outdir" ]; then mkdir -p "$outdir" 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 s="$scriptdir/$f" orig="$testdir/$name.txt" results="$scriptdir/$name.txt" if [ -f "$orig" ]; then res="$orig" elif [ -f "$results" ]; then res="$results" elif [ "$generate" -eq 0 ]; then printf 'Skipping %s script %s\n' "$d" "$f" exit 0 else set +e # This is to check that the command exists. If not, we should not try to # generate the test. Instead, we should just skip. command -v "$d" 1>/dev/null 2>&1 err="$?" set -e if [ "$err" -ne 0 ]; then printf 'Could not find %s to generate results; skipping %s script %s\n' "$d" "$d" "$f" exit 0 fi - # This sed, and the script, are to remove an incompatibility with GNU bc, - # where GNU bc is wrong. See the development manual - # (manuals/development.md#script-tests) for more information. printf 'Generating %s results...' "$f" - printf '%s\n' "$halt" 2> /dev/null | "$d" "$s" | sed -n -f "$testdir/script.sed" > "$results" + + # This particular test needs to be generated straight. + if [ "$d" = "dc" ] && [ "$f" = "stream.dc" ]; then + printf '%s\n' "$halt" 2> /dev/null | "$d" "$s" > "$results" + else + # This sed, and the script, are to remove an incompatibility with GNU + # bc, where GNU bc is wrong. See the development manual + # (manuals/development.md#script-tests) for more information. + printf '%s\n' "$halt" 2> /dev/null | "$d" "$s" | sed -n -f "$testdir/script.sed" > "$results" + fi printf 'done\n' res="$results" fi set +e printf 'Running %s script %s...' "$d" "$f" # Yes this is poor timing, but it works. if [ "$time_tests" -ne 0 ]; then printf '\n' printf '%s\n' "$halt" 2> /dev/null | /usr/bin/time -p "$exe" "$@" $options "$s" > "$out" err="$?" printf '\n' else printf '%s\n' "$halt" 2> /dev/null | "$exe" "$@" $options "$s" > "$out" err="$?" fi checktest "$d" "$err" "script $f" "$res" "$out" rm -f "$out" exec printf 'pass\n'