Index: head/contrib/bc/Makefile.in =================================================================== --- head/contrib/bc/Makefile.in (revision 366317) +++ head/contrib/bc/Makefile.in (revision 366318) @@ -1,364 +1,364 @@ # # SPDX-License-Identifier: BSD-2-Clause # # Copyright (c) 2018-2020 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: -VERSION = 3.1.5 +VERSION = 3.1.6 SRC = %%SRC%% OBJ = %%OBJ%% GCDA = %%GCDA%% GCNO = %%GCNO%% BC_SRC = %%BC_SRC%% BC_OBJ = %%BC_OBJ%% BC_GCDA = %%BC_GCDA%% BC_GCNO = %%BC_GCNO%% DC_SRC = %%DC_SRC%% DC_OBJ = %%DC_OBJ%% DC_GCDA = %%DC_GCDA%% DC_GCNO = %%DC_GCNO%% HISTORY_SRC = %%HISTORY_SRC%% HISTORY_OBJ = %%HISTORY_OBJ%% HISTORY_GCDA = %%HISTORY_GCDA%% HISTORY_GCNO = %%HISTORY_GCNO%% RAND_SRC = %%RAND_SRC%% RAND_OBJ = %%RAND_OBJ%% RAND_GCDA = %%RAND_GCDA%% RAND_GCNO = %%RAND_GCNO%% BC_ENABLED_NAME = BC_ENABLED BC_ENABLED = %%BC_ENABLED%% DC_ENABLED_NAME = DC_ENABLED DC_ENABLED = %%DC_ENABLED%% GEN_DIR = gen GEN = %%GEN%% GEN_EXEC = $(GEN_DIR)/$(GEN) GEN_C = $(GEN_DIR)/$(GEN).c GEN_EMU = %%GEN_EMU%% BC_LIB = $(GEN_DIR)/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 = $(GEN_DIR)/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 = $(GEN_DIR)/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 = $(GEN_DIR)/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 LOCALES = locales EXEC_SUFFIX = %%EXECSUFFIX%% EXEC_PREFIX = %%EXECPREFIX%% BC = bc DC = dc BC_EXEC = $(BIN)/$(EXEC_PREFIX)$(BC) DC_EXEC = $(BIN)/$(EXEC_PREFIX)$(DC) 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 MANPAGE_INSTALL_ARGS = -Dm644 %%DESTDIR%% BINDIR = %%BINDIR%% MAN1DIR = %%MAN1DIR%% MAIN_EXEC = $(EXEC_PREFIX)$(%%MAIN_EXEC%%)$(EXEC_SUFFIX) EXEC = $(%%EXEC%%) NLSPATH = %%NLSPATH%% BC_ENABLE_HISTORY = %%HISTORY%% BC_ENABLE_EXTRA_MATH_NAME = BC_ENABLE_EXTRA_MATH BC_ENABLE_EXTRA_MATH = %%EXTRA_MATH%% BC_ENABLE_NLS = %%NLS%% BC_ENABLE_PROMPT = %%PROMPT%% BC_LONG_BIT = %%LONG_BIT%% RM = rm MKDIR = mkdir INSTALL = ./install.sh SAFE_INSTALL = ./safe-install.sh LINK = ./link.sh MANPAGE = ./manpage.sh KARATSUBA = ./karatsuba.py LOCALE_INSTALL = ./locale_install.sh LOCALE_UNINSTALL = ./locale_uninstall.sh VALGRIND_ARGS = --error-exitcode=100 --leak-check=full --show-leak-kinds=all --errors-for-leak-kinds=all BC_NUM_KARATSUBA_LEN = %%KARATSUBA_LEN%% CPPFLAGS1 = -D$(BC_ENABLED_NAME)=$(BC_ENABLED) -D$(DC_ENABLED_NAME)=$(DC_ENABLED) CPPFLAGS2 = $(CPPFLAGS1) -I./include/ -DVERSION=$(VERSION) %%LONG_BIT_DEFINE%% CPPFLAGS3 = $(CPPFLAGS2) -DEXECPREFIX=$(EXEC_PREFIX) -DMAINEXEC=$(MAIN_EXEC) CPPFLAGS4 = $(CPPFLAGS3) -D_POSIX_C_SOURCE=200809L -D_XOPEN_SOURCE=700 CPPFLAGS5 = $(CPPFLAGS4) -DBC_NUM_KARATSUBA_LEN=$(BC_NUM_KARATSUBA_LEN) CPPFLAGS6 = $(CPPFLAGS5) -DBC_ENABLE_NLS=$(BC_ENABLE_NLS) -DBC_ENABLE_PROMPT=$(BC_ENABLE_PROMPT) CPPFLAGS7 = $(CPPFLAGS6) -D$(BC_ENABLE_EXTRA_MATH_NAME)=$(BC_ENABLE_EXTRA_MATH) CPPFLAGS = $(CPPFLAGS7) -DBC_ENABLE_HISTORY=$(BC_ENABLE_HISTORY) CFLAGS = $(CPPFLAGS) %%CPPFLAGS%% %%CFLAGS%% LDFLAGS = %%LDFLAGS%% HOSTCFLAGS = %%HOSTCFLAGS%% CC = %%CC%% HOSTCC = %%HOSTCC%% BC_LIB_C_ARGS = bc_lib bc.h bc_lib_name $(BC_ENABLED_NAME) 1 BC_LIB2_C_ARGS = bc_lib2 bc.h bc_lib2_name "$(BC_ENABLED_NAME) && $(BC_ENABLE_EXTRA_MATH_NAME)" 1 OBJS1 = $(OBJ) $(DC_OBJ) $(BC_OBJ) $(HISTORY_OBJ) $(RAND_OBJ) $(BC_HELP_O) $(DC_HELP_O) OBJS = $(OBJS1) $(BC_LIB_O) $(BC_LIB2_O) $(BC_LIB3_O) OBJ_TARGETS1 = $(DC_HELP_O) $(BC_HELP_O) $(BC_LIB_O) $(BC_LIB2_O) $(BC_LIB3_O) OBJ_TARGETS = $(OBJ_TARGETS1) $(BC_OBJ) $(DC_OBJ) $(HISTORY_OBJ) $(RAND_OBJ) $(OBJ) .c.o: $(CC) $(CFLAGS) -o $@ -c $< all: make_bin $(OBJ_TARGETS) $(CC) $(CFLAGS) $(OBJS) $(LDFLAGS) -o $(EXEC) %%LINK%% $(GEN_EXEC): %%GEN_EXEC_TARGET%% $(BC_LIB_C): $(GEN_EXEC) $(BC_LIB) $(GEN_EMU) $(GEN_EXEC) $(BC_LIB) $(BC_LIB_C) $(BC_LIB_C_ARGS) $(BC_LIB2_C): $(GEN_EXEC) $(BC_LIB2) $(GEN_EMU) $(GEN_EXEC) $(BC_LIB2) $(BC_LIB2_C) $(BC_LIB2_C_ARGS) $(BC_HELP_C): $(GEN_EXEC) $(BC_HELP) $(GEN_EMU) $(GEN_EXEC) $(BC_HELP) $(BC_HELP_C) bc_help bc.h "" $(BC_ENABLED_NAME) $(DC_HELP_C): $(GEN_EXEC) $(DC_HELP) $(GEN_EMU) $(GEN_EXEC) $(DC_HELP) $(DC_HELP_C) dc_help dc.h "" $(DC_ENABLED_NAME) make_bin: $(MKDIR) -p $(BIN) 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' @printf ' valgrind runs the test suite through valgrind\n' @printf ' valgrind_bc runs the bc test suite, if bc has been built,\n' @printf ' through valgrind\n' @printf ' valgrind_dc runs the dc test suite, if dc has been built,\n' @printf ' through valgrind\n' check: test test: test_bc timeconst test_dc test_bc: %%BC_TEST%% test_dc: %%DC_TEST%% time_test: time_test_bc timeconst time_test_dc time_test_bc: %%BC_TIME_TEST%% time_test_dc: %%DC_TIME_TEST%% timeconst: %%TIMECONST%% valgrind: valgrind_bc valgrind_dc valgrind_bc: %%VG_BC_TEST%% valgrind_dc: %%VG_DC_TEST%% karatsuba: %%KARATSUBA%% karatsuba_test: %%KARATSUBA_TEST%% coverage_output: %%COVERAGE_OUTPUT%% coverage:%%COVERAGE_PREREQS%% version: @printf '%s' "$(VERSION)" libcname: @printf '%s' "$(BC_LIB_C)" extra_math: @printf '%s' "$(BC_ENABLE_EXTRA_MATH)" manpages: $(MANPAGE) bc $(MANPAGE) dc clean_gen: @$(RM) -f $(GEN_EXEC) clean:%%CLEAN_PREREQS%% @printf 'Cleaning files...\n' @$(RM) -f $(OBJ) @$(RM) -f $(BC_OBJ) @$(RM) -f $(DC_OBJ) @$(RM) -f $(HISTORY_OBJ) @$(RM) -f $(RAND_OBJ) @$(RM) -f $(BC_EXEC) @$(RM) -f $(DC_EXEC) @$(RM) -fr $(BIN) @$(RM) -f $(LOCALES)/*.cat @$(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) clean_config: clean @printf 'Cleaning config...\n' @$(RM) -f Makefile @$(RM) -f $(BC_MD) $(DC_MD) @$(RM) -f $(BC_MANPAGE) $(DC_MANPAGE) 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) -f tests/bc/parse.txt tests/bc/parse_results.txt @$(RM) -f tests/bc/print.txt tests/bc/print_results.txt @$(RM) -f tests/bc/bessel.txt tests/bc/bessel_results.txt @$(RM) -f tests/bc/scripts/bessel.txt @$(RM) -f tests/bc/scripts/parse.txt @$(RM) -f tests/bc/scripts/print.txt @$(RM) -f tests/bc/scripts/add.txt @$(RM) -f tests/bc/scripts/divide.txt @$(RM) -f tests/bc/scripts/multiply.txt @$(RM) -f tests/bc/scripts/subtract.txt @$(RM) -f tests/dc/scripts/prime.txt tests/dc/scripts/stream.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 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:%%INSTALL_LOCALES_PREREQS%%%%INSTALL_PREREQS%% $(INSTALL) $(DESTDIR)$(BINDIR) "$(EXEC_SUFFIX)" 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:%%UNINSTALL_LOCALES_PREREQS%%%%UNINSTALL_MAN_PREREQS%%%%UNINSTALL_PREREQS%% Index: head/contrib/bc/NEWS.md =================================================================== --- head/contrib/bc/NEWS.md (revision 366317) +++ head/contrib/bc/NEWS.md (revision 366318) @@ -1,923 +1,931 @@ # News +## 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` 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 in 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]: ./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]: ./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/ Index: head/contrib/bc/include/bc.h =================================================================== --- head/contrib/bc/include/bc.h (revision 366317) +++ head/contrib/bc/include/bc.h (revision 366318) @@ -1,178 +1,182 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2020 Gavin D. Howard and contributors. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * ***************************************************************************** * * Definitions for bc. * */ #ifndef BC_BC_H #define BC_BC_H #if BC_ENABLED #include #include #include #include #include void bc_main(int argc, char **argv); extern const char bc_help[]; extern const char bc_lib[]; extern const char* bc_lib_name; #if BC_ENABLE_EXTRA_MATH extern const char bc_lib2[]; extern const char* bc_lib2_name; #endif // BC_ENABLE_EXTRA_MATH typedef struct BcLexKeyword { uchar data; const char name[9]; } BcLexKeyword; #define BC_LEX_CHAR_MSB(bit) ((bit) << (CHAR_BIT - 1)) #define BC_LEX_KW_POSIX(kw) ((kw)->data & (BC_LEX_CHAR_MSB(1))) #define BC_LEX_KW_LEN(kw) ((size_t) ((kw)->data & ~(BC_LEX_CHAR_MSB(1)))) #define BC_LEX_KW_ENTRY(a, b, c) \ { .data = ((b) & ~(BC_LEX_CHAR_MSB(1))) | BC_LEX_CHAR_MSB(c), .name = a } extern const BcLexKeyword bc_lex_kws[]; extern const size_t bc_lex_kws_len; void bc_lex_token(BcLex *l); #define BC_PARSE_TOP_FLAG_PTR(p) ((uint16_t*) bc_vec_top(&(p)->flags)) #define BC_PARSE_TOP_FLAG(p) (*(BC_PARSE_TOP_FLAG_PTR(p))) #define BC_PARSE_FLAG_BRACE (UINTMAX_C(1)<<0) #define BC_PARSE_BRACE(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_BRACE) #define BC_PARSE_FLAG_FUNC_INNER (UINTMAX_C(1)<<1) #define BC_PARSE_FUNC_INNER(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_FUNC_INNER) #define BC_PARSE_FLAG_FUNC (UINTMAX_C(1)<<2) #define BC_PARSE_FUNC(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_FUNC) #define BC_PARSE_FLAG_BODY (UINTMAX_C(1)<<3) #define BC_PARSE_BODY(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_BODY) #define BC_PARSE_FLAG_LOOP (UINTMAX_C(1)<<4) #define BC_PARSE_LOOP(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_LOOP) #define BC_PARSE_FLAG_LOOP_INNER (UINTMAX_C(1)<<5) #define BC_PARSE_LOOP_INNER(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_LOOP_INNER) #define BC_PARSE_FLAG_IF (UINTMAX_C(1)<<6) #define BC_PARSE_IF(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_IF) #define BC_PARSE_FLAG_ELSE (UINTMAX_C(1)<<7) #define BC_PARSE_ELSE(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_ELSE) #define BC_PARSE_FLAG_IF_END (UINTMAX_C(1)<<8) #define BC_PARSE_IF_END(p) (BC_PARSE_TOP_FLAG(p) & BC_PARSE_FLAG_IF_END) #define BC_PARSE_NO_EXEC(p) ((p)->flags.len != 1 || BC_PARSE_TOP_FLAG(p) != 0) #define BC_PARSE_DELIMITER(t) \ ((t) == BC_LEX_SCOLON || (t) == BC_LEX_NLINE || (t) == BC_LEX_EOF) #define BC_PARSE_BLOCK_STMT(f) \ ((f) & (BC_PARSE_FLAG_ELSE | BC_PARSE_FLAG_LOOP_INNER)) #define BC_PARSE_OP(p, l) (((p) & ~(BC_LEX_CHAR_MSB(1))) | (BC_LEX_CHAR_MSB(l))) #define BC_PARSE_OP_DATA(t) bc_parse_ops[((t) - BC_LEX_OP_INC)] #define BC_PARSE_OP_LEFT(op) (BC_PARSE_OP_DATA(op) & BC_LEX_CHAR_MSB(1)) #define BC_PARSE_OP_PREC(op) (BC_PARSE_OP_DATA(op) & ~(BC_LEX_CHAR_MSB(1))) #define BC_PARSE_EXPR_ENTRY(e1, e2, e3, e4, e5, e6, e7, e8) \ ((UINTMAX_C(e1) << 7) | (UINTMAX_C(e2) << 6) | (UINTMAX_C(e3) << 5) | \ (UINTMAX_C(e4) << 4) | (UINTMAX_C(e5) << 3) | (UINTMAX_C(e6) << 2) | \ (UINTMAX_C(e7) << 1) | (UINTMAX_C(e8) << 0)) #define BC_PARSE_EXPR(i) \ (bc_parse_exprs[(((i) & (uchar) ~(0x07)) >> 3)] & (1 << (7 - ((i) & 0x07)))) #define BC_PARSE_TOP_OP(p) (*((BcLexType*) bc_vec_top(&(p)->ops))) #define BC_PARSE_LEAF(prev, bin_last, rparen) \ (!(bin_last) && ((rparen) || bc_parse_inst_isLeaf(prev))) #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND #define BC_PARSE_INST_VAR(t) \ ((t) >= BC_INST_VAR && (t) <= BC_INST_SEED && (t) != BC_INST_ARRAY) #else // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND #define BC_PARSE_INST_VAR(t) \ ((t) >= BC_INST_VAR && (t) <= BC_INST_SCALE && (t) != BC_INST_ARRAY) #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND #define BC_PARSE_PREV_PREFIX(p) \ ((p) >= BC_INST_NEG && (p) <= BC_INST_BOOL_NOT) #define BC_PARSE_OP_PREFIX(t) ((t) == BC_LEX_OP_BOOL_NOT || (t) == BC_LEX_NEG) // We can calculate the conversion between tokens and exprs by subtracting the // position of the first operator in the lex enum and adding the position of // the first in the expr enum. Note: This only works for binary operators. #define BC_PARSE_TOKEN_INST(t) ((uchar) ((t) - BC_LEX_NEG + BC_INST_NEG)) typedef enum BcParseStatus { BC_PARSE_STATUS_SUCCESS, BC_PARSE_STATUS_EMPTY_EXPR, } BcParseStatus; void bc_parse_expr(BcParse *p, uint8_t flags); void bc_parse_parse(BcParse *p); void bc_parse_expr_status(BcParse *p, uint8_t flags, BcParseNext next); extern const char bc_sig_msg[]; extern const uchar bc_sig_msg_len; extern const char* const bc_parse_const1; extern const uint8_t bc_parse_exprs[]; extern const uchar bc_parse_ops[]; extern const BcParseNext bc_parse_next_expr; extern const BcParseNext bc_parse_next_param; extern const BcParseNext bc_parse_next_print; extern const BcParseNext bc_parse_next_rel; extern const BcParseNext bc_parse_next_elem; extern const BcParseNext bc_parse_next_for; extern const BcParseNext bc_parse_next_read; +#else // BC_ENABLED + +#define BC_PARSE_NO_EXEC(p) (0) + #endif // BC_ENABLED #endif // BC_BC_H Index: head/contrib/bc/release.sh =================================================================== --- head/contrib/bc/release.sh (revision 366317) +++ head/contrib/bc/release.sh (revision 366318) @@ -1,535 +1,536 @@ #! /bin/sh # # SPDX-License-Identifier: BSD-2-Clause # # Copyright (c) 2018-2020 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. # usage() { printf 'usage: %s [run_tests] [generate_tests] [test_with_clang] [test_with_gcc] \n' "$script" printf ' [run_sanitizers] [run_valgrind] [run_64_bit] [run_gen_script]\n' exit 1 } header() { _header_msg="$1" shift printf '\n' printf '*******************\n' printf "$_header_msg" printf '\n' printf '*******************\n' printf '\n' } do_make() { make -j4 "$@" } configure() { _configure_CFLAGS="$1" shift _configure_CC="$1" shift _configure_configure_flags="$1" shift _configure_GEN_HOST="$1" shift _configure_LONG_BIT="$1" shift if [ "$gen_tests" -eq 0 ]; then _configure_configure_flags="-G $_configure_configure_flags" fi if [ "$_configure_CC" = "clang" ]; then _configure_CFLAGS="$clang_flags $_configure_CFLAGS" elif [ "$_configure_CC" = "gcc" ]; then _configure_CFLAGS="$gcc_flags $_configure_CFLAGS" fi _configure_header=$(printf 'Running ./configure.sh %s ...' "$_configure_configure_flags") _configure_header=$(printf "$_configure_header\n CC=\"%s\"\n" "$_configure_CC") _configure_header=$(printf "$_configure_header\n CFLAGS=\"%s\"\n" "$_configure_CFLAGS") _configure_header=$(printf "$_configure_header\n LONG_BIT=%s" "$_configure_LONG_BIT") _configure_header=$(printf "$_configure_header\n GEN_HOST=%s" "$_configure_GEN_HOST") header "$_configure_header" CFLAGS="$_configure_CFLAGS" CC="$_configure_CC" GEN_HOST="$_configure_GEN_HOST" \ LONG_BIT="$_configure_LONG_BIT" ./configure.sh $_configure_configure_flags > /dev/null } build() { _build_CFLAGS="$1" shift _build_CC="$1" shift _build_configure_flags="$1" shift _build_GEN_HOST="$1" shift _build_LONG_BIT="$1" shift configure "$_build_CFLAGS" "$_build_CC" "$_build_configure_flags" "$_build_GEN_HOST" "$_build_LONG_BIT" _build_header=$(printf 'Building...\n CC=%s' "$_build_CC") _build_header=$(printf "$_build_header\n CFLAGS=\"%s\"" "$_build_CFLAGS") _build_header=$(printf "$_build_header\n LONG_BIT=%s" "$_build_LONG_BIT") _build_header=$(printf "$_build_header\n GEN_HOST=%s" "$_build_GEN_HOST") header "$_build_header" do_make > /dev/null 2> "$scriptdir/.test.txt" if [ -s "$scriptdir/.test.txt" ]; then printf '%s generated warning(s):\n' "$_build_CC" printf '\n' cat "$scriptdir/.test.txt" exit 1 fi } runtest() { header "Running tests" if [ "$#" -gt 0 ]; then do_make "$@" else do_make test fi } runconfigtests() { _runconfigtests_CFLAGS="$1" shift _runconfigtests_CC="$1" shift _runconfigtests_configure_flags="$1" shift _runconfigtests_GEN_HOST="$1" shift _runconfigtests_LONG_BIT="$1" shift _runconfigtests_run_tests="$1" shift if [ "$_runconfigtests_run_tests" -ne 0 ]; then _runconfigtests_header=$(printf 'Running tests with configure flags') else _runconfigtests_header=$(printf 'Building with configure flags') fi _runconfigtests_header=$(printf "$_runconfigtests_header \"%s\" ...\n" "$_runconfigtests_configure_flags") _runconfigtests_header=$(printf "$_runconfigtests_header\n CC=%s\n" "$_runconfigseries_CC") _runconfigtests_header=$(printf "$_runconfigtests_header\n CFLAGS=\"%s\"" "$_runconfigseries_CFLAGS") _runconfigtests_header=$(printf "$_runconfigtests_header\n LONG_BIT=%s" "$_runconfigtests_LONG_BIT") _runconfigtests_header=$(printf "$_runconfigtests_header\n GEN_HOST=%s" "$_runconfigtests_GEN_HOST") header "$_runconfigtests_header" build "$_runconfigtests_CFLAGS" "$_runconfigtests_CC" \ "$_runconfigtests_configure_flags" "$_runconfigtests_GEN_HOST" \ "$_runconfigtests_LONG_BIT" if [ "$_runconfigtests_run_tests" -ne 0 ]; then runtest fi do_make clean build "$_runconfigtests_CFLAGS" "$_runconfigtests_CC" \ "$_runconfigtests_configure_flags -b" "$_runconfigtests_GEN_HOST" \ "$_runconfigtests_LONG_BIT" if [ "$_runconfigtests_run_tests" -ne 0 ]; then runtest fi do_make clean build "$_runconfigtests_CFLAGS" "$_runconfigtests_CC" \ "$_runconfigtests_configure_flags -d" "$_runconfigtests_GEN_HOST" \ "$_runconfigtests_LONG_BIT" if [ "$_runconfigtests_run_tests" -ne 0 ]; then runtest fi do_make clean } runconfigseries() { _runconfigseries_CFLAGS="$1" shift _runconfigseries_CC="$1" shift _runconfigseries_configure_flags="$1" shift _runconfigseries_run_tests="$1" shift if [ "$run_64_bit" -ne 0 ]; then runconfigtests "$_runconfigseries_CFLAGS" "$_runconfigseries_CC" \ "$_runconfigseries_configure_flags" 1 64 "$_runconfigseries_run_tests" if [ "$run_gen_script" -ne 0 ]; then runconfigtests "$_runconfigseries_CFLAGS" "$_runconfigseries_CC" \ "$_runconfigseries_configure_flags" 0 64 "$_runconfigseries_run_tests" fi runconfigtests "$_runconfigseries_CFLAGS -DBC_RAND_BUILTIN=0" "$_runconfigseries_CC" \ "$_runconfigseries_configure_flags" 1 64 "$_runconfigseries_run_tests" fi runconfigtests "$_runconfigseries_CFLAGS" "$_runconfigseries_CC" \ "$_runconfigseries_configure_flags" 1 32 "$_runconfigseries_run_tests" if [ "$run_gen_script" -ne 0 ]; then runconfigtests "$_runconfigseries_CFLAGS" "$_runconfigseries_CC" \ "$_runconfigseries_configure_flags" 0 32 "$_runconfigseries_run_tests" fi } runtestseries() { _runtestseries_CFLAGS="$1" shift _runtestseries_CC="$1" shift _runtestseries_configure_flags="$1" shift _runtestseries_run_tests="$1" shift _runtestseries_flags="E H N P EH EN EP HN HP NP EHN EHP ENP HNP EHNP" runconfigseries "$_runtestseries_CFLAGS" "$_runtestseries_CC" \ "$_runtestseries_configure_flags" "$_runtestseries_run_tests" for f in $_runtestseries_flags; do runconfigseries "$_runtestseries_CFLAGS" "$_runtestseries_CC" \ "$_runtestseries_configure_flags -$f" "$_runtestseries_run_tests" done } runtests() { _runtests_CFLAGS="$1" shift _runtests_CC="$1" shift _runtests_configure_flags="$1" shift _runtests_run_tests="$1" shift runtestseries "-std=c99 $_runtests_CFLAGS" "$_runtests_CC" "$_runtests_configure_flags" "$_runtests_run_tests" runtestseries "-std=c11 $_runtests_CFLAGS" "$_runtests_CC" "$_runtests_configure_flags" "$_runtests_run_tests" } karatsuba() { header "Running Karatsuba tests" do_make karatsuba_test } vg() { header "Running valgrind" if [ "$run_64_bit" -ne 0 ]; then _vg_bits=64 else _vg_bits=32 fi build "$debug" "gcc" "-O0 -g" "1" "$_vg_bits" runtest valgrind do_make clean_config build "$debug" "gcc" "-O0 -gb" "1" "$_vg_bits" runtest valgrind do_make clean_config build "$debug" "gcc" "-O0 -gd" "1" "$_vg_bits" runtest valgrind do_make clean_config } debug() { _debug_CC="$1" shift _debug_run_tests="$1" shift runtests "$debug" "$_debug_CC" "-g" "$_debug_run_tests" if [ "$_debug_CC" = "clang" -a "$run_sanitizers" -ne 0 ]; then runtests "$debug -fsanitize=undefined" "$_debug_CC" "-g" "$_debug_run_tests" fi } release() { _release_CC="$1" shift _release_run_tests="$1" shift runtests "$release" "$_release_CC" "-O3" "$_release_run_tests" } reldebug() { _reldebug_CC="$1" shift _reldebug_run_tests="$1" shift runtests "$debug" "$_reldebug_CC" "-gO3" "$_reldebug_run_tests" if [ "$_reldebug_CC" = "clang" -a "$run_sanitizers" -ne 0 ]; then runtests "$debug -fsanitize=address" "$_reldebug_CC" "-gO3" "$_reldebug_run_tests" runtests "$debug -fsanitize=memory" "$_reldebug_CC" "-gO3" "$_reldebug_run_tests" fi } minsize() { _minsize_CC="$1" shift _minsize_run_tests="$1" shift runtests "$release" "$_minsize_CC" "-Os" "$_minsize_run_tests" } build_set() { _build_set_CC="$1" shift _build_set_run_tests="$1" shift debug "$_build_set_CC" "$_build_set_run_tests" release "$_build_set_CC" "$_build_set_run_tests" reldebug "$_build_set_CC" "$_build_set_run_tests" minsize "$_build_set_CC" "$_build_set_run_tests" } clang_flags="-Weverything -Wno-padded -Wno-switch-enum -Wno-format-nonliteral" clang_flags="$clang_flags -Wno-cast-align -Wno-missing-noreturn -Wno-disabled-macro-expansion" clang_flags="$clang_flags -Wno-unreachable-code -Wno-unreachable-code-return" +clang_flags="$clang_flags -Wno-implicit-fallthrough" gcc_flags="-Wno-maybe-uninitialized -Wno-clobbered" cflags="-Wall -Wextra -Werror -pedantic -Wno-conditional-uninitialized" debug="$cflags -fno-omit-frame-pointer" release="$cflags -DNDEBUG" set -e script="$0" scriptdir=$(dirname "$script") if [ "$#" -gt 0 ]; then run_tests="$1" shift else run_tests=1 fi if [ "$#" -gt 0 ]; then gen_tests="$1" shift else gen_tests=1 fi if [ "$#" -gt 0 ]; then test_with_clang="$1" shift else test_with_clang=1 fi if [ "$#" -gt 0 ]; then test_with_gcc="$1" shift else test_with_gcc=1 fi if [ "$#" -gt 0 ]; then run_sanitizers="$1" shift else run_sanitizers=1 fi if [ "$#" -gt 0 ]; then run_valgrind="$1" shift else run_valgrind=1 fi if [ "$#" -gt 0 ]; then run_64_bit="$1" shift else run_64_bit=1 fi if [ "$#" -gt 0 ]; then run_gen_script="$1" shift else run_gen_script=0 fi if [ "$run_64_bit" -ne 0 ]; then bits=64 else bits=32 fi cd "$scriptdir" if [ "$test_with_clang" -ne 0 ]; then defcc="clang" elif [ "$test_with_gcc" -ne 0 ]; then defcc="gcc" else defcc="c99" fi export ASAN_OPTIONS="abort_on_error=1" export UBSAN_OPTIONS="print_stack_trace=1,silence_unsigned_overflow=1" build "$debug" "$defcc" "-g" "1" "$bits" header "Running math library under --standard" printf 'quit\n' | bin/bc -ls version=$(make version) do_make clean_tests if [ "$test_with_clang" -ne 0 ]; then build_set "clang" "$run_tests" fi if [ "$test_with_gcc" -ne 0 ]; then build_set "gcc" "$run_tests" fi if [ "$run_tests" -ne 0 ]; then build "$release" "$defcc" "-O3" "1" "$bits" karatsuba if [ "$run_valgrind" -ne 0 -a "$test_with_gcc" -ne 0 ]; then vg fi printf '\n' printf 'Tests successful.\n' set +e command -v afl-gcc > /dev/null 2>&1 err="$?" set -e if [ "$err" -eq 0 ]; then header "Configuring for afl-gcc..." configure "$debug $gcc_flags -DBC_ENABLE_RAND=0" "afl-gcc" "-HNP -gO3" "1" "$bits" printf '\n' printf 'Run make\n' printf '\n' printf 'Then run %s/tests/randmath.py and the fuzzer.\n' "$scriptdir" printf '\n' printf 'Then run ASan on the fuzzer test cases with the following build:\n' printf '\n' printf ' CFLAGS="-fsanitize=address -fno-omit-frame-pointer -DBC_ENABLE_RAND=0" ./configure.sh -gO3 -HNPS\n' printf ' make\n' printf '\n' printf 'Then run the GitHub release script as follows:\n' printf '\n' printf ' %s .travis.yml codecov.yml release.sh \\\n' "$version" printf ' RELEASE.md tests/afl.py tests/radamsa.sh tests/radamsa.txt tests/randmath.py \\\n' printf ' tests/bc/scripts/timeconst.bc\n' fi fi Index: head/contrib/bc/src/data.c =================================================================== --- head/contrib/bc/src/data.c (revision 366317) +++ head/contrib/bc/src/data.c (revision 366318) @@ -1,1004 +1,1004 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2020 Gavin D. Howard and contributors. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * ***************************************************************************** * * Constant data for bc. * */ #include #include #include #include #include #include #include #include #include #if BC_ENABLED const char bc_sig_msg[] = "\ninterrupt (type \"quit\" to exit)\n"; const uchar bc_sig_msg_len = (uchar) (sizeof(bc_sig_msg) - 1); #endif // BC_ENABLED #if DC_ENABLED const char dc_sig_msg[] = "\ninterrupt (type \"q\" to exit)\n"; const uchar dc_sig_msg_len = (uchar) (sizeof(dc_sig_msg) - 1); #endif // DC_ENABLED const char bc_copyright[] = "Copyright (c) 2018-2020 Gavin D. Howard and contributors\n" "Report bugs at: https://git.yzena.com/gavin/bc\n\n" "This is free software with ABSOLUTELY NO WARRANTY.\n"; const char* const bc_err_func_header = "Function:"; const char* const bc_err_line = ":%zu"; const char *bc_errs[] = { "Math error:", "Parse error:", "Runtime error:", "Fatal error:", #if BC_ENABLED "Warning:", #endif // BC_ENABLED }; const uchar bc_err_ids[] = { BC_ERR_IDX_MATH, BC_ERR_IDX_MATH, BC_ERR_IDX_MATH, BC_ERR_IDX_MATH, BC_ERR_IDX_FATAL, BC_ERR_IDX_FATAL, BC_ERR_IDX_FATAL, BC_ERR_IDX_FATAL, BC_ERR_IDX_FATAL, BC_ERR_IDX_FATAL, BC_ERR_IDX_FATAL, BC_ERR_IDX_FATAL, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_EXEC, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, #if BC_ENABLED BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, BC_ERR_IDX_PARSE, #endif // BC_ENABLED }; const char* const bc_err_msgs[] = { "negative number", "non-integer number", "overflow: number cannot fit", "divide by 0", "memory allocation failed", "I/O error", "cannot open file: %s", "file is not ASCII: %s", "path is a directory: %s", "bad command-line option: \"%s\"", "option requires an argument: '%c' (\"%s\")", "option takes no arguments: '%c' (\"%s\")", "bad ibase: must be [%lu, %lu]", "bad obase: must be [%lu, %lu]", "bad scale: must be [%lu, %lu]", "bad read() expression", "read() call inside of a read() call", "variable or array element is the wrong type", #if DC_ENABLED "stack has too few elements", #else // DC_ENABLED NULL, #endif // DC_ENABLED #if BC_ENABLED "wrong number of parameters; need %zu, have %zu", "undefined function: %s()", "cannot use a void value in an expression", #else NULL, NULL, NULL, #endif // BC_ENABLED "end of file", "bad character '%c'", "string end cannot be found", "comment end cannot be found", "bad token", #if BC_ENABLED "bad expression", "empty expression", "bad print statement", "bad function definition", - "bad assignment: left side must be scale, ibase, " - "obase, seed, last, var, or array element", + ("bad assignment: left side must be scale, ibase, " + "obase, seed, last, var, or array element"), "no auto variable found", "function parameter or auto \"%s%s\" already exists", "block end cannot be found", "cannot return a value from void function: %s()", "var cannot be a reference: %s", "POSIX does not allow names longer than 1 character: %s", "POSIX does not allow '#' script comments", "POSIX does not allow the following keyword: %s", "POSIX does not allow a period ('.') as a shortcut for the last result", "POSIX requires parentheses around return expressions", "POSIX does not allow the following operator: %s", "POSIX does not allow comparison operators outside if statements or loops", "POSIX requires 0 or 1 comparison operators per condition", "POSIX requires all 3 parts of a for loop to be non-empty", #if BC_ENABLE_EXTRA_MATH "POSIX does not allow exponential notation", #else NULL, #endif // BC_ENABLE_EXTRA_MATH "POSIX does not allow array references as function parameters", "POSIX does not allow void functions", "POSIX requires the left brace be on the same line as the function header", #endif // BC_ENABLED }; #if BC_ENABLE_HISTORY const char *bc_history_bad_terms[] = { "dumb", "cons25", "emacs", NULL }; const char bc_history_tab[] = " "; const size_t bc_history_tab_len = sizeof(bc_history_tab) - 1; // These are listed in ascending order for efficiency. const uint32_t bc_history_wchars[][2] = { { 0x1100, 0x115F }, { 0x231A, 0x231B }, { 0x2329, 0x232A }, { 0x23E9, 0x23EC }, { 0x23F0, 0x23F0 }, { 0x23F3, 0x23F3 }, { 0x25FD, 0x25FE }, { 0x2614, 0x2615 }, { 0x2648, 0x2653 }, { 0x267F, 0x267F }, { 0x2693, 0x2693 }, { 0x26A1, 0x26A1 }, { 0x26AA, 0x26AB }, { 0x26BD, 0x26BE }, { 0x26C4, 0x26C5 }, { 0x26CE, 0x26CE }, { 0x26D4, 0x26D4 }, { 0x26EA, 0x26EA }, { 0x26F2, 0x26F3 }, { 0x26F5, 0x26F5 }, { 0x26FA, 0x26FA }, { 0x26FD, 0x26FD }, { 0x2705, 0x2705 }, { 0x270A, 0x270B }, { 0x2728, 0x2728 }, { 0x274C, 0x274C }, { 0x274E, 0x274E }, { 0x2753, 0x2755 }, { 0x2757, 0x2757 }, { 0x2795, 0x2797 }, { 0x27B0, 0x27B0 }, { 0x27BF, 0x27BF }, { 0x2B1B, 0x2B1C }, { 0x2B50, 0x2B50 }, { 0x2B55, 0x2B55 }, { 0x2E80, 0x2E99 }, { 0x2E9B, 0x2EF3 }, { 0x2F00, 0x2FD5 }, { 0x2FF0, 0x2FFB }, { 0x3001, 0x303E }, { 0x3041, 0x3096 }, { 0x3099, 0x30FF }, { 0x3105, 0x312D }, { 0x3131, 0x318E }, { 0x3190, 0x31BA }, { 0x31C0, 0x31E3 }, { 0x31F0, 0x321E }, { 0x3220, 0x3247 }, { 0x3250, 0x32FE }, { 0x3300, 0x4DBF }, { 0x4E00, 0xA48C }, { 0xA490, 0xA4C6 }, { 0xA960, 0xA97C }, { 0xAC00, 0xD7A3 }, { 0xF900, 0xFAFF }, { 0xFE10, 0xFE19 }, { 0xFE30, 0xFE52 }, { 0xFE54, 0xFE66 }, { 0xFE68, 0xFE6B }, { 0x16FE0, 0x16FE0 }, { 0x17000, 0x187EC }, { 0x18800, 0x18AF2 }, { 0x1B000, 0x1B001 }, { 0x1F004, 0x1F004 }, { 0x1F0CF, 0x1F0CF }, { 0x1F18E, 0x1F18E }, { 0x1F191, 0x1F19A }, { 0x1F200, 0x1F202 }, { 0x1F210, 0x1F23B }, { 0x1F240, 0x1F248 }, { 0x1F250, 0x1F251 }, { 0x1F300, 0x1F320 }, { 0x1F32D, 0x1F335 }, { 0x1F337, 0x1F37C }, { 0x1F37E, 0x1F393 }, { 0x1F3A0, 0x1F3CA }, { 0x1F3CF, 0x1F3D3 }, { 0x1F3E0, 0x1F3F0 }, { 0x1F3F4, 0x1F3F4 }, { 0x1F3F8, 0x1F43E }, { 0x1F440, 0x1F440 }, { 0x1F442, 0x1F4FC }, { 0x1F4FF, 0x1F53D }, { 0x1F54B, 0x1F54E }, { 0x1F550, 0x1F567 }, { 0x1F57A, 0x1F57A }, { 0x1F595, 0x1F596 }, { 0x1F5A4, 0x1F5A4 }, { 0x1F5FB, 0x1F64F }, { 0x1F680, 0x1F6C5 }, { 0x1F6CC, 0x1F6CC }, { 0x1F6D0, 0x1F6D2 }, { 0x1F6EB, 0x1F6EC }, { 0x1F6F4, 0x1F6F6 }, { 0x1F910, 0x1F91E }, { 0x1F920, 0x1F927 }, { 0x1F930, 0x1F930 }, { 0x1F933, 0x1F93E }, { 0x1F940, 0x1F94B }, { 0x1F950, 0x1F95E }, { 0x1F980, 0x1F991 }, { 0x1F9C0, 0x1F9C0 }, { 0x20000, 0x2FFFD }, { 0x30000, 0x3FFFD }, }; const size_t bc_history_wchars_len = sizeof(bc_history_wchars) / sizeof(bc_history_wchars[0]); // These are listed in ascending order for efficiency. const uint32_t bc_history_combo_chars[] = { 0x0300,0x0301,0x0302,0x0303,0x0304,0x0305,0x0306,0x0307, 0x0308,0x0309,0x030A,0x030B,0x030C,0x030D,0x030E,0x030F, 0x0310,0x0311,0x0312,0x0313,0x0314,0x0315,0x0316,0x0317, 0x0318,0x0319,0x031A,0x031B,0x031C,0x031D,0x031E,0x031F, 0x0320,0x0321,0x0322,0x0323,0x0324,0x0325,0x0326,0x0327, 0x0328,0x0329,0x032A,0x032B,0x032C,0x032D,0x032E,0x032F, 0x0330,0x0331,0x0332,0x0333,0x0334,0x0335,0x0336,0x0337, 0x0338,0x0339,0x033A,0x033B,0x033C,0x033D,0x033E,0x033F, 0x0340,0x0341,0x0342,0x0343,0x0344,0x0345,0x0346,0x0347, 0x0348,0x0349,0x034A,0x034B,0x034C,0x034D,0x034E,0x034F, 0x0350,0x0351,0x0352,0x0353,0x0354,0x0355,0x0356,0x0357, 0x0358,0x0359,0x035A,0x035B,0x035C,0x035D,0x035E,0x035F, 0x0360,0x0361,0x0362,0x0363,0x0364,0x0365,0x0366,0x0367, 0x0368,0x0369,0x036A,0x036B,0x036C,0x036D,0x036E,0x036F, 0x0483,0x0484,0x0485,0x0486,0x0487,0x0591,0x0592,0x0593, 0x0594,0x0595,0x0596,0x0597,0x0598,0x0599,0x059A,0x059B, 0x059C,0x059D,0x059E,0x059F,0x05A0,0x05A1,0x05A2,0x05A3, 0x05A4,0x05A5,0x05A6,0x05A7,0x05A8,0x05A9,0x05AA,0x05AB, 0x05AC,0x05AD,0x05AE,0x05AF,0x05B0,0x05B1,0x05B2,0x05B3, 0x05B4,0x05B5,0x05B6,0x05B7,0x05B8,0x05B9,0x05BA,0x05BB, 0x05BC,0x05BD,0x05BF,0x05C1,0x05C2,0x05C4,0x05C5,0x05C7, 0x0610,0x0611,0x0612,0x0613,0x0614,0x0615,0x0616,0x0617, 0x0618,0x0619,0x061A,0x064B,0x064C,0x064D,0x064E,0x064F, 0x0650,0x0651,0x0652,0x0653,0x0654,0x0655,0x0656,0x0657, 0x0658,0x0659,0x065A,0x065B,0x065C,0x065D,0x065E,0x065F, 0x0670,0x06D6,0x06D7,0x06D8,0x06D9,0x06DA,0x06DB,0x06DC, 0x06DF,0x06E0,0x06E1,0x06E2,0x06E3,0x06E4,0x06E7,0x06E8, 0x06EA,0x06EB,0x06EC,0x06ED,0x0711,0x0730,0x0731,0x0732, 0x0733,0x0734,0x0735,0x0736,0x0737,0x0738,0x0739,0x073A, 0x073B,0x073C,0x073D,0x073E,0x073F,0x0740,0x0741,0x0742, 0x0743,0x0744,0x0745,0x0746,0x0747,0x0748,0x0749,0x074A, 0x07A6,0x07A7,0x07A8,0x07A9,0x07AA,0x07AB,0x07AC,0x07AD, 0x07AE,0x07AF,0x07B0,0x07EB,0x07EC,0x07ED,0x07EE,0x07EF, 0x07F0,0x07F1,0x07F2,0x07F3,0x0816,0x0817,0x0818,0x0819, 0x081B,0x081C,0x081D,0x081E,0x081F,0x0820,0x0821,0x0822, 0x0823,0x0825,0x0826,0x0827,0x0829,0x082A,0x082B,0x082C, 0x082D,0x0859,0x085A,0x085B,0x08D4,0x08D5,0x08D6,0x08D7, 0x08D8,0x08D9,0x08DA,0x08DB,0x08DC,0x08DD,0x08DE,0x08DF, 0x08E0,0x08E1,0x08E3,0x08E4,0x08E5,0x08E6,0x08E7,0x08E8, 0x08E9,0x08EA,0x08EB,0x08EC,0x08ED,0x08EE,0x08EF,0x08F0, 0x08F1,0x08F2,0x08F3,0x08F4,0x08F5,0x08F6,0x08F7,0x08F8, 0x08F9,0x08FA,0x08FB,0x08FC,0x08FD,0x08FE,0x08FF,0x0900, 0x0901,0x0902,0x093A,0x093C,0x0941,0x0942,0x0943,0x0944, 0x0945,0x0946,0x0947,0x0948,0x094D,0x0951,0x0952,0x0953, 0x0954,0x0955,0x0956,0x0957,0x0962,0x0963,0x0981,0x09BC, 0x09C1,0x09C2,0x09C3,0x09C4,0x09CD,0x09E2,0x09E3,0x0A01, 0x0A02,0x0A3C,0x0A41,0x0A42,0x0A47,0x0A48,0x0A4B,0x0A4C, 0x0A4D,0x0A51,0x0A70,0x0A71,0x0A75,0x0A81,0x0A82,0x0ABC, 0x0AC1,0x0AC2,0x0AC3,0x0AC4,0x0AC5,0x0AC7,0x0AC8,0x0ACD, 0x0AE2,0x0AE3,0x0B01,0x0B3C,0x0B3F,0x0B41,0x0B42,0x0B43, 0x0B44,0x0B4D,0x0B56,0x0B62,0x0B63,0x0B82,0x0BC0,0x0BCD, 0x0C00,0x0C3E,0x0C3F,0x0C40,0x0C46,0x0C47,0x0C48,0x0C4A, 0x0C4B,0x0C4C,0x0C4D,0x0C55,0x0C56,0x0C62,0x0C63,0x0C81, 0x0CBC,0x0CBF,0x0CC6,0x0CCC,0x0CCD,0x0CE2,0x0CE3,0x0D01, 0x0D41,0x0D42,0x0D43,0x0D44,0x0D4D,0x0D62,0x0D63,0x0DCA, 0x0DD2,0x0DD3,0x0DD4,0x0DD6,0x0E31,0x0E34,0x0E35,0x0E36, 0x0E37,0x0E38,0x0E39,0x0E3A,0x0E47,0x0E48,0x0E49,0x0E4A, 0x0E4B,0x0E4C,0x0E4D,0x0E4E,0x0EB1,0x0EB4,0x0EB5,0x0EB6, 0x0EB7,0x0EB8,0x0EB9,0x0EBB,0x0EBC,0x0EC8,0x0EC9,0x0ECA, 0x0ECB,0x0ECC,0x0ECD,0x0F18,0x0F19,0x0F35,0x0F37,0x0F39, 0x0F71,0x0F72,0x0F73,0x0F74,0x0F75,0x0F76,0x0F77,0x0F78, 0x0F79,0x0F7A,0x0F7B,0x0F7C,0x0F7D,0x0F7E,0x0F80,0x0F81, 0x0F82,0x0F83,0x0F84,0x0F86,0x0F87,0x0F8D,0x0F8E,0x0F8F, 0x0F90,0x0F91,0x0F92,0x0F93,0x0F94,0x0F95,0x0F96,0x0F97, 0x0F99,0x0F9A,0x0F9B,0x0F9C,0x0F9D,0x0F9E,0x0F9F,0x0FA0, 0x0FA1,0x0FA2,0x0FA3,0x0FA4,0x0FA5,0x0FA6,0x0FA7,0x0FA8, 0x0FA9,0x0FAA,0x0FAB,0x0FAC,0x0FAD,0x0FAE,0x0FAF,0x0FB0, 0x0FB1,0x0FB2,0x0FB3,0x0FB4,0x0FB5,0x0FB6,0x0FB7,0x0FB8, 0x0FB9,0x0FBA,0x0FBB,0x0FBC,0x0FC6,0x102D,0x102E,0x102F, 0x1030,0x1032,0x1033,0x1034,0x1035,0x1036,0x1037,0x1039, 0x103A,0x103D,0x103E,0x1058,0x1059,0x105E,0x105F,0x1060, 0x1071,0x1072,0x1073,0x1074,0x1082,0x1085,0x1086,0x108D, 0x109D,0x135D,0x135E,0x135F,0x1712,0x1713,0x1714,0x1732, 0x1733,0x1734,0x1752,0x1753,0x1772,0x1773,0x17B4,0x17B5, 0x17B7,0x17B8,0x17B9,0x17BA,0x17BB,0x17BC,0x17BD,0x17C6, 0x17C9,0x17CA,0x17CB,0x17CC,0x17CD,0x17CE,0x17CF,0x17D0, 0x17D1,0x17D2,0x17D3,0x17DD,0x180B,0x180C,0x180D,0x1885, 0x1886,0x18A9,0x1920,0x1921,0x1922,0x1927,0x1928,0x1932, 0x1939,0x193A,0x193B,0x1A17,0x1A18,0x1A1B,0x1A56,0x1A58, 0x1A59,0x1A5A,0x1A5B,0x1A5C,0x1A5D,0x1A5E,0x1A60,0x1A62, 0x1A65,0x1A66,0x1A67,0x1A68,0x1A69,0x1A6A,0x1A6B,0x1A6C, 0x1A73,0x1A74,0x1A75,0x1A76,0x1A77,0x1A78,0x1A79,0x1A7A, 0x1A7B,0x1A7C,0x1A7F,0x1AB0,0x1AB1,0x1AB2,0x1AB3,0x1AB4, 0x1AB5,0x1AB6,0x1AB7,0x1AB8,0x1AB9,0x1ABA,0x1ABB,0x1ABC, 0x1ABD,0x1B00,0x1B01,0x1B02,0x1B03,0x1B34,0x1B36,0x1B37, 0x1B38,0x1B39,0x1B3A,0x1B3C,0x1B42,0x1B6B,0x1B6C,0x1B6D, 0x1B6E,0x1B6F,0x1B70,0x1B71,0x1B72,0x1B73,0x1B80,0x1B81, 0x1BA2,0x1BA3,0x1BA4,0x1BA5,0x1BA8,0x1BA9,0x1BAB,0x1BAC, 0x1BAD,0x1BE6,0x1BE8,0x1BE9,0x1BED,0x1BEF,0x1BF0,0x1BF1, 0x1C2C,0x1C2D,0x1C2E,0x1C2F,0x1C30,0x1C31,0x1C32,0x1C33, 0x1C36,0x1C37,0x1CD0,0x1CD1,0x1CD2,0x1CD4,0x1CD5,0x1CD6, 0x1CD7,0x1CD8,0x1CD9,0x1CDA,0x1CDB,0x1CDC,0x1CDD,0x1CDE, 0x1CDF,0x1CE0,0x1CE2,0x1CE3,0x1CE4,0x1CE5,0x1CE6,0x1CE7, 0x1CE8,0x1CED,0x1CF4,0x1CF8,0x1CF9,0x1DC0,0x1DC1,0x1DC2, 0x1DC3,0x1DC4,0x1DC5,0x1DC6,0x1DC7,0x1DC8,0x1DC9,0x1DCA, 0x1DCB,0x1DCC,0x1DCD,0x1DCE,0x1DCF,0x1DD0,0x1DD1,0x1DD2, 0x1DD3,0x1DD4,0x1DD5,0x1DD6,0x1DD7,0x1DD8,0x1DD9,0x1DDA, 0x1DDB,0x1DDC,0x1DDD,0x1DDE,0x1DDF,0x1DE0,0x1DE1,0x1DE2, 0x1DE3,0x1DE4,0x1DE5,0x1DE6,0x1DE7,0x1DE8,0x1DE9,0x1DEA, 0x1DEB,0x1DEC,0x1DED,0x1DEE,0x1DEF,0x1DF0,0x1DF1,0x1DF2, 0x1DF3,0x1DF4,0x1DF5,0x1DFB,0x1DFC,0x1DFD,0x1DFE,0x1DFF, 0x20D0,0x20D1,0x20D2,0x20D3,0x20D4,0x20D5,0x20D6,0x20D7, 0x20D8,0x20D9,0x20DA,0x20DB,0x20DC,0x20E1,0x20E5,0x20E6, 0x20E7,0x20E8,0x20E9,0x20EA,0x20EB,0x20EC,0x20ED,0x20EE, 0x20EF,0x20F0,0x2CEF,0x2CF0,0x2CF1,0x2D7F,0x2DE0,0x2DE1, 0x2DE2,0x2DE3,0x2DE4,0x2DE5,0x2DE6,0x2DE7,0x2DE8,0x2DE9, 0x2DEA,0x2DEB,0x2DEC,0x2DED,0x2DEE,0x2DEF,0x2DF0,0x2DF1, 0x2DF2,0x2DF3,0x2DF4,0x2DF5,0x2DF6,0x2DF7,0x2DF8,0x2DF9, 0x2DFA,0x2DFB,0x2DFC,0x2DFD,0x2DFE,0x2DFF,0x302A,0x302B, 0x302C,0x302D,0x3099,0x309A,0xA66F,0xA674,0xA675,0xA676, 0xA677,0xA678,0xA679,0xA67A,0xA67B,0xA67C,0xA67D,0xA69E, 0xA69F,0xA6F0,0xA6F1,0xA802,0xA806,0xA80B,0xA825,0xA826, 0xA8C4,0xA8C5,0xA8E0,0xA8E1,0xA8E2,0xA8E3,0xA8E4,0xA8E5, 0xA8E6,0xA8E7,0xA8E8,0xA8E9,0xA8EA,0xA8EB,0xA8EC,0xA8ED, 0xA8EE,0xA8EF,0xA8F0,0xA8F1,0xA926,0xA927,0xA928,0xA929, 0xA92A,0xA92B,0xA92C,0xA92D,0xA947,0xA948,0xA949,0xA94A, 0xA94B,0xA94C,0xA94D,0xA94E,0xA94F,0xA950,0xA951,0xA980, 0xA981,0xA982,0xA9B3,0xA9B6,0xA9B7,0xA9B8,0xA9B9,0xA9BC, 0xA9E5,0xAA29,0xAA2A,0xAA2B,0xAA2C,0xAA2D,0xAA2E,0xAA31, 0xAA32,0xAA35,0xAA36,0xAA43,0xAA4C,0xAA7C,0xAAB0,0xAAB2, 0xAAB3,0xAAB4,0xAAB7,0xAAB8,0xAABE,0xAABF,0xAAC1,0xAAEC, 0xAAED,0xAAF6,0xABE5,0xABE8,0xABED,0xFB1E,0xFE00,0xFE01, 0xFE02,0xFE03,0xFE04,0xFE05,0xFE06,0xFE07,0xFE08,0xFE09, 0xFE0A,0xFE0B,0xFE0C,0xFE0D,0xFE0E,0xFE0F,0xFE20,0xFE21, 0xFE22,0xFE23,0xFE24,0xFE25,0xFE26,0xFE27,0xFE28,0xFE29, 0xFE2A,0xFE2B,0xFE2C,0xFE2D,0xFE2E,0xFE2F, 0x101FD,0x102E0,0x10376,0x10377,0x10378,0x10379,0x1037A,0x10A01, 0x10A02,0x10A03,0x10A05,0x10A06,0x10A0C,0x10A0D,0x10A0E,0x10A0F, 0x10A38,0x10A39,0x10A3A,0x10A3F,0x10AE5,0x10AE6,0x11001,0x11038, 0x11039,0x1103A,0x1103B,0x1103C,0x1103D,0x1103E,0x1103F,0x11040, 0x11041,0x11042,0x11043,0x11044,0x11045,0x11046,0x1107F,0x11080, 0x11081,0x110B3,0x110B4,0x110B5,0x110B6,0x110B9,0x110BA,0x11100, 0x11101,0x11102,0x11127,0x11128,0x11129,0x1112A,0x1112B,0x1112D, 0x1112E,0x1112F,0x11130,0x11131,0x11132,0x11133,0x11134,0x11173, 0x11180,0x11181,0x111B6,0x111B7,0x111B8,0x111B9,0x111BA,0x111BB, 0x111BC,0x111BD,0x111BE,0x111CA,0x111CB,0x111CC,0x1122F,0x11230, 0x11231,0x11234,0x11236,0x11237,0x1123E,0x112DF,0x112E3,0x112E4, 0x112E5,0x112E6,0x112E7,0x112E8,0x112E9,0x112EA,0x11300,0x11301, 0x1133C,0x11340,0x11366,0x11367,0x11368,0x11369,0x1136A,0x1136B, 0x1136C,0x11370,0x11371,0x11372,0x11373,0x11374,0x11438,0x11439, 0x1143A,0x1143B,0x1143C,0x1143D,0x1143E,0x1143F,0x11442,0x11443, 0x11444,0x11446,0x114B3,0x114B4,0x114B5,0x114B6,0x114B7,0x114B8, 0x114BA,0x114BF,0x114C0,0x114C2,0x114C3,0x115B2,0x115B3,0x115B4, 0x115B5,0x115BC,0x115BD,0x115BF,0x115C0,0x115DC,0x115DD,0x11633, 0x11634,0x11635,0x11636,0x11637,0x11638,0x11639,0x1163A,0x1163D, 0x1163F,0x11640,0x116AB,0x116AD,0x116B0,0x116B1,0x116B2,0x116B3, 0x116B4,0x116B5,0x116B7,0x1171D,0x1171E,0x1171F,0x11722,0x11723, 0x11724,0x11725,0x11727,0x11728,0x11729,0x1172A,0x1172B,0x11C30, 0x11C31,0x11C32,0x11C33,0x11C34,0x11C35,0x11C36,0x11C38,0x11C39, 0x11C3A,0x11C3B,0x11C3C,0x11C3D,0x11C3F,0x11C92,0x11C93,0x11C94, 0x11C95,0x11C96,0x11C97,0x11C98,0x11C99,0x11C9A,0x11C9B,0x11C9C, 0x11C9D,0x11C9E,0x11C9F,0x11CA0,0x11CA1,0x11CA2,0x11CA3,0x11CA4, 0x11CA5,0x11CA6,0x11CA7,0x11CAA,0x11CAB,0x11CAC,0x11CAD,0x11CAE, 0x11CAF,0x11CB0,0x11CB2,0x11CB3,0x11CB5,0x11CB6,0x16AF0,0x16AF1, 0x16AF2,0x16AF3,0x16AF4,0x16B30,0x16B31,0x16B32,0x16B33,0x16B34, 0x16B35,0x16B36,0x16F8F,0x16F90,0x16F91,0x16F92,0x1BC9D,0x1BC9E, 0x1D167,0x1D168,0x1D169,0x1D17B,0x1D17C,0x1D17D,0x1D17E,0x1D17F, 0x1D180,0x1D181,0x1D182,0x1D185,0x1D186,0x1D187,0x1D188,0x1D189, 0x1D18A,0x1D18B,0x1D1AA,0x1D1AB,0x1D1AC,0x1D1AD,0x1D242,0x1D243, 0x1D244,0x1DA00,0x1DA01,0x1DA02,0x1DA03,0x1DA04,0x1DA05,0x1DA06, 0x1DA07,0x1DA08,0x1DA09,0x1DA0A,0x1DA0B,0x1DA0C,0x1DA0D,0x1DA0E, 0x1DA0F,0x1DA10,0x1DA11,0x1DA12,0x1DA13,0x1DA14,0x1DA15,0x1DA16, 0x1DA17,0x1DA18,0x1DA19,0x1DA1A,0x1DA1B,0x1DA1C,0x1DA1D,0x1DA1E, 0x1DA1F,0x1DA20,0x1DA21,0x1DA22,0x1DA23,0x1DA24,0x1DA25,0x1DA26, 0x1DA27,0x1DA28,0x1DA29,0x1DA2A,0x1DA2B,0x1DA2C,0x1DA2D,0x1DA2E, 0x1DA2F,0x1DA30,0x1DA31,0x1DA32,0x1DA33,0x1DA34,0x1DA35,0x1DA36, 0x1DA3B,0x1DA3C,0x1DA3D,0x1DA3E,0x1DA3F,0x1DA40,0x1DA41,0x1DA42, 0x1DA43,0x1DA44,0x1DA45,0x1DA46,0x1DA47,0x1DA48,0x1DA49,0x1DA4A, 0x1DA4B,0x1DA4C,0x1DA4D,0x1DA4E,0x1DA4F,0x1DA50,0x1DA51,0x1DA52, 0x1DA53,0x1DA54,0x1DA55,0x1DA56,0x1DA57,0x1DA58,0x1DA59,0x1DA5A, 0x1DA5B,0x1DA5C,0x1DA5D,0x1DA5E,0x1DA5F,0x1DA60,0x1DA61,0x1DA62, 0x1DA63,0x1DA64,0x1DA65,0x1DA66,0x1DA67,0x1DA68,0x1DA69,0x1DA6A, 0x1DA6B,0x1DA6C,0x1DA75,0x1DA84,0x1DA9B,0x1DA9C,0x1DA9D,0x1DA9E, 0x1DA9F,0x1DAA1,0x1DAA2,0x1DAA3,0x1DAA4,0x1DAA5,0x1DAA6,0x1DAA7, 0x1DAA8,0x1DAA9,0x1DAAA,0x1DAAB,0x1DAAC,0x1DAAD,0x1DAAE,0x1DAAF, 0x1E000,0x1E001,0x1E002,0x1E003,0x1E004,0x1E005,0x1E006,0x1E008, 0x1E009,0x1E00A,0x1E00B,0x1E00C,0x1E00D,0x1E00E,0x1E00F,0x1E010, 0x1E011,0x1E012,0x1E013,0x1E014,0x1E015,0x1E016,0x1E017,0x1E018, 0x1E01B,0x1E01C,0x1E01D,0x1E01E,0x1E01F,0x1E020,0x1E021,0x1E023, 0x1E024,0x1E026,0x1E027,0x1E028,0x1E029,0x1E02A,0x1E8D0,0x1E8D1, 0x1E8D2,0x1E8D3,0x1E8D4,0x1E8D5,0x1E8D6,0x1E944,0x1E945,0x1E946, 0x1E947,0x1E948,0x1E949,0x1E94A,0xE0100,0xE0101,0xE0102,0xE0103, 0xE0104,0xE0105,0xE0106,0xE0107,0xE0108,0xE0109,0xE010A,0xE010B, 0xE010C,0xE010D,0xE010E,0xE010F,0xE0110,0xE0111,0xE0112,0xE0113, 0xE0114,0xE0115,0xE0116,0xE0117,0xE0118,0xE0119,0xE011A,0xE011B, 0xE011C,0xE011D,0xE011E,0xE011F,0xE0120,0xE0121,0xE0122,0xE0123, 0xE0124,0xE0125,0xE0126,0xE0127,0xE0128,0xE0129,0xE012A,0xE012B, 0xE012C,0xE012D,0xE012E,0xE012F,0xE0130,0xE0131,0xE0132,0xE0133, 0xE0134,0xE0135,0xE0136,0xE0137,0xE0138,0xE0139,0xE013A,0xE013B, 0xE013C,0xE013D,0xE013E,0xE013F,0xE0140,0xE0141,0xE0142,0xE0143, 0xE0144,0xE0145,0xE0146,0xE0147,0xE0148,0xE0149,0xE014A,0xE014B, 0xE014C,0xE014D,0xE014E,0xE014F,0xE0150,0xE0151,0xE0152,0xE0153, 0xE0154,0xE0155,0xE0156,0xE0157,0xE0158,0xE0159,0xE015A,0xE015B, 0xE015C,0xE015D,0xE015E,0xE015F,0xE0160,0xE0161,0xE0162,0xE0163, 0xE0164,0xE0165,0xE0166,0xE0167,0xE0168,0xE0169,0xE016A,0xE016B, 0xE016C,0xE016D,0xE016E,0xE016F,0xE0170,0xE0171,0xE0172,0xE0173, 0xE0174,0xE0175,0xE0176,0xE0177,0xE0178,0xE0179,0xE017A,0xE017B, 0xE017C,0xE017D,0xE017E,0xE017F,0xE0180,0xE0181,0xE0182,0xE0183, 0xE0184,0xE0185,0xE0186,0xE0187,0xE0188,0xE0189,0xE018A,0xE018B, 0xE018C,0xE018D,0xE018E,0xE018F,0xE0190,0xE0191,0xE0192,0xE0193, 0xE0194,0xE0195,0xE0196,0xE0197,0xE0198,0xE0199,0xE019A,0xE019B, 0xE019C,0xE019D,0xE019E,0xE019F,0xE01A0,0xE01A1,0xE01A2,0xE01A3, 0xE01A4,0xE01A5,0xE01A6,0xE01A7,0xE01A8,0xE01A9,0xE01AA,0xE01AB, 0xE01AC,0xE01AD,0xE01AE,0xE01AF,0xE01B0,0xE01B1,0xE01B2,0xE01B3, 0xE01B4,0xE01B5,0xE01B6,0xE01B7,0xE01B8,0xE01B9,0xE01BA,0xE01BB, 0xE01BC,0xE01BD,0xE01BE,0xE01BF,0xE01C0,0xE01C1,0xE01C2,0xE01C3, 0xE01C4,0xE01C5,0xE01C6,0xE01C7,0xE01C8,0xE01C9,0xE01CA,0xE01CB, 0xE01CC,0xE01CD,0xE01CE,0xE01CF,0xE01D0,0xE01D1,0xE01D2,0xE01D3, 0xE01D4,0xE01D5,0xE01D6,0xE01D7,0xE01D8,0xE01D9,0xE01DA,0xE01DB, 0xE01DC,0xE01DD,0xE01DE,0xE01DF,0xE01E0,0xE01E1,0xE01E2,0xE01E3, 0xE01E4,0xE01E5,0xE01E6,0xE01E7,0xE01E8,0xE01E9,0xE01EA,0xE01EB, 0xE01EC,0xE01ED,0xE01EE,0xE01EF, }; const size_t bc_history_combo_chars_len = sizeof(bc_history_combo_chars) / sizeof(bc_history_combo_chars[0]); #if BC_DEBUG_CODE BcFile bc_history_debug_fp; char *bc_history_debug_buf; #endif // BC_DEBUG_CODE #endif // BC_ENABLE_HISTORY const char bc_func_main[] = "(main)"; const char bc_func_read[] = "(read)"; #if BC_DEBUG_CODE const char* bc_inst_names[] = { #if BC_ENABLED "BC_INST_INC", "BC_INST_DEC", #endif // BC_ENABLED "BC_INST_NEG", "BC_INST_BOOL_NOT", #if BC_ENABLE_EXTRA_MATH "BC_INST_TRUNC", #endif // BC_ENABLE_EXTRA_MATH "BC_INST_POWER", "BC_INST_MULTIPLY", "BC_INST_DIVIDE", "BC_INST_MODULUS", "BC_INST_PLUS", "BC_INST_MINUS", #if BC_ENABLE_EXTRA_MATH "BC_INST_PLACES", "BC_INST_LSHIFT", "BC_INST_RSHIFT", #endif // BC_ENABLE_EXTRA_MATH "BC_INST_REL_EQ", "BC_INST_REL_LE", "BC_INST_REL_GE", "BC_INST_REL_NE", "BC_INST_REL_LT", "BC_INST_REL_GT", "BC_INST_BOOL_OR", "BC_INST_BOOL_AND", #if BC_ENABLED "BC_INST_ASSIGN_POWER", "BC_INST_ASSIGN_MULTIPLY", "BC_INST_ASSIGN_DIVIDE", "BC_INST_ASSIGN_MODULUS", "BC_INST_ASSIGN_PLUS", "BC_INST_ASSIGN_MINUS", #if BC_ENABLE_EXTRA_MATH "BC_INST_ASSIGN_PLACES", "BC_INST_ASSIGN_LSHIFT", "BC_INST_ASSIGN_RSHIFT", #endif // BC_ENABLE_EXTRA_MATH "BC_INST_ASSIGN", "BC_INST_ASSIGN_POWER_NO_VAL", "BC_INST_ASSIGN_MULTIPLY_NO_VAL", "BC_INST_ASSIGN_DIVIDE_NO_VAL", "BC_INST_ASSIGN_MODULUS_NO_VAL", "BC_INST_ASSIGN_PLUS_NO_VAL", "BC_INST_ASSIGN_MINUS_NO_VAL", #if BC_ENABLE_EXTRA_MATH "BC_INST_ASSIGN_PLACES_NO_VAL", "BC_INST_ASSIGN_LSHIFT_NO_VAL", "BC_INST_ASSIGN_RSHIFT_NO_VAL", #endif // BC_ENABLE_EXTRA_MATH #endif // BC_ENABLED "BC_INST_ASSIGN_NO_VAL", "BC_INST_NUM", "BC_INST_VAR", "BC_INST_ARRAY_ELEM", #if BC_ENABLED "BC_INST_ARRAY", #endif // BC_ENABLED "BC_INST_ZERO", "BC_INST_ONE", #if BC_ENABLED "BC_INST_LAST", #endif // BC_ENABLED "BC_INST_IBASE", "BC_INST_OBASE", "BC_INST_SCALE", #if BC_ENABLE_EXTRA_MATH "BC_INST_SEED", #endif // BC_ENABLE_EXTRA_MATH "BC_INST_LENGTH", "BC_INST_SCALE_FUNC", "BC_INST_SQRT", "BC_INST_ABS", #if BC_ENABLE_EXTRA_MATH "BC_INST_IRAND", #endif // BC_ENABLE_EXTRA_MATH "BC_INST_READ", #if BC_ENABLE_EXTRA_MATH "BC_INST_RAND", #endif // BC_ENABLE_EXTRA_MATH "BC_INST_MAXIBASE", "BC_INST_MAXOBASE", "BC_INST_MAXSCALE", #if BC_ENABLE_EXTRA_MATH "BC_INST_MAXRAND", #endif // BC_ENABLE_EXTRA_MATH "BC_INST_PRINT", "BC_INST_PRINT_POP", "BC_INST_STR", "BC_INST_PRINT_STR", #if BC_ENABLED "BC_INST_JUMP", "BC_INST_JUMP_ZERO", "BC_INST_CALL", "BC_INST_RET", "BC_INST_RET0", "BC_INST_RET_VOID", "BC_INST_HALT", #endif // BC_ENABLED #if DC_ENABLED "BC_INST_POP", "BC_INST_POP_EXEC", "BC_INST_MODEXP", "BC_INST_DIVMOD", "BC_INST_EXECUTE", "BC_INST_EXEC_COND", "BC_INST_ASCIIFY", "BC_INST_PRINT_STREAM", "BC_INST_PRINT_STACK", "BC_INST_CLEAR_STACK", "BC_INST_STACK_LEN", "BC_INST_DUPLICATE", "BC_INST_SWAP", "BC_INST_LOAD", "BC_INST_PUSH_VAR", "BC_INST_PUSH_TO_VAR", "BC_INST_QUIT", "BC_INST_NQUIT", #endif // DC_ENABLED }; #endif // BC_DEBUG_CODE #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND const BcRandState bc_rand_multiplier = BC_RAND_MULTIPLIER; #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND #if BC_ENABLED const BcLexKeyword bc_lex_kws[] = { BC_LEX_KW_ENTRY("auto", 4, true), BC_LEX_KW_ENTRY("break", 5, true), BC_LEX_KW_ENTRY("continue", 8, false), BC_LEX_KW_ENTRY("define", 6, true), BC_LEX_KW_ENTRY("for", 3, true), BC_LEX_KW_ENTRY("if", 2, true), BC_LEX_KW_ENTRY("limits", 6, false), BC_LEX_KW_ENTRY("return", 6, true), BC_LEX_KW_ENTRY("while", 5, true), BC_LEX_KW_ENTRY("halt", 4, false), BC_LEX_KW_ENTRY("last", 4, false), BC_LEX_KW_ENTRY("ibase", 5, true), BC_LEX_KW_ENTRY("obase", 5, true), BC_LEX_KW_ENTRY("scale", 5, true), #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_ENTRY("seed", 4, false), #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_ENTRY("length", 6, true), BC_LEX_KW_ENTRY("print", 5, false), BC_LEX_KW_ENTRY("sqrt", 4, true), BC_LEX_KW_ENTRY("abs", 3, false), #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_ENTRY("irand", 5, false), #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_ENTRY("quit", 4, true), BC_LEX_KW_ENTRY("read", 4, false), #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_ENTRY("rand", 4, false), #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_ENTRY("maxibase", 8, false), BC_LEX_KW_ENTRY("maxobase", 8, false), BC_LEX_KW_ENTRY("maxscale", 8, false), #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_ENTRY("maxrand", 7, false), #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_ENTRY("else", 4, false), }; const size_t bc_lex_kws_len = sizeof(bc_lex_kws) / sizeof(BcLexKeyword); const char* const bc_parse_const1 = "1"; // This is an array that corresponds to token types. An entry is // true if the token is valid in an expression, false otherwise. const uint8_t bc_parse_exprs[] = { BC_PARSE_EXPR_ENTRY(false, false, true, true, true, true, true, true), BC_PARSE_EXPR_ENTRY(true, true, true, true, true, true, true, true), BC_PARSE_EXPR_ENTRY(true, true, true, true, true, true, true, true), #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_PARSE_EXPR_ENTRY(true, true, true, true, true, true, true, true), BC_PARSE_EXPR_ENTRY(true, true, false, false, true, true, false, false), BC_PARSE_EXPR_ENTRY(false, false, false, false, false, true, true, false), BC_PARSE_EXPR_ENTRY(false, false, false, false, false, false, false, false), BC_PARSE_EXPR_ENTRY(false, true, true, true, true, true, true, false), BC_PARSE_EXPR_ENTRY(true, true, true, false, true, true, true, true), BC_PARSE_EXPR_ENTRY(true, true, false, 0, 0, 0, 0, 0) #elif BC_ENABLE_EXTRA_MATH // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_PARSE_EXPR_ENTRY(true, true, true, true, true, true, true, true), BC_PARSE_EXPR_ENTRY(true, true, false, false, true, true, false, false), BC_PARSE_EXPR_ENTRY(false, false, false, false, false, true, true, false), BC_PARSE_EXPR_ENTRY(false, false, false, false, false, false, false, false), BC_PARSE_EXPR_ENTRY(false, true, true, true, true, true, false, true), BC_PARSE_EXPR_ENTRY(true, false, true, true, true, true, false, 0), #else // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_PARSE_EXPR_ENTRY(true, true, true, false, false, true, true, false), BC_PARSE_EXPR_ENTRY(false, false, false, false, false, false, true, true), BC_PARSE_EXPR_ENTRY(false, false, false, false, false, false, false, false), BC_PARSE_EXPR_ENTRY(false, false, true, true, true, true, true, false), BC_PARSE_EXPR_ENTRY(true, true, false, true, true, true, true, false) #endif // BC_ENABLE_EXTRA_MATH }; // This is an array of data for operators that correspond to token types. const uchar bc_parse_ops[] = { BC_PARSE_OP(0, false), BC_PARSE_OP(0, false), BC_PARSE_OP(1, false), BC_PARSE_OP(1, false), #if BC_ENABLE_EXTRA_MATH BC_PARSE_OP(2, false), #endif // BC_ENABLE_EXTRA_MATH BC_PARSE_OP(4, false), BC_PARSE_OP(5, true), BC_PARSE_OP(5, true), BC_PARSE_OP(5, true), BC_PARSE_OP(6, true), BC_PARSE_OP(6, true), #if BC_ENABLE_EXTRA_MATH BC_PARSE_OP(3, false), BC_PARSE_OP(7, true), BC_PARSE_OP(7, true), #endif // BC_ENABLE_EXTRA_MATH BC_PARSE_OP(9, true), BC_PARSE_OP(9, true), BC_PARSE_OP(9, true), BC_PARSE_OP(9, true), BC_PARSE_OP(9, true), BC_PARSE_OP(9, true), BC_PARSE_OP(11, true), BC_PARSE_OP(10, true), BC_PARSE_OP(8, false), BC_PARSE_OP(8, false), BC_PARSE_OP(8, false), BC_PARSE_OP(8, false), BC_PARSE_OP(8, false), BC_PARSE_OP(8, false), #if BC_ENABLE_EXTRA_MATH BC_PARSE_OP(8, false), BC_PARSE_OP(8, false), BC_PARSE_OP(8, false), #endif // BC_ENABLE_EXTRA_MATH BC_PARSE_OP(8, false), }; // These identify what tokens can come after expressions in certain cases. const BcParseNext bc_parse_next_expr = BC_PARSE_NEXT(4, BC_LEX_NLINE, BC_LEX_SCOLON, BC_LEX_RBRACE, BC_LEX_EOF); const BcParseNext bc_parse_next_param = BC_PARSE_NEXT(2, BC_LEX_RPAREN, BC_LEX_COMMA); const BcParseNext bc_parse_next_print = BC_PARSE_NEXT(4, BC_LEX_COMMA, BC_LEX_NLINE, BC_LEX_SCOLON, BC_LEX_EOF); const BcParseNext bc_parse_next_rel = BC_PARSE_NEXT(1, BC_LEX_RPAREN); const BcParseNext bc_parse_next_elem = BC_PARSE_NEXT(1, BC_LEX_RBRACKET); const BcParseNext bc_parse_next_for = BC_PARSE_NEXT(1, BC_LEX_SCOLON); const BcParseNext bc_parse_next_read = BC_PARSE_NEXT(2, BC_LEX_NLINE, BC_LEX_EOF); #endif // BC_ENABLED #if DC_ENABLED const uint8_t dc_lex_regs[] = { BC_LEX_OP_REL_EQ, BC_LEX_OP_REL_LE, BC_LEX_OP_REL_GE, BC_LEX_OP_REL_NE, BC_LEX_OP_REL_LT, BC_LEX_OP_REL_GT, BC_LEX_SCOLON, BC_LEX_COLON, BC_LEX_KW_ELSE, BC_LEX_LOAD, BC_LEX_LOAD_POP, BC_LEX_OP_ASSIGN, BC_LEX_STORE_PUSH, }; const size_t dc_lex_regs_len = sizeof(dc_lex_regs) / sizeof(uint8_t); const uchar dc_lex_tokens[] = { #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_IRAND, #else // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_INVALID, #if BC_ENABLE_EXTRA_MATH BC_LEX_OP_TRUNC, #else // BC_ENABLE_EXTRA_MATH BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH BC_LEX_OP_MODULUS, BC_LEX_INVALID, #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_RAND, #else // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_LPAREN, BC_LEX_RPAREN, BC_LEX_OP_MULTIPLY, BC_LEX_OP_PLUS, BC_LEX_INVALID, BC_LEX_OP_MINUS, BC_LEX_INVALID, BC_LEX_OP_DIVIDE, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_COLON, BC_LEX_SCOLON, BC_LEX_OP_REL_GT, BC_LEX_OP_REL_EQ, BC_LEX_OP_REL_LT, BC_LEX_KW_READ, #if BC_ENABLE_EXTRA_MATH BC_LEX_OP_PLACES, #else // BC_ENABLE_EXTRA_MATH BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_EQ_NO_REG, #if BC_ENABLE_EXTRA_MATH BC_LEX_OP_LSHIFT, #else // BC_ENABLE_EXTRA_MATH BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH BC_LEX_KW_IBASE, #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_SEED, #else // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_SCALE, BC_LEX_LOAD_POP, BC_LEX_OP_BOOL_AND, BC_LEX_OP_BOOL_NOT, BC_LEX_KW_OBASE, BC_LEX_PRINT_STREAM, BC_LEX_NQUIT, BC_LEX_POP, BC_LEX_STORE_PUSH, BC_LEX_KW_MAXIBASE, BC_LEX_KW_MAXOBASE, BC_LEX_KW_MAXSCALE, #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_KW_MAXRAND, #else // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_SCALE_FACTOR, BC_LEX_INVALID, BC_LEX_KW_LENGTH, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_OP_POWER, BC_LEX_NEG, BC_LEX_INVALID, BC_LEX_ASCIIFY, BC_LEX_KW_ABS, BC_LEX_CLEAR_STACK, BC_LEX_DUPLICATE, BC_LEX_KW_ELSE, BC_LEX_PRINT_STACK, BC_LEX_INVALID, #if BC_ENABLE_EXTRA_MATH BC_LEX_OP_RSHIFT, #else // BC_ENABLE_EXTRA_MATH BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH BC_LEX_STORE_IBASE, #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_STORE_SEED, #else // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_INVALID, #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_LEX_STORE_SCALE, BC_LEX_LOAD, BC_LEX_OP_BOOL_OR, BC_LEX_PRINT_POP, BC_LEX_STORE_OBASE, BC_LEX_KW_PRINT, BC_LEX_KW_QUIT, BC_LEX_SWAP, BC_LEX_OP_ASSIGN, BC_LEX_INVALID, BC_LEX_INVALID, BC_LEX_KW_SQRT, BC_LEX_INVALID, BC_LEX_EXECUTE, BC_LEX_INVALID, BC_LEX_STACK_LEVEL, BC_LEX_LBRACE, BC_LEX_OP_MODEXP, BC_LEX_RBRACE, BC_LEX_OP_DIVMOD, BC_LEX_INVALID }; const uchar dc_parse_insts[] = { BC_INST_INVALID, BC_INST_INVALID, #if BC_ENABLED BC_INST_INVALID, BC_INST_INVALID, #endif // BC_ENABLED BC_INST_INVALID, BC_INST_BOOL_NOT, #if BC_ENABLE_EXTRA_MATH BC_INST_TRUNC, #endif // BC_ENABLE_EXTRA_MATH BC_INST_POWER, BC_INST_MULTIPLY, BC_INST_DIVIDE, BC_INST_MODULUS, BC_INST_PLUS, BC_INST_MINUS, #if BC_ENABLE_EXTRA_MATH BC_INST_PLACES, BC_INST_LSHIFT, BC_INST_RSHIFT, #endif // BC_ENABLE_EXTRA_MATH BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_BOOL_OR, BC_INST_BOOL_AND, #if BC_ENABLED BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, #if BC_ENABLE_EXTRA_MATH BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, #endif // BC_ENABLE_EXTRA_MATH #endif // BC_ENABLED BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GT, BC_INST_REL_LT, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_REL_GE, BC_INST_INVALID, BC_INST_REL_LE, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, #if BC_ENABLED BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, #endif // BC_ENABLED BC_INST_IBASE, BC_INST_OBASE, BC_INST_SCALE, #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_INST_SEED, #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_INST_LENGTH, BC_INST_PRINT, BC_INST_SQRT, BC_INST_ABS, #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_INST_IRAND, #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_INST_QUIT, BC_INST_INVALID, #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_INST_RAND, #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_INST_MAXIBASE, BC_INST_MAXOBASE, BC_INST_MAXSCALE, #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_INST_MAXRAND, #endif // BC_ENABLE_EXTRA_MATH BC_INST_INVALID, BC_INST_REL_EQ, BC_INST_MODEXP, BC_INST_DIVMOD, BC_INST_INVALID, BC_INST_EXECUTE, BC_INST_PRINT_STACK, BC_INST_CLEAR_STACK, BC_INST_STACK_LEN, BC_INST_DUPLICATE, BC_INST_SWAP, BC_INST_POP, BC_INST_ASCIIFY, BC_INST_PRINT_STREAM, BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, #if BC_ENABLE_EXTRA_MATH BC_INST_INVALID, #endif // BC_ENABLE_EXTRA_MATH BC_INST_INVALID, BC_INST_INVALID, BC_INST_INVALID, BC_INST_PRINT_POP, BC_INST_NQUIT, BC_INST_SCALE_FUNC, }; #endif // DC_ENABLED #if BC_LONG_BIT >= 64 const BcDig bc_num_bigdigMax[] = { 709551616U, 446744073U, 18U }; #else // BC_LONG_BIT >= 64 const BcDig bc_num_bigdigMax[] = { 7296U, 9496U, 42U, }; #endif // BC_LONG_BIT >= 64 const size_t bc_num_bigdigMax_size = sizeof(bc_num_bigdigMax) / sizeof(BcDig); const char bc_parse_zero[] = "0"; const char bc_parse_one[] = "1"; const char bc_num_hex_digits[] = "0123456789ABCDEF"; const BcBigDig bc_num_pow10[BC_BASE_DIGS + 1] = { 1, 10, 100, 1000, 10000, #if BC_BASE_DIGS > 4 100000, 1000000, 10000000, 100000000, 1000000000, #endif // BC_BASE_DIGS > 4 }; const BcNumBinaryOp bc_program_ops[] = { bc_num_pow, bc_num_mul, bc_num_div, bc_num_mod, bc_num_add, bc_num_sub, #if BC_ENABLE_EXTRA_MATH bc_num_places, bc_num_lshift, bc_num_rshift, #endif // BC_ENABLE_EXTRA_MATH }; const BcNumBinaryOpReq bc_program_opReqs[] = { bc_num_powReq, bc_num_mulReq, bc_num_mulReq, bc_num_mulReq, bc_num_addReq, bc_num_addReq, #if BC_ENABLE_EXTRA_MATH bc_num_placesReq, bc_num_placesReq, bc_num_placesReq, #endif // BC_ENABLE_EXTRA_MATH }; const BcProgramUnary bc_program_unarys[] = { bc_program_negate, bc_program_not, #if BC_ENABLE_EXTRA_MATH bc_program_trunc, #endif // BC_ENABLE_EXTRA_MATH }; const char bc_program_exprs_name[] = ""; const char bc_program_stdin_name[] = ""; const char bc_program_ready_msg[] = "ready for more input\n"; const size_t bc_program_ready_msg_len = sizeof(bc_program_ready_msg) - 1; const char bc_program_esc_chars[] = "ab\\efnqrt"; const char bc_program_esc_seqs[] = "\a\b\\\\\f\n\"\r\t"; Index: head/contrib/bc/src/num.c =================================================================== --- head/contrib/bc/src/num.c (revision 366317) +++ head/contrib/bc/src/num.c (revision 366318) @@ -1,2836 +1,2837 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2020 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 #include static void bc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale); static inline ssize_t bc_num_neg(size_t n, bool neg) { return (((ssize_t) n) ^ -((ssize_t) neg)) + neg; } ssize_t bc_num_cmpZero(const BcNum *n) { return bc_num_neg((n)->len != 0, (n)->neg); } static inline size_t bc_num_int(const BcNum *n) { return n->len ? n->len - n->rdx : 0; } 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; } } static void bc_num_setToZero(BcNum *restrict n, size_t scale) { assert(n != NULL); n->scale = scale; n->len = n->rdx = 0; n->neg = false; } static inline 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; } static void bc_num_clean(BcNum *restrict n) { while (BC_NUM_NONZERO(n) && !n->num[n->len - 1]) n->len -= 1; if (BC_NUM_ZERO(n)) { n->neg = false; n->rdx = 0; } else if (n->len < n->rdx) n->len = n->rdx; } static size_t bc_num_log10(size_t i) { size_t len; for (len = 1; i; i /= BC_BASE, ++len); assert(len - 1 <= BC_BASE_DIGS + 1); return len - 1; } 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); } 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; } static size_t bc_num_nonzeroLen(const BcNum *restrict n) { size_t i, len = n->len; assert(len == n->rdx); for (i = len - 1; i < len && !n->num[i]; --i); assert(i + 1 > 0); return i + 1; } 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); assert(b < BC_BASE_POW); a += b + *carry; *carry = (a >= BC_BASE_POW); if (*carry) a -= BC_BASE_POW; assert(a >= 0); assert(a < BC_BASE_POW); return a; } static BcDig bc_num_subDigits(BcDig a, BcDig b, bool *carry) { assert(a < BC_BASE_POW); assert(b < BC_BASE_POW); b += *carry; *carry = (a < b); if (*carry) a += BC_BASE_POW; assert(a - b >= 0); assert(a - b < BC_BASE_POW); return 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); for (; carry; ++i) a[i] = bc_num_addDigits(a[i], 0, &carry); } 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); for (; carry; ++i) a[i] = bc_num_subDigits(a[i], 0, &carry); } 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); if (a->len + 1 > c->cap) bc_num_expand(c, a->len + 1); memset(c->num, 0, BC_NUM_SIZE(c->cap)); 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); c->num[i] = (BcDig) carry; c->len = a->len; c->len += (carry != 0); bc_num_clean(c); assert(!c->neg || BC_NUM_NONZERO(c)); assert(c->rdx <= c->len || !c->len); assert(!c->len || c->num[c->len - 1] || c->rdx == c->len); } 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); 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); carry = in % b; } c->len = a->len; bc_num_clean(c); *rem = carry; assert(!c->neg || BC_NUM_NONZERO(c)); assert(c->rdx <= c->len || !c->len); assert(!c->len || c->num[c->len - 1] || c->rdx == c->len); } 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); 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; BcDig *max_num, *min_num; bool a_max, neg = false; ssize_t cmp; assert(a != NULL && b != NULL); if (a == b) return 0; if (BC_NUM_ZERO(a)) return bc_num_neg(b->len != 0, !b->neg); if (BC_NUM_ZERO(b)) return bc_num_cmpZero(a); if (a->neg) { if (b->neg) neg = true; else return -1; } else if (b->neg) return 1; a_int = bc_num_int(a); b_int = bc_num_int(b); a_int -= b_int; if (a_int) return neg ? -((ssize_t) a_int) : (ssize_t) a_int; a_max = (a->rdx > b->rdx); if (a_max) { min = b->rdx; diff = a->rdx - b->rdx; max_num = a->num + diff; min_num = b->num; } else { min = a->rdx; diff = b->rdx - a->rdx; max_num = b->num + diff; min_num = a->num; } cmp = bc_num_compare(max_num, min_num, b_int + min); if (cmp) return bc_num_neg((size_t) cmp, !a_max == !neg); 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 places_rdx; if (!places) return; places_rdx = n->rdx ? n->rdx - BC_NUM_RDX(n->scale - places) : 0; assert(places <= n->scale && (BC_NUM_ZERO(n) || places_rdx <= n->len)); n->scale -= places; n->rdx -= places_rdx; if (BC_NUM_NONZERO(n)) { size_t pow; pow = n->scale % BC_BASE_DIGS; pow = pow ? BC_BASE_DIGS - pow : 0; pow = bc_num_pow10[pow]; n->len -= places_rdx; 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); } } static void bc_num_extend(BcNum *restrict n, size_t places) { size_t places_rdx; if (!places) return; if (BC_NUM_ZERO(n)) { n->scale += places; return; } places_rdx = BC_NUM_RDX(places + n->scale) - n->rdx; if (places_rdx) { bc_num_expand(n, bc_vm_growSize(n->len, places_rdx)); memmove(n->num + places_rdx, n->num, BC_NUM_SIZE(n->len)); memset(n->num, 0, BC_NUM_SIZE(places_rdx)); } n->rdx += places_rdx; n->scale += places; n->len += places_rdx; assert(n->rdx == BC_NUM_RDX(n->scale)); } static void bc_num_retireMul(BcNum *restrict n, size_t scale, bool neg1, bool neg2) { if (n->scale < scale) bc_num_extend(n, scale - n->scale); else bc_num_truncate(n, n->scale - scale); bc_num_clean(n); if (BC_NUM_NONZERO(n)) n->neg = (!neg1 != !neg2); } static void bc_num_split(const BcNum *restrict n, size_t idx, BcNum *restrict a, BcNum *restrict b) { assert(BC_NUM_ZERO(a)); assert(BC_NUM_ZERO(b)); if (idx < n->len) { b->len = n->len - idx; a->len = idx; a->scale = a->rdx = b->scale = b->rdx = 0; assert(a->cap >= a->len); assert(b->cap >= b->len); memcpy(b->num, n->num + idx, BC_NUM_SIZE(b->len)); memcpy(a->num, n->num, BC_NUM_SIZE(idx)); bc_num_clean(b); } else bc_num_copy(a, n); bc_num_clean(a); } static size_t bc_num_shiftZero(BcNum *restrict n) { size_t i; assert(!n->rdx || BC_NUM_ZERO(n)); for (i = 0; i < n->len && !n->num[i]; ++i); n->len -= i; n->num += i; return i; } static void bc_num_unshiftZero(BcNum *restrict n, size_t places_rdx) { n->len += places_rdx; n->num -= places_rdx; } 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); pow = bc_num_pow10[dig]; dig = bc_num_pow10[BC_BASE_DIGS - dig]; 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(!carry); } static void bc_num_shiftLeft(BcNum *restrict n, size_t places) { BcBigDig dig; size_t places_rdx; bool shift; if (!places) return; if (places > n->scale) { size_t size = bc_vm_growSize(BC_NUM_RDX(places - n->scale), n->len); if (size > SIZE_MAX - 1) bc_vm_err(BC_ERROR_MATH_OVERFLOW); } if (BC_NUM_ZERO(n)) { if (n->scale >= places) n->scale -= places; else n->scale = 0; return; } dig = (BcBigDig) (places % BC_BASE_DIGS); shift = (dig != 0); places_rdx = BC_NUM_RDX(places); if (n->scale) { if (n->rdx >= places_rdx) { size_t mod = n->scale % BC_BASE_DIGS, revdig; mod = mod ? mod : BC_BASE_DIGS; revdig = dig ? BC_BASE_DIGS - dig : 0; if (mod + revdig > BC_BASE_DIGS) places_rdx = 1; else places_rdx = 0; } else places_rdx -= n->rdx; } if (places_rdx) { bc_num_expand(n, bc_vm_growSize(n->len, places_rdx)); memmove(n->num + places_rdx, n->num, BC_NUM_SIZE(n->len)); memset(n->num, 0, BC_NUM_SIZE(places_rdx)); n->len += places_rdx; } if (places > n->scale) n->scale = n->rdx = 0; else { n->scale -= places; n->rdx = BC_NUM_RDX(n->scale); } if (shift) bc_num_shift(n, BC_BASE_DIGS - dig); bc_num_clean(n); } static 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 (BC_NUM_ZERO(n)) { n->scale += places; bc_num_expand(n, BC_NUM_RDX(n->scale)); return; } dig = (BcBigDig) (places % BC_BASE_DIGS); shift = (dig != 0); scale = n->scale; scale_mod = scale % BC_BASE_DIGS; scale_mod = scale_mod ? scale_mod : BC_BASE_DIGS; int_len = bc_num_int(n); places_rdx = BC_NUM_RDX(places); if (scale_mod + dig > BC_BASE_DIGS) { expand = places_rdx - 1; places_rdx = 1; } else { expand = places_rdx; places_rdx = 0; } if (expand > int_len) expand -= int_len; else expand = 0; bc_num_extend(n, places_rdx * BC_BASE_DIGS); bc_num_expand(n, bc_vm_growSize(expand, n->len)); memset(n->num + n->len, 0, BC_NUM_SIZE(expand)); n->len += expand; n->scale = n->rdx = 0; if (shift) bc_num_shift(n, dig); n->scale = scale + places; n->rdx = BC_NUM_RDX(n->scale); bc_num_clean(n); assert(n->rdx <= n->len && n->len <= n->cap); assert(n->rdx == BC_NUM_RDX(n->scale)); } static void bc_num_inv(BcNum *a, BcNum *b, size_t scale) { BcNum one; BcDig num[2]; assert(BC_NUM_NONZERO(a)); bc_num_setup(&one, num, sizeof(num) / sizeof(BcDig)); bc_num_one(&one); bc_num_div(&one, a, b, scale); } #if BC_ENABLE_EXTRA_MATH static void bc_num_intop(const BcNum *a, const BcNum *b, BcNum *restrict c, BcBigDig *v) { if (BC_ERR(b->rdx)) bc_vm_err(BC_ERROR_MATH_NON_INTEGER); bc_num_copy(c, a); bc_num_bigdig(b, v); } #endif // BC_ENABLE_EXTRA_MATH static void bc_num_as(BcNum *a, BcNum *b, BcNum *restrict c, size_t sub) { BcDig *ptr_c, *ptr_l, *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; bool b_neg, do_sub, do_rev_sub, carry; // Because 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. // Convert substraction to addition of negative second operand. if (BC_NUM_ZERO(b)) { bc_num_copy(c, a); return; } if (BC_NUM_ZERO(a)) { bc_num_copy(c, b); c->neg = (b->neg != sub); return; } // Invert sign of b if it is to be subtracted. This operation must // preced the tests for any of the operands being zero. b_neg = (b->neg != sub); // Actually add the numbers if their signs are equal, else subtract. do_sub = (a->neg != b_neg); a_int = bc_num_int(a); b_int = bc_num_int(b); max_int = BC_MAX(a_int, b_int); min_rdx = BC_MIN(a->rdx, b->rdx); max_rdx = BC_MAX(a->rdx, b->rdx); 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 (a->rdx > b->rdx) 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); 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; 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 ((a->rdx > b->rdx) != do_rev_sub) { // !do_rev_sub && a->rdx > b->rdx || do_rev_sub && b->rdx > a->rdx // The left operand has BcDig values that need to be copied, // either from a or from b (in case of a reversed subtraction). 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 && a->rdx > b->rdx || // !do_rev_sub && b->rdx > a->rdx) for (i = 0; i < diff; i++) ptr_c[i] = bc_num_subDigits(0, ptr_r[i], &carry); } else { // !do_sub && b->rdx > a->rdx memcpy(ptr_c, ptr_r, BC_NUM_SIZE(diff)); } ptr_r += diff; len_r -= diff; } ptr_c += diff; } min_len = BC_MIN(len_l, len_r); // After dealing with possible low array elements that depend on only one // operand, 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) { for (i = 0; i < min_len; ++i) ptr_c[i] = bc_num_subDigits(ptr_l[i], ptr_r[i], &carry); for (; i < len_l; ++i) ptr_c[i] = bc_num_subDigits(ptr_l[i], 0, &carry); } else { for (i = 0; i < min_len; ++i) ptr_c[i] = bc_num_addDigits(ptr_l[i], ptr_r[i], &carry); for (; i < len_l; ++i) ptr_c[i] = bc_num_addDigits(ptr_l[i], 0, &carry); 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 = (a->neg != (do_sub && do_rev_sub)); c->len = max_len; c->rdx = max_rdx; c->scale = BC_MAX(a->scale, b->scale); bc_num_clean(c); } 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, *ptr_b = b->num, *ptr_c; BcBigDig sum = 0, carry = 0; assert(sizeof(sum) >= sizeof(BcDig) * 2); assert(!a->rdx && !b->rdx); clen = bc_vm_growSize(alen, blen); bc_num_expand(c, bc_vm_growSize(clen, 1)); ptr_c = c->num; memset(ptr_c, 0, BC_NUM_SIZE(c->cap)); for (i = 0; i < clen; ++i) { ssize_t sidx = (ssize_t) (i - blen + 1); size_t j = (size_t) BC_MAX(0, sidx), k = BC_MIN(i, blen - 1); 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; } } if (sum >= BC_BASE_POW) { carry += sum / BC_BASE_POW; sum %= BC_BASE_POW; } 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; } static void bc_num_shiftAddSub(BcNum *restrict n, const BcNum *restrict a, size_t shift, BcNumShiftAddOp op) { assert(n->len >= shift + a->len); assert(!n->rdx && !a->rdx); op(n->num + shift, a->num, a->len); } static void bc_num_k(BcNum *a, BcNum *b, BcNum *restrict c) { size_t max, max2, total; BcNum l1, h1, l2, h2, m2, m1, z0, z1, z2, temp; BcDig *digs, *dig_ptr; BcNumShiftAddOp op; bool aone = BC_NUM_ONE(a); 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 && a->neg) || b->neg) c->neg = !c->neg; return; } if (a->len < BC_NUM_KARATSUBA_LEN || b->len < BC_NUM_KARATSUBA_LEN) { bc_num_m_simp(a, b, c); return; } max = BC_MAX(a->len, b->len); max = BC_MAX(max, BC_NUM_DEF_SIZE); max2 = (max + 1) / 2; total = bc_vm_arraySize(BC_NUM_KARATSUBA_ALLOCS, max); BC_SIG_LOCK; digs = dig_ptr = bc_vm_malloc(BC_NUM_SIZE(total)); 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); 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(err); BC_SIG_UNLOCK; bc_num_split(a, max2, &l1, &h1); bc_num_split(b, max2, &l2, &h2); bc_num_expand(c, max); c->len = max; memset(c->num, 0, BC_NUM_SIZE(c->len)); bc_num_sub(&h1, &l1, &m1, 0); bc_num_sub(&l2, &h2, &m2, 0); if (BC_NUM_NONZERO(&h1) && BC_NUM_NONZERO(&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)) { 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)) { bc_num_m(&m1, &m2, &z1, 0); bc_num_clean(&z1); op = (m1.neg != m2.neg) ? 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; } static void bc_num_m(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { BcNum cpa, cpb; size_t ascale, bscale, ardx, brdx, azero = 0, bzero = 0, zero, len, rscale; bc_num_zero(c); ascale = a->scale; bscale = b->scale; scale = BC_MAX(scale, ascale); scale = BC_MAX(scale, bscale); rscale = ascale + bscale; scale = BC_MIN(rscale, scale); if ((a->len == 1 || b->len == 1) && !a->rdx && !b->rdx) { BcNum *operand; BcBigDig dig; 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); if (BC_NUM_NONZERO(c)) c->neg = (a->neg != b->neg); return; } BC_SIG_LOCK; bc_num_init(&cpa, a->len + a->rdx); bc_num_init(&cpb, b->len + b->rdx); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; bc_num_copy(&cpa, a); bc_num_copy(&cpb, b); cpa.neg = cpb.neg = false; ardx = cpa.rdx * BC_BASE_DIGS; bc_num_shiftLeft(&cpa, ardx); brdx = cpb.rdx * 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; azero = bc_num_shiftZero(&cpa); bzero = bc_num_shiftZero(&cpb); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; bc_num_clean(&cpa); bc_num_clean(&cpb); bc_num_k(&cpa, &cpb, c); zero = bc_vm_growSize(azero, bzero); len = bc_vm_growSize(c->len, zero); bc_num_expand(c, len); bc_num_shiftLeft(c, (len - c->len) * BC_BASE_DIGS); bc_num_shiftRight(c, ardx + brdx); bc_num_retireMul(c, scale, a->neg, b->neg); err: BC_SIG_MAYLOCK; bc_num_unshiftZero(&cpb, bzero); bc_num_free(&cpb); bc_num_unshiftZero(&cpa, azero); bc_num_free(&cpa); BC_LONGJMP_CONT; } static bool bc_num_nonZeroDig(BcDig *restrict a, size_t len) { size_t i; bool nonzero = false; for (i = len - 1; !nonzero && i < len; --i) nonzero = (a[i] != 0); return nonzero; } 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; } 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); } static void bc_num_d_long(BcNum *restrict a, BcNum *restrict b, BcNum *restrict c, size_t scale) { BcBigDig divisor; size_t len, end, i, rdx; BcNum cpb; bool nonzero = false; assert(b->len < a->len); len = b->len; end = a->len - len; assert(len >= 1); bc_num_expand(c, a->len); memset(c->num, 0, c->cap * sizeof(BcDig)); c->rdx = a->rdx; c->scale = a->scale; c->len = a->len; divisor = (BcBigDig) b->num[len - 1]; if (len > 1 && bc_num_nonZeroDig(b->num, len - 1)) { nonzero = (divisor > 1 << ((10 * BC_BASE_DIGS) / 6 + 1)); if (!nonzero) { bc_num_divExtend(a, b, divisor); len = BC_MAX(a->len, b->len); bc_num_expand(a, len + 1); if (len + 1 > a->len) a->len = len + 1; len = b->len; end = a->len - len; divisor = (BcBigDig) b->num[len - 1]; nonzero = bc_num_nonZeroDig(b->num, len - 1); } } divisor += nonzero; bc_num_expand(c, a->len); memset(c->num, 0, BC_NUM_SIZE(c->cap)); assert(c->scale >= scale); rdx = c->rdx - BC_NUM_RDX(scale); BC_SIG_LOCK; bc_num_init(&cpb, len + 1); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; i = end - 1; for (; i < end && 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); while (cmp >= 0) { BcBigDig n1, dividend, q; n1 = (BcBigDig) n[len]; dividend = n1 * BC_BASE_POW + (BcBigDig) n[len - 1]; q = (dividend / divisor); if (q <= 1) { q = 1; bc_num_subArrays(n, b->num, len); } else { assert(q <= BC_BASE_POW); bc_num_mulArray(b, (BcBigDig) q, &cpb); bc_num_subArrays(n, cpb.num, cpb.len); } result += q; assert(result <= BC_BASE_POW); if (nonzero) cmp = bc_num_divCmp(n, b, len); else cmp = -1; } assert(result < BC_BASE_POW); c->num[i] = (BcDig) result; } err: BC_SIG_MAYLOCK; bc_num_free(&cpb); BC_LONGJMP_CONT; } static void bc_num_d(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { size_t len; BcNum cpa, cpb; if (BC_NUM_ZERO(b)) bc_vm_err(BC_ERROR_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, a->neg, b->neg); return; } if (!a->rdx && !b->rdx && b->len == 1 && !scale) { BcBigDig rem; bc_num_divArray(a, (BcBigDig) b->num[0], c, &rem); bc_num_retireMul(c, scale, a->neg, b->neg); return; } len = bc_num_mulReq(a, b, scale); BC_SIG_LOCK; bc_num_init(&cpa, len); bc_num_copy(&cpa, a); bc_num_createCopy(&cpb, b); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; len = b->len; if (len > cpa.len) { bc_num_expand(&cpa, bc_vm_growSize(len, 2)); bc_num_extend(&cpa, (len - cpa.len) * BC_BASE_DIGS); } cpa.scale = cpa.rdx * BC_BASE_DIGS; bc_num_extend(&cpa, b->scale); cpa.rdx -= BC_NUM_RDX(b->scale); cpa.scale = cpa.rdx * BC_BASE_DIGS; if (scale > cpa.scale) { bc_num_extend(&cpa, scale); cpa.scale = cpa.rdx * BC_BASE_DIGS; } 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; if (cpa.rdx == cpa.len) cpa.len = bc_num_nonzeroLen(&cpa); if (cpb.rdx == cpb.len) cpb.len = bc_num_nonzeroLen(&cpb); cpb.scale = cpb.rdx = 0; bc_num_d_long(&cpa, &cpb, c, scale); bc_num_retireMul(c, scale, a->neg, b->neg); err: BC_SIG_MAYLOCK; bc_num_free(&cpb); bc_num_free(&cpa); BC_LONGJMP_CONT; } static void bc_num_r(BcNum *a, BcNum *b, BcNum *restrict c, BcNum *restrict d, size_t scale, size_t ts) { BcNum temp; bool neg; if (BC_NUM_ZERO(b)) bc_vm_err(BC_ERROR_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(err); BC_SIG_UNLOCK; bc_num_d(a, b, c, scale); if (scale) scale = ts + 1; bc_num_m(c, b, &temp, scale); bc_num_sub(a, &temp, d, scale); if (ts > d->scale && BC_NUM_NONZERO(d)) bc_num_extend(d, ts - d->scale); neg = d->neg; bc_num_retireMul(d, ts, a->neg, b->neg); d->neg = BC_NUM_NONZERO(d) ? neg : false; err: BC_SIG_MAYLOCK; bc_num_free(&temp); BC_LONGJMP_CONT; } static void bc_num_rem(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { BcNum c1; size_t ts; ts = bc_vm_growSize(scale, b->scale); ts = BC_MAX(ts, a->scale); BC_SIG_LOCK; bc_num_init(&c1, bc_num_mulReq(a, b, ts)); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; bc_num_r(a, b, &c1, c, scale, ts); err: BC_SIG_MAYLOCK; bc_num_free(&c1); BC_LONGJMP_CONT; } static void bc_num_p(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { BcNum copy; BcBigDig pow = 0; size_t i, powrdx, resrdx; bool neg, zero; if (BC_ERR(b->rdx)) bc_vm_err(BC_ERROR_MATH_NON_INTEGER); if (BC_NUM_ZERO(b)) { bc_num_one(c); return; } if (BC_NUM_ZERO(a)) { if (b->neg) bc_vm_err(BC_ERROR_MATH_DIVIDE_BY_ZERO); bc_num_setToZero(c, scale); return; } if (BC_NUM_ONE(b)) { if (!b->neg) bc_num_copy(c, a); else bc_num_inv(a, c, scale); return; } BC_SIG_LOCK; neg = b->neg; b->neg = false; bc_num_bigdig(b, &pow); b->neg = neg; bc_num_createCopy(©, a); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; if (!neg) { size_t max = BC_MAX(scale, a->scale), scalepow = a->scale * pow; scale = BC_MIN(scalepow, max); } for (powrdx = a->scale; !(pow & 1); pow >>= 1) { powrdx <<= 1; bc_num_mul(©, ©, ©, powrdx); } bc_num_copy(c, ©); resrdx = powrdx; while (pow >>= 1) { powrdx <<= 1; bc_num_mul(©, ©, ©, powrdx); if (pow & 1) { resrdx += powrdx; bc_num_mul(c, ©, c, resrdx); } } if (neg) bc_num_inv(c, c, scale); if (c->scale > scale) bc_num_truncate(c, c->scale - scale); // We can't use bc_num_clean() here. for (zero = true, i = 0; zero && i < c->len; ++i) zero = !c->num[i]; if (zero) bc_num_setToZero(c, scale); err: BC_SIG_MAYLOCK; bc_num_free(©); BC_LONGJMP_CONT; } #if BC_ENABLE_EXTRA_MATH static void bc_num_place(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { BcBigDig val = 0; BC_UNUSED(scale); bc_num_intop(a, b, c, &val); if (val < c->scale) bc_num_truncate(c, c->scale - val); else if (val > c->scale) bc_num_extend(c, val - c->scale); } static void bc_num_left(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { BcBigDig val = 0; BC_UNUSED(scale); bc_num_intop(a, b, c, &val); bc_num_shiftLeft(c, (size_t) val); } static void bc_num_right(BcNum *a, BcNum *b, BcNum *restrict c, size_t scale) { BcBigDig val = 0; BC_UNUSED(scale); bc_num_intop(a, b, c, &val); if (BC_NUM_ZERO(c)) return; bc_num_shiftRight(c, (size_t) val); } #endif // BC_ENABLE_EXTRA_MATH static void bc_num_binary(BcNum *a, BcNum *b, BcNum *c, size_t scale, BcNumBinaryOp op, size_t req) { BcNum num2, *ptr_a, *ptr_b; bool init = false; assert(a != NULL && b != NULL && c != NULL && op != NULL); BC_SIG_LOCK; if (c == a) { ptr_a = &num2; memcpy(ptr_a, c, sizeof(BcNum)); init = true; } else ptr_a = a; if (c == b) { ptr_b = &num2; if (c != a) { memcpy(ptr_b, c, sizeof(BcNum)); init = true; } } else ptr_b = b; if (init) { bc_num_init(c, req); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; } else { BC_SIG_UNLOCK; bc_num_expand(c, req); } op(ptr_a, ptr_b, c, scale); assert(!c->neg || BC_NUM_NONZERO(c)); assert(c->rdx <= c->len || !c->len); assert(!c->len || c->num[c->len - 1] || c->rdx == c->len); err: if (init) { BC_SIG_MAYLOCK; bc_num_free(&num2); BC_LONGJMP_CONT; } } #ifndef NDEBUG static bool bc_num_strValid(const char *val) { bool radix = false; size_t i, len = strlen(val); if (!len) return true; for (i = 0; i < len; ++i) { BcDig c = val[i]; if (c == '.') { if (radix) return false; radix = true; continue; } if (!(isdigit(c) || isupper(c))) return false; } return true; } #endif // NDEBUG static BcBigDig bc_num_parseChar(char c, size_t base_t) { if (isupper(c)) { c = BC_NUM_NUM_LETTER(c); c = ((size_t) c) >= base_t ? (char) base_t - 1 : c; } else c -= '0'; return (BcBigDig) (uchar) c; } 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; for (i = 0; val[i] == '0'; ++i); 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; len = strlen(val); ptr = strchr(val, '.'); rdx = (ptr != NULL); for (i = 0; i < len && (zero = (val[i] == '0' || val[i] == '.')); ++i); - n->scale = (size_t) (rdx * ((val + len) - (ptr + 1))); + n->scale = (size_t) (rdx * (((uintptr_t) (val + len)) - + (((uintptr_t) ptr) + 1))); n->rdx = BC_NUM_RDX(n->scale); 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); bc_num_expand(n, n->len); memset(n->num, 0, BC_NUM_SIZE(n->len)); if (zero) n->len = n->rdx = 0; else { BcBigDig exp, pow; assert(i <= BC_NUM_BIGDIG_MAX); exp = (BcBigDig) i; pow = bc_num_pow10[exp]; for (i = len - 1; i < len; --i, ++exp) { char c = val[i]; if (c == '.') exp -= 1; else { size_t idx = exp / BC_BASE_DIGS; if (isupper(c)) c = '9'; n->num[idx] += (((BcBigDig) c) - '0') * pow; if ((exp + 1) % BC_BASE_DIGS == 0) pow = 1; else pow *= BC_BASE; } } } } static void bc_num_parseBase(BcNum *restrict n, const char *restrict val, BcBigDig base) { BcNum temp, mult1, mult2, result1, result2, *m1, *m2, *ptr; char c = 0; bool zero = true; BcBigDig v; size_t i, digs, len = strlen(val); 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(int_err); BC_SIG_UNLOCK; for (i = 0; i < len && (c = val[i]) && c != '.'; ++i) { v = bc_num_parseChar(c, base); bc_num_mulArray(n, base, &mult1); bc_num_bigdig2num(&temp, v); bc_num_add(&mult1, &temp, n, 0); } if (i == len && !(c = val[i])) goto int_err; assert(c == '.'); BC_SIG_LOCK; BC_UNSETJMP; 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(err); BC_SIG_UNLOCK; m1 = &mult1; m2 = &mult2; for (i += 1, digs = 0; i < len && (c = val[i]); ++i, ++digs) { v = bc_num_parseChar(c, base); bc_num_mulArray(&result1, base, &result2); bc_num_bigdig2num(&temp, v); bc_num_add(&result2, &temp, &result1, 0); bc_num_mulArray(m1, base, m2); if (m2->len < m2->rdx) m2->len = m2->rdx; 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. bc_num_div(&result1, m1, &result2, digs * 2); bc_num_truncate(&result2, digs); bc_num_add(n, &result2, n, digs); 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; } static void bc_num_printNewline(void) { if (vm.nchars >= vm.line_len - 1) { bc_vm_putchar('\\'); bc_vm_putchar('\n'); } } static void bc_num_putchar(int c) { if (c != '\n') bc_num_printNewline(); bc_vm_putchar(c); } #if DC_ENABLED static void bc_num_printChar(size_t n, size_t len, bool rdx) { BC_UNUSED(rdx); BC_UNUSED(len); assert(len == 1); bc_vm_putchar((uchar) n); } #endif // DC_ENABLED static void bc_num_printDigits(size_t n, size_t len, bool rdx) { size_t exp, pow; bc_num_putchar(rdx ? '.' : ' '); for (exp = 0, pow = 1; exp < len - 1; ++exp, pow *= BC_BASE); for (exp = 0; exp < len; pow /= BC_BASE, ++exp) { size_t dig = n / pow; n -= dig * pow; bc_num_putchar(((uchar) dig) + '0'); } } static void bc_num_printHex(size_t n, size_t len, bool rdx) { BC_UNUSED(len); assert(len == 1); if (rdx) bc_num_putchar('.'); bc_num_putchar(bc_num_hex_digits[n]); } static void bc_num_printDecimal(const BcNum *restrict n) { size_t i, j, rdx = n->rdx; bool zero = true; size_t buffer[BC_BASE_DIGS]; if (n->neg) bc_num_putchar('-'); for (i = n->len - 1; i < n->len; --i) { BcDig n9 = n->num[i]; size_t temp; bool irdx = (i == rdx - 1); zero = (zero & !irdx); temp = n->scale % BC_BASE_DIGS; temp = i || !temp ? 0 : BC_BASE_DIGS - temp; memset(buffer, 0, BC_BASE_DIGS * sizeof(size_t)); for (j = 0; n9 && j < BC_BASE_DIGS; ++j) { - buffer[j] = n9 % BC_BASE; + buffer[j] = ((size_t) n9) % BC_BASE; n9 /= BC_BASE; } for (j = BC_BASE_DIGS - 1; j < BC_BASE_DIGS && j >= temp; --j) { bool print_rdx = (irdx & (j == BC_BASE_DIGS - 1)); zero = (zero && buffer[j] == 0); if (!zero) bc_num_printHex(buffer[j], 1, print_rdx); } } } #if BC_ENABLE_EXTRA_MATH static void bc_num_printExponent(const BcNum *restrict n, bool eng) { bool neg = (n->len <= n->rdx); BcNum temp, exp; size_t places, mod; BcDig digs[BC_NUM_BIGDIG_LOG10]; BC_SIG_LOCK; bc_num_createCopy(&temp, n); BC_SETJMP_LOCKED(exit); BC_SIG_UNLOCK; if (neg) { size_t i, idx = bc_num_nonzeroLen(n) - 1; places = 1; for (i = BC_BASE_DIGS - 1; i < BC_BASE_DIGS; --i) { if (bc_num_pow10[i] > (BcBigDig) n->num[idx]) places += 1; else break; } places += (n->rdx - (idx + 1)) * BC_BASE_DIGS; mod = places % 3; if (eng && mod != 0) places += 3 - mod; bc_num_shiftLeft(&temp, places); } else { places = bc_num_intDigits(n) - 1; mod = places % 3; if (eng && mod != 0) places -= 3 - (3 - mod); bc_num_shiftRight(&temp, places); } bc_num_printDecimal(&temp); bc_num_putchar('e'); if (!places) { bc_num_printHex(0, 1, false); goto exit; } if (neg) bc_num_putchar('-'); bc_num_setup(&exp, digs, BC_NUM_BIGDIG_LOG10); bc_num_bigdig2num(&exp, (BcBigDig) places); bc_num_printDecimal(&exp); exit: BC_SIG_MAYLOCK; bc_num_free(&temp); BC_LONGJMP_CONT; } #endif // BC_ENABLE_EXTRA_MATH 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; if (len < 2) return; for (i = len - 1; i > 0; --i) { acc = ((BcBigDig) a[i]) * rem + ((BcBigDig) a[i - 1]); a[i - 1] = (BcDig) (acc % pow); acc /= pow; acc += (BcBigDig) a[i]; if (acc >= BC_BASE_POW) { if (i == len - 1) { len = bc_vm_growSize(len, 1); bc_num_expand(n, bc_vm_growSize(len, idx)); a = n->num + idx; a[len - 1] = 0; } a[i + 1] += acc / BC_BASE_POW; acc %= BC_BASE_POW; } assert(acc < BC_BASE_POW); a[i] = (BcDig) acc; } n->len = len + idx; } static void bc_num_printPrepare(BcNum *restrict n, BcBigDig rem, BcBigDig pow) { size_t i; for (i = 0; i < n->len; ++i) bc_num_printFixup(n, rem, pow, i); for (i = 0; i < n->len; ++i) { assert(pow == ((BcBigDig) ((BcDig) pow))); if (n->num[i] >= (BcDig) pow) { if (i + 1 == n->len) { n->len = bc_vm_growSize(n->len, 1); bc_num_expand(n, n->len); n->num[i + 1] = 0; } assert(pow < BC_BASE_POW); 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) { BcVec stack; BcNum intp, fracp1, fracp2, digit, flen1, flen2, *n1, *n2, *temp; BcBigDig dig = 0, *ptr, acc, exp; size_t i, j; bool radix; BcDig digit_digs[BC_NUM_BIGDIG_LOG10 + 1]; assert(base > 1); if (BC_NUM_ZERO(n)) { print(0, len, false); 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 digit (after intp has // been converted to an integer) and the next to least significant digit, // and it converts the least significant digit into one of the specified // base, putting any overflow into the next to least significant digit. It // iterates through the whole number, from least significant to most // significant, doing this conversion. At the end of that iteration, the // least significant digit is converted, but the others are not, so it // iterates again, starting at the next to least significant digit. It keeps // doing that conversion, skipping one more digit than the last time, until // all digits 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 digits 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. BC_SIG_LOCK; bc_vec_init(&stack, sizeof(BcBigDig), NULL); bc_num_init(&fracp1, n->rdx); bc_num_createCopy(&intp, n); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; bc_num_truncate(&intp, intp.scale); bc_num_sub(n, &intp, &fracp1, 0); if (base != vm.last_base) { vm.last_pow = 1; vm.last_exp = 0; while (vm.last_pow * base <= BC_BASE_POW) { vm.last_pow *= base; vm.last_exp += 1; } vm.last_rem = BC_BASE_POW - vm.last_pow; vm.last_base = base; } exp = vm.last_exp; if (vm.last_rem != 0) bc_num_printPrepare(&intp, vm.last_rem, vm.last_pow); for (i = 0; i < intp.len; ++i) { acc = (BcBigDig) intp.num[i]; for (j = 0; j < exp && (i < intp.len - 1 || acc != 0); ++j) { if (j != exp - 1) { dig = acc % base; acc /= base; } else { dig = acc; acc = 0; } assert(dig < base); bc_vec_push(&stack, &dig); } assert(acc == 0); } for (i = 0; i < stack.len; ++i) { ptr = bc_vec_item_rev(&stack, i); assert(ptr != NULL); print(*ptr, len, false); } if (!n->scale) goto err; BC_SIG_LOCK; BC_UNSETJMP; bc_num_init(&fracp2, n->rdx); 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(frac_err); BC_SIG_UNLOCK; bc_num_one(&flen1); radix = true; n1 = &flen1; n2 = &flen2; fracp2.scale = n->scale; fracp2.rdx = BC_NUM_RDX(fracp2.scale); while (bc_num_intDigits(n1) < n->scale + 1) { bc_num_expand(&fracp2, fracp1.len + 1); bc_num_mulArray(&fracp1, base, &fracp2); if (fracp2.len < fracp2.rdx) fracp2.len = fracp2.rdx; // fracp is guaranteed to be non-negative and small enough. bc_num_bigdig2(&fracp2, &dig); bc_num_bigdig2num(&digit, dig); bc_num_sub(&fracp2, &digit, &fracp1, 0); print(dig, len, radix); bc_num_mulArray(n1, base, n2); radix = false; 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; } static void bc_num_printBase(BcNum *restrict n, BcBigDig base) { size_t width; BcNumDigitOp print; bool neg = n->neg; if (neg) bc_num_putchar('-'); n->neg = false; 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; } bc_num_printNum(n, base, width, print); n->neg = neg; } #if DC_ENABLED void bc_num_stream(BcNum *restrict n, BcBigDig base) { bc_num_printNum(n, base, 1, bc_num_printChar); } #endif // DC_ENABLED 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); req = req >= BC_NUM_DEF_SIZE ? req : BC_NUM_DEF_SIZE; if (req == BC_NUM_DEF_SIZE && vm.temps.len) { BcNum *nptr = bc_vec_top(&vm.temps); num = nptr->num; bc_vec_pop(&vm.temps); } else num = bc_vm_malloc(BC_NUM_SIZE(req)); 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_vec_push(&vm.temps, n); 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; d->neg = s->neg; d->rdx = s->rdx; d->scale = s->scale; 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 *n, BcBigDig val) { BC_SIG_ASSERT_LOCKED; bc_num_init(n, (BC_NUM_BIGDIG_LOG10 - 1) / BC_BASE_DIGS + 1); 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; if (BC_NUM_ZERO(n)) return 0; if (n->rdx == len) { size_t zero, scale; len = bc_num_nonzeroLen(n); scale = n->scale % BC_BASE_DIGS; scale = scale ? scale : BC_BASE_DIGS; zero = bc_num_zeroDigits(n->num + len - 1); len = len * BC_BASE_DIGS - zero - (BC_BASE_DIGS - scale); } else len = bc_num_intDigits(n) + n->scale; return len; } void bc_num_parse(BcNum *restrict n, const char *restrict val, BcBigDig base, bool letter) { assert(n != NULL && val != NULL && base); assert(base >= BC_NUM_MIN_BASE && base <= vm.maxes[BC_PROG_GLOBALS_IBASE]); assert(bc_num_strValid(val)); if (letter) { 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); } void bc_num_print(BcNum *restrict n, BcBigDig base, bool newline) { assert(n != NULL); assert(BC_ENABLE_EXTRA_MATH || base >= BC_NUM_MIN_BASE); bc_num_printNewline(); if (BC_NUM_ZERO(n)) bc_num_printHex(0, 1, false); else if (base == BC_BASE) bc_num_printDecimal(n); #if BC_ENABLE_EXTRA_MATH else if (base == 0 || base == 1) bc_num_printExponent(n, base != 0); #endif // BC_ENABLE_EXTRA_MATH else bc_num_printBase(n, base); if (newline) bc_num_putchar('\n'); } void bc_num_bigdig2(const BcNum *restrict n, BcBigDig *result) { // This function returns no errors because it's guaranteed to succeed if // its preconditions are met. Those preconditions include both parameters // being 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. We also don't care about signals because // this function should execute in only a few iterations, meaning that // ignoring signals here should be fine. BcBigDig r = 0; assert(n != NULL && result != NULL); assert(!n->neg); assert(bc_num_cmp(n, &vm.max) < 0); assert(n->len - n->rdx <= 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 - n->rdx) { case 3: r = (BcBigDig) n->num[n->rdx + 2]; // Fallthrough. case 2: r = r * BC_BASE_POW + (BcBigDig) n->num[n->rdx + 1]; // Fallthrough. case 1: r = r * BC_BASE_POW + (BcBigDig) n->num[n->rdx]; } *result = r; } void bc_num_bigdig(const BcNum *restrict n, BcBigDig *result) { assert(n != NULL && result != NULL); if (BC_ERR(n->neg)) bc_vm_err(BC_ERROR_MATH_NEGATIVE); if (BC_ERR(bc_num_cmp(n, &vm.max) >= 0)) bc_vm_err(BC_ERROR_MATH_OVERFLOW); bc_num_bigdig2(n, result); } void bc_num_bigdig2num(BcNum *restrict n, BcBigDig val) { BcDig *ptr; size_t i; assert(n != NULL); bc_num_zero(n); if (!val) return; bc_num_expand(n, BC_NUM_BIGDIG_LOG10); 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 && BC_ENABLE_RAND void bc_num_rng(const BcNum *restrict n, BcRNG *rng) { BcNum pow, temp, temp2, intn, frac; BcRand state1, state2, inc1, inc2; BcDig pow_num[BC_RAND_NUM_SIZE]; bc_num_setup(&pow, pow_num, sizeof(pow_num) / sizeof(BcDig)); BC_SIG_LOCK; bc_num_init(&temp, n->len); bc_num_init(&temp2, n->len); bc_num_init(&frac, n->rdx); bc_num_init(&intn, bc_num_int(n)); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; bc_num_mul(&vm.max, &vm.max, &pow, 0); memcpy(frac.num, n->num, BC_NUM_SIZE(n->rdx)); frac.len = n->rdx; frac.rdx = n->rdx; frac.scale = n->scale; bc_num_mul(&frac, &pow, &temp, 0); bc_num_truncate(&temp, temp.scale); bc_num_copy(&frac, &temp); memcpy(intn.num, n->num + n->rdx, 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 // the use of BC_ERROR_SIGNAL_ONLY() on each of the divmod's and mod's // below. assert(BC_NUM_NONZERO(&vm.max)); if (BC_NUM_NONZERO(&frac)) { 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. bc_num_bigdig2(&temp2, (BcBigDig*) &state1); bc_num_bigdig2(&temp, (BcBigDig*) &state2); } else state1 = state2 = 0; if (BC_NUM_NONZERO(&intn)) { 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(). bc_num_bigdig2(&temp2, (BcBigDig*) &inc1); 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. bc_num_bigdig2(&temp, (BcBigDig*) &inc2); } 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; } void bc_num_createFromRNG(BcNum *restrict n, BcRNG *rng) { BcRand s1, s2, i1, i2; BcNum pow, conv, temp1, temp2, temp3; BcDig pow_num[BC_RAND_NUM_SIZE]; BcDig temp1_num[BC_RAND_NUM_SIZE], temp2_num[BC_RAND_NUM_SIZE]; BcDig conv_num[BC_NUM_BIGDIG_LOG10]; BC_SIG_LOCK; bc_num_init(&temp3, 2 * BC_RAND_NUM_SIZE); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; bc_num_setup(&pow, pow_num, sizeof(pow_num) / sizeof(BcDig)); 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 pow is not zero. assert(BC_NUM_NONZERO(&vm.max)); bc_num_mul(&vm.max, &vm.max, &pow, 0); // Because this is true, we can just use BC_ERROR_SIGNAL_ONLY() below when // dividing by pow. assert(BC_NUM_NONZERO(&pow)); bc_rand_getRands(rng, &s1, &s2, &i1, &i2); bc_num_bigdig2num(&conv, (BcBigDig) s2); bc_num_mul(&conv, &vm.max, &temp1, 0); bc_num_bigdig2num(&conv, (BcBigDig) s1); bc_num_add(&conv, &temp1, &temp2, 0); bc_num_div(&temp2, &pow, &temp3, BC_RAND_STATE_BITS); bc_num_bigdig2num(&conv, (BcBigDig) i2); bc_num_mul(&conv, &vm.max, &temp1, 0); bc_num_bigdig2num(&conv, (BcBigDig) i1); bc_num_add(&conv, &temp1, &temp2, 0); bc_num_add(&temp2, &temp3, n, 0); err: BC_SIG_MAYLOCK; bc_num_free(&temp3); BC_LONGJMP_CONT; } void bc_num_irand(const BcNum *restrict a, BcNum *restrict b, BcRNG *restrict rng) { BcRand r; BcBigDig modl; BcNum pow, pow2, cp, cp2, mod, temp1, temp2, rand; BcNum *p1, *p2, *t1, *t2, *c1, *c2, *tmp; BcDig rand_num[BC_NUM_BIGDIG_LOG10]; bool carry; ssize_t cmp; assert(a != b); if (BC_ERR(a->neg)) bc_vm_err(BC_ERROR_MATH_NEGATIVE); if (BC_ERR(a->rdx)) bc_vm_err(BC_ERROR_MATH_NON_INTEGER); if (BC_NUM_ZERO(a) || BC_NUM_ONE(a)) return; cmp = bc_num_cmp(a, &vm.max); if (cmp <= 0) { BcRand bits = 0; if (cmp < 0) bc_num_bigdig2(a, (BcBigDig*) &bits); // This condition means that bits is a power of 2. In that case, we // can just grab a full-size int and mask out the unneeded bits. // Also, this condition says that 0 is a power of 2, which works for // us, since a value of 0 means a == rng->max. The bitmask will mask // nothing in that case as well. if (!(bits & (bits - 1))) r = bc_rand_int(rng) & (bits - 1); else r = bc_rand_bounded(rng, bits); // We made sure that r is less than vm.max, // so we can use bc_num_bigdig2() here. bc_num_bigdig2num(b, r); return; } // In the case where a is less than rng->max, we have to make sure we have // an exclusive bound. This ensures that it happens. (See below.) carry = (cmp < 0); BC_SIG_LOCK; bc_num_createCopy(&cp, a); bc_num_init(&cp2, cp.len); bc_num_init(&mod, BC_NUM_BIGDIG_LOG10); bc_num_init(&temp1, BC_NUM_DEF_SIZE); bc_num_init(&temp2, BC_NUM_DEF_SIZE); bc_num_init(&pow2, BC_NUM_DEF_SIZE); bc_num_init(&pow, BC_NUM_DEF_SIZE); bc_num_one(&pow); bc_num_setup(&rand, rand_num, sizeof(rand_num) / sizeof(BcDig)); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; p1 = &pow; p2 = &pow2; t1 = &temp1; t2 = &temp2; c1 = &cp; c2 = &cp2; // This assert is here because it has to be true. It is also here to justify // the use of BC_ERROR_SIGNAL_ONLY() on each of the divmod's and mod's // below. assert(BC_NUM_NONZERO(&vm.max)); while (BC_NUM_NONZERO(c1)) { bc_num_divmod(c1, &vm.max, c2, &mod, 0); // Because mod is the mod of vm.max, it is guaranteed to be smaller, // which means we can use bc_num_bigdig2() here. bc_num_bigdig(&mod, &modl); if (bc_num_cmp(c1, &vm.max) < 0) { // In this case, if there is no carry, then we know we can generate // an integer *equal* to modl. Thus, we add one if there is no // carry. Otherwise, we add zero, and we are still bounded properly. // Since the last portion is guaranteed to be greater than 1, we // know modl isn't 0 unless there is no carry. modl += !carry; if (modl == 1) r = 0; else if (!modl) r = bc_rand_int(rng); else r = bc_rand_bounded(rng, (BcRand) modl); } else { if (modl) modl -= carry; r = bc_rand_int(rng); carry = (r >= (BcRand) modl); } bc_num_bigdig2num(&rand, r); bc_num_mul(&rand, p1, p2, 0); bc_num_add(p2, t1, t2, 0); if (BC_NUM_NONZERO(c2)) { bc_num_mul(&vm.max, p1, p2, 0); tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp; } else c1 = c2; tmp = t1; t1 = t2; t2 = tmp; } bc_num_copy(b, t1); bc_num_clean(b); err: BC_SIG_MAYLOCK; bc_num_free(&pow); bc_num_free(&pow2); bc_num_free(&temp2); bc_num_free(&temp1); bc_num_free(&mod); bc_num_free(&cp2); bc_num_free(&cp); BC_LONGJMP_CONT; } #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND size_t bc_num_addReq(const BcNum *a, const BcNum *b, size_t scale) { size_t aint, bint, ardx, brdx; BC_UNUSED(scale); ardx = a->rdx; aint = bc_num_int(a); assert(aint <= a->len && ardx <= a->len); brdx = b->rdx; 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; rdx = bc_vm_growSize(a->rdx, b->rdx); 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_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 - a->rdx - b->rdx; } #endif // BC_ENABLE_EXTRA_MATH void bc_num_add(BcNum *a, BcNum *b, BcNum *c, size_t scale) { 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) { 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) { 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) { bc_num_binary(a, b, c, scale, bc_num_d, bc_num_mulReq(a, b, scale)); } void bc_num_mod(BcNum *a, BcNum *b, BcNum *c, size_t scale) { bc_num_binary(a, b, c, scale, bc_num_rem, bc_num_mulReq(a, b, scale)); } void bc_num_pow(BcNum *a, BcNum *b, BcNum *c, size_t scale) { 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) { 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) { 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) { 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, *x0, *x1, *temp; size_t pow, len, rdx, req, digs, digs1, digs2, resscale; BcDig half_digs[1]; assert(a != NULL && b != NULL && a != b); if (BC_ERR(a->neg)) bc_vm_err(BC_ERROR_MATH_NEGATIVE); if (a->scale > scale) scale = a->scale; len = bc_vm_growSize(bc_num_intDigits(a), 1); rdx = BC_NUM_RDX(scale); req = bc_vm_growSize(BC_MAX(rdx, a->rdx), len >> 1); BC_SIG_LOCK; bc_num_init(b, bc_vm_growSize(req, 1)); BC_SIG_UNLOCK; if (BC_NUM_ZERO(a)) { bc_num_setToZero(b, scale); return; } if (BC_NUM_ONE(a)) { bc_num_one(b); bc_num_extend(b, scale); return; } rdx = BC_NUM_RDX(scale); rdx = BC_MAX(rdx, a->rdx); 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)); bc_num_one(&half); half.num[0] = BC_BASE_POW / 2; half.len = 1; half.rdx = 1; half.scale = 1; bc_num_init(&f, len); bc_num_init(&fprime, len); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; x0 = &num1; x1 = &num2; bc_num_one(x0); pow = bc_num_intDigits(a); if (pow) { if (pow & 1) x0->num[0] = 2; else x0->num[0] = 6; pow -= 2 - (pow & 1); bc_num_shiftLeft(x0, pow / 2); } x0->scale = x0->rdx = digs = digs1 = digs2 = 0; resscale = (scale + BC_BASE_DIGS) + 2; while (bc_num_cmp(x1, x0)) { assert(BC_NUM_NONZERO(x0)); bc_num_div(a, x0, &f, resscale); bc_num_add(x0, &f, &fprime, resscale); bc_num_mul(&fprime, &half, x1, resscale); temp = x0; x0 = x1; x1 = temp; } bc_num_copy(b, x0); if (b->scale > scale) bc_num_truncate(b, b->scale - scale); assert(!b->neg || BC_NUM_NONZERO(b)); assert(b->rdx <= b->len || !b->len); assert(!b->len || b->num[b->len - 1] || b->rdx == 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; } void bc_num_divmod(BcNum *a, BcNum *b, BcNum *c, BcNum *d, size_t scale) { BcNum num2, *ptr_a; bool init = false; size_t ts, len; 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); if (c == a) { memcpy(&num2, c, sizeof(BcNum)); ptr_a = &num2; BC_SIG_LOCK; bc_num_init(c, len); init = true; BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; } else { ptr_a = a; bc_num_expand(c, len); } if (BC_NUM_NONZERO(a) && !a->rdx && !b->rdx && 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); } else bc_num_r(ptr_a, b, c, d, scale, ts); assert(!c->neg || BC_NUM_NONZERO(c)); assert(c->rdx <= c->len || !c->len); assert(!c->len || c->num[c->len - 1] || c->rdx == c->len); assert(!d->neg || BC_NUM_NONZERO(d)); assert(d->rdx <= d->len || !d->len); assert(!d->len || d->num[d->len - 1] || d->rdx == d->len); err: if (init) { BC_SIG_MAYLOCK; bc_num_free(&num2); BC_LONGJMP_CONT; } } #if DC_ENABLED void bc_num_modexp(BcNum *a, BcNum *b, BcNum *c, BcNum *restrict d) { BcNum base, exp, two, temp; BcDig two_digs[2]; assert(a != NULL && b != NULL && c != NULL && d != NULL); assert(a != d && b != d && c != d); if (BC_ERR(BC_NUM_ZERO(c))) bc_vm_err(BC_ERROR_MATH_DIVIDE_BY_ZERO); if (BC_ERR(b->neg)) bc_vm_err(BC_ERROR_MATH_NEGATIVE); if (BC_ERR(a->rdx || b->rdx || c->rdx)) bc_vm_err(BC_ERROR_MATH_NON_INTEGER); bc_num_expand(d, c->len); BC_SIG_LOCK; bc_num_init(&base, c->len); bc_num_setup(&two, two_digs, sizeof(two_digs) / sizeof(BcDig)); bc_num_init(&temp, b->len + 1); bc_num_createCopy(&exp, b); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; bc_num_one(&two); two.num[0] = 2; bc_num_one(d); // We already checked for 0. bc_num_rem(a, c, &base, 0); 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) && !temp.neg) { bc_num_mul(d, &base, &temp, 0); // We already checked for 0. bc_num_rem(&temp, c, d, 0); } bc_num_mul(&base, &base, &temp, 0); // We already checked for 0. bc_num_rem(&temp, c, &base, 0); } err: BC_SIG_MAYLOCK; bc_num_free(&exp); bc_num_free(&temp); bc_num_free(&base); BC_LONGJMP_CONT; assert(!d->neg || d->len); assert(!d->len || d->num[d->len - 1] || d->rdx == d->len); } #endif // DC_ENABLED #if BC_DEBUG_CODE void bc_num_printDebug(const BcNum *n, const char *name, bool emptyline) { bc_file_puts(&vm.fout, name); bc_file_puts(&vm.fout, ": "); bc_num_printDecimal(n); bc_file_putchar(&vm.fout, '\n'); if (emptyline) bc_file_putchar(&vm.fout, '\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, '\n'); if (emptyline) bc_file_putchar(&vm.fout, '\n'); vm.nchars = 0; } void bc_num_printWithDigs(const BcNum *n, const char *name, bool emptyline) { bc_file_puts(&vm.fout, name); bc_file_printf(&vm.fout, " len: %zu, rdx: %zu, scale: %zu\n", name, n->len, n->rdx, 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 ? (n->neg ? "-" : "+") : "0 "); for (i = n->len - 1; i < n->len; --i) { if (i + 1 == n->rdx) bc_file_puts(&vm.ferr, ". "); if (scale / BC_BASE_DIGS != n->rdx - 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, n->rdx, n->cap, (unsigned long) (void*) n->num); } #endif // BC_DEBUG_CODE Index: head/contrib/bc/src/program.c =================================================================== --- head/contrib/bc/src/program.c (revision 366317) +++ head/contrib/bc/src/program.c (revision 366318) @@ -1,2323 +1,2323 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2020 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 static void bc_program_addFunc(BcProgram *p, BcFunc *f, BcId *id_ptr); static inline void bc_program_setVecs(BcProgram *p, BcFunc *f) { p->consts = &f->consts; if (BC_IS_BC) p->strs = &f->strs; } static inline void bc_program_type_num(BcResult *r, BcNum *n) { #if BC_ENABLED assert(r->t != BC_RESULT_VOID); #endif // BC_ENABLED if (BC_ERR(!BC_PROG_NUM(r, n))) bc_vm_err(BC_ERROR_EXEC_TYPE); } #if BC_ENABLED static void bc_program_type_match(BcResult *r, BcType t) { #if DC_ENABLED assert(BC_IS_DC || BC_NO_ERR(r->t != BC_RESULT_STR)); #endif // DC_ENABLED if (BC_ERR((r->t != BC_RESULT_ARRAY) != (!t))) bc_vm_err(BC_ERROR_EXEC_TYPE); } #endif // BC_ENABLED 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; } #if BC_ENABLED 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_ENABLE_RAND bc_rand_push(&p->rng); #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND } static void bc_program_popGlobals(BcProgram *p, bool reset) { size_t i; 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_ENABLE_RAND bc_rand_pop(&p->rng, reset); #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND } #endif // BC_ENABLED 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; } #if BC_ENABLED static BcVec* bc_program_dereference(const BcProgram *p, BcVec *vec) { BcVec *v; size_t vidx, nidx, i = 0; assert(vec->size == sizeof(uchar)); 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); assert(v->size != sizeof(uchar)); return v; } #endif // BC_ENABLED size_t bc_program_search(BcProgram *p, const char *id, bool var) { BcVec *v, *map; size_t i; BcResultData data; v = var ? &p->vars : &p->arrs; map = var ? &p->var_map : &p->arr_map; BC_SIG_LOCK; if (bc_map_insert(map, id, v->len, &i)) { bc_array_init(&data.v, var); bc_vec_push(v, &data.v); } BC_SIG_UNLOCK; return ((BcId*) bc_vec_item(map, i))->idx; } 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); } static BcNum* bc_program_num(BcProgram *p, BcResult *r) { - BcNum *n = NULL; + BcNum *n; 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: #if BC_ENABLED case BC_RESULT_ARRAY: #endif // BC_ENABLED case BC_RESULT_ARRAY_ELEM: { BcVec *v; BcType type = (r->t == BC_RESULT_VAR) ? BC_TYPE_VAR : BC_TYPE_ARRAY; v = bc_program_vec(p, r->d.loc.loc, type); if (r->t == BC_RESULT_ARRAY_ELEM) { size_t idx = r->d.loc.idx; v = bc_vec_top(v); #if BC_ENABLED if (v->size == sizeof(uchar)) v = bc_program_dereference(p, v); #endif // BC_ENABLED assert(v->size == sizeof(BcNum)); 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); } else n = bc_vec_top(v); break; } case BC_RESULT_ZERO: { n = &p->zero; break; } case BC_RESULT_ONE: { n = &p->one; break; } #if BC_ENABLED case BC_RESULT_VOID: #ifndef NDEBUG { abort(); } #endif // NDEBUG // Fallthrough case BC_RESULT_LAST: { n = &p->last; break; } #endif // BC_ENABLED } return n; } 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_vm_err(BC_ERROR_EXEC_VOID_VAL); #endif // BC_ENABLED *n = bc_program_num(p, *r); } 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 if (BC_IS_DC) { if (BC_ERR(!BC_PROG_STACK(&p->results, idx + 2))) bc_vm_err(BC_ERROR_EXEC_STACK); } #endif // BC_PROG_NO_STACK_CHECK assert(BC_PROG_STACK(&p->results, idx + 2)); bc_program_operand(p, l, ln, idx + 1); bc_program_operand(p, r, rn, idx); lt = (*l)->t; #if BC_ENABLED 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. 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_vm_err(BC_ERROR_EXEC_TYPE); } 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); } static void bc_program_assignPrep(BcProgram *p, BcResult **l, BcNum **ln, BcResult **r, BcNum **rn) { BcResultType lt, min; min = BC_RESULT_TEMP - ((unsigned int) (BC_IS_BC)); bc_program_binPrep(p, l, ln, r, rn, 0); lt = (*l)->t; if (BC_ERR(lt >= min && lt <= BC_RESULT_ONE)) bc_vm_err(BC_ERROR_EXEC_TYPE); #if DC_ENABLED if(BC_IS_DC) { bool good = (((*r)->t == BC_RESULT_STR || BC_PROG_STR(*rn)) && lt <= BC_RESULT_ARRAY_ELEM); if (!good) bc_program_type_num(*r, *rn); } #else assert((*r)->t != BC_RESULT_STR); #endif // DC_ENABLED } 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 if (BC_IS_DC) { if (BC_ERR(!BC_PROG_STACK(&p->results, idx + 1))) bc_vm_err(BC_ERROR_EXEC_STACK); } #endif // BC_PROG_NO_STACK_CHECK assert(BC_PROG_STACK(&p->results, idx + 1)); bc_program_operand(p, r, n, idx); #if DC_ENABLED assert((*r)->t != BC_RESULT_VAR || !BC_PROG_STR(*n)); #endif // DC_ENABLED bc_program_type_num(*r, *n); } static BcResult* bc_program_prepResult(BcProgram *p) { BcResult res; bc_result_clear(&res); bc_vec_push(&p->results, &res); return bc_vec_top(&p->results); } static void bc_program_const(BcProgram *p, const char *code, size_t *bgn) { BcResult *r = bc_program_prepResult(p); BcConst *c = bc_vec_item(p->consts, bc_program_index(code, bgn)); BcBigDig base = BC_PROG_IBASE(p); if (c->base != base) { if (c->num.num == NULL) { BC_SIG_LOCK; bc_num_init(&c->num, BC_NUM_RDX(strlen(c->val))); BC_SIG_UNLOCK; } // bc_num_parse() should only do operations that cannot fail. bc_num_parse(&c->num, c->val, base, !c->val[1]); c->base = base; } BC_SIG_LOCK; bc_num_createCopy(&r->d.n, &c->num); BC_SIG_UNLOCK; } static void bc_program_op(BcProgram *p, uchar inst) { BcResult *opd1, *opd2, *res; BcNum *n1, *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; bc_num_init(&res->d.n, bc_program_opReqs[idx](n1, n2, BC_PROG_SCALE(p))); BC_SIG_UNLOCK; bc_program_ops[idx](n1, n2, &res->d.n, BC_PROG_SCALE(p)); bc_program_retire(p, 1, 2); } static void bc_program_read(BcProgram *p) { BcStatus s; BcParse parse; BcVec buf; BcInstPtr ip; size_t i; const char* file; BcFunc *f = bc_vec_item(&p->fns, BC_PROG_READ); 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_vm_err(BC_ERROR_EXEC_REC_READ); } BC_SIG_LOCK; file = vm.file; bc_parse_init(&parse, p, BC_PROG_READ); bc_vec_init(&buf, sizeof(char), NULL); BC_SETJMP_LOCKED(exec_err); BC_SIG_UNLOCK; bc_lex_file(&parse.l, bc_program_stdin_name); bc_vec_npop(&f->code, f->code.len); s = bc_read_line(&buf, BC_IS_BC ? "read> " : "?> "); if (s == BC_STATUS_EOF) bc_vm_err(BC_ERROR_EXEC_READ_EXPR); bc_parse_text(&parse, buf.v); vm.expr(&parse, BC_PARSE_NOREAD | BC_PARSE_NEEDVAL); if (BC_ERR(parse.l.t != BC_LEX_NLINE && parse.l.t != BC_LEX_EOF)) bc_vm_err(BC_ERROR_EXEC_READ_EXPR); #if BC_ENABLED if (BC_G) bc_program_prepGlobals(p); #endif // BC_ENABLED 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); bc_vec_pushByte(&f->code, vm.read_ret); bc_vec_push(&p->stack, &ip); #if DC_ENABLED if (BC_IS_DC) { size_t temp = 0; bc_vec_push(&p->tail_calls, &temp); } #endif // DC_ENABLED exec_err: BC_SIG_MAYLOCK; bc_parse_free(&parse); bc_vec_free(&buf); vm.file = file; BC_LONGJMP_CONT; } #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND static void bc_program_rand(BcProgram *p) { BcRand rand = bc_rand_int(&p->rng); bc_program_pushBigdig(p, (BcBigDig) rand, BC_RESULT_TEMP); } #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND static void bc_program_printChars(const char *str) { const char *nl; size_t len = vm.nchars + strlen(str); bc_file_puts(&vm.fout, str); nl = strrchr(str, '\n'); if (nl != NULL) len = strlen(nl + 1); vm.nchars = len > UINT16_MAX ? UINT16_MAX : (uint16_t) len; } static void bc_program_printString(const char *restrict str) { size_t i, len = strlen(str); #if DC_ENABLED if (!len && BC_IS_DC) { bc_vm_putchar('\0'); return; } #endif // DC_ENABLED for (i = 0; i < len; ++i) { int c = str[i]; if (c == '\\' && i != len - 1) { const char *ptr; c = str[++i]; ptr = strchr(bc_program_esc_chars, c); if (ptr != NULL) { if (c == 'n') vm.nchars = UINT16_MAX; c = bc_program_esc_seqs[(size_t) (ptr - bc_program_esc_chars)]; } else { // Just print the backslash. The following // character will be printed later. bc_vm_putchar('\\'); } } bc_vm_putchar(c); } } 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_vm_err(BC_ERROR_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 (r->t == BC_RESULT_VOID) { if (BC_ERR(pop)) bc_vm_err(BC_ERROR_EXEC_VOID_VAL); bc_vec_pop(&p->results); return; } #endif // BC_ENABLED n = bc_program_num(p, r); if (BC_PROG_NUM(r, n)) { assert(inst != BC_INST_PRINT_STR); bc_num_print(n, BC_PROG_OBASE(p), !pop); #if BC_ENABLED if (BC_IS_BC) bc_num_copy(&p->last, n); #endif // BC_ENABLED } else { size_t i = (r->t == BC_RESULT_STR) ? r->d.loc.loc : n->scale; bc_file_flush(&vm.fout); str = *((char**) bc_vec_item(p->strs, i)); if (inst == BC_INST_PRINT_STR) bc_program_printChars(str); else { bc_program_printString(str); if (inst == BC_INST_PRINT) bc_vm_putchar('\n'); } } if (BC_IS_BC || 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)) r->d.n.neg = !r->d.n.neg; } 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 static void bc_program_unary(BcProgram *p, uchar inst) { BcResult *res, *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; bc_program_unarys[inst - BC_INST_NEG](res, num); bc_program_retire(p, 1, 1); } static void bc_program_logical(BcProgram *p, uchar inst) { BcResult *opd1, *opd2, *res; BcNum *n1, *n2; bool cond = 0; ssize_t cmp; res = bc_program_prepResult(p); bc_program_binOpPrep(p, &opd1, &n1, &opd2, &n2, 1); 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 { 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; } #ifndef NDEBUG default: { abort(); } #endif // NDEBUG } } 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); } #if DC_ENABLED static void bc_program_assignStr(BcProgram *p, BcResult *r, BcVec *v, bool push) { BcNum n2; bc_num_clear(&n2); n2.scale = r->d.loc.loc; assert(BC_PROG_STACK(&p->results, 1 + !push)); if (!push) bc_vec_pop(v); bc_vec_npop(&p->results, 1 + !push); bc_vec_push(v, &n2); } #endif // DC_ENABLED static void bc_program_copyToVar(BcProgram *p, size_t idx, BcType t, bool last) { BcResult *ptr = NULL, r; BcVec *vec; BcNum *n = NULL; bool var = (t == BC_TYPE_VAR); #if DC_ENABLED if (BC_IS_DC) { if (BC_ERR(!BC_PROG_STACK(&p->results, 1))) bc_vm_err(BC_ERROR_EXEC_STACK); assert(BC_PROG_STACK(&p->results, 1)); bc_program_operand(p, &ptr, &n, 0); } #endif #if BC_ENABLED if (BC_IS_BC) { ptr = bc_vec_top(&p->results); bc_program_type_match(ptr, t); if (last) n = bc_program_num(p, ptr); else if (var) n = bc_vec_item_rev(bc_program_vec(p, ptr->d.loc.loc, t), 1); } #endif // BC_ENABLED vec = bc_program_vec(p, idx, t); #if DC_ENABLED if (BC_IS_DC && (ptr->t == BC_RESULT_STR || BC_PROG_STR(n))) { if (BC_ERR(!var)) bc_vm_err(BC_ERROR_EXEC_TYPE); bc_program_assignStr(p, ptr, vec, true); return; } #endif // DC_ENABLED BC_SIG_LOCK; if (var) bc_num_createCopy(&r.d.n, n); else { BcVec *v = (BcVec*) n, *rv = &r.d.v; #if BC_ENABLED BcVec *parent; bool ref, ref_size; parent = bc_program_vec(p, ptr->d.loc.loc, t); assert(parent != NULL); if (!last) v = bc_vec_item_rev(parent, !last); assert(v != NULL); ref = (v->size == sizeof(BcNum) && t == BC_TYPE_REF); ref_size = (v->size == sizeof(uchar)); if (ref || (ref_size && t == BC_TYPE_REF)) { bc_vec_init(rv, sizeof(uchar), NULL); if (ref) { assert(parent->len >= (size_t) (!last + 1)); // Make sure the pointer was not invalidated. vec = bc_program_vec(p, idx, t); bc_vec_pushIndex(rv, ptr->d.loc.loc); bc_vec_pushIndex(rv, parent->len - !last - 1); } // If we get here, we are copying a ref to a ref. else bc_vec_npush(rv, v->len * sizeof(uchar), v->v); // We need to return early. bc_vec_push(vec, &r.d); bc_vec_pop(&p->results); BC_SIG_UNLOCK; return; } else if (ref_size && t != BC_TYPE_REF) v = bc_program_dereference(p, v); #endif // BC_ENABLED bc_array_init(rv, true); bc_array_copy(rv, v); } bc_vec_push(vec, &r.d); bc_vec_pop(&p->results); BC_SIG_UNLOCK; } static void bc_program_assign(BcProgram *p, uchar inst) { BcResult *left, *right, res; BcNum *l, *r; bool ob, sc, use_val = BC_INST_USE_VAL(inst); bc_program_assignPrep(p, &left, &l, &right, &r); #if DC_ENABLED assert(left->t != BC_RESULT_STR); if (right->t == BC_RESULT_STR || BC_PROG_STR(r)) { size_t idx = right->t == BC_RESULT_STR ? right->d.loc.loc : r->scale; if (left->t == BC_RESULT_ARRAY_ELEM) { BC_SIG_LOCK; bc_num_free(l); bc_num_clear(l); l->scale = idx; bc_vec_npop(&p->results, 2); BC_SIG_UNLOCK; } else { BcVec *v = bc_program_vec(p, left->d.loc.loc, BC_TYPE_VAR); bc_program_assignStr(p, right, v, false); } return; } #endif // DC_ENABLED if (BC_INST_IS_ASSIGN(inst)) bc_num_copy(l, r); #if BC_ENABLED else { BcBigDig scale = BC_PROG_SCALE(p); if (!use_val) inst -= (BC_INST_ASSIGN_POWER_NO_VAL - BC_INST_ASSIGN_POWER); 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); if (ob || sc || left->t == BC_RESULT_IBASE) { BcVec *v; BcBigDig *ptr, *ptr_t, val, max, min; BcError e; bc_num_bigdig(l, &val); e = left->t - BC_RESULT_IBASE + BC_ERROR_EXEC_IBASE; if (sc) { min = 0; max = vm.maxes[BC_PROG_GLOBALS_SCALE]; v = p->globals_v + BC_PROG_GLOBALS_SCALE; ptr_t = p->globals + BC_PROG_GLOBALS_SCALE; } else { min = BC_NUM_MIN_BASE; if (BC_ENABLE_EXTRA_MATH && ob && (BC_IS_DC || !BC_IS_POSIX)) min = 0; max = vm.maxes[ob + BC_PROG_GLOBALS_IBASE]; v = p->globals_v + BC_PROG_GLOBALS_IBASE + ob; ptr_t = p->globals + BC_PROG_GLOBALS_IBASE + ob; } if (BC_ERR(val > max || val < min)) bc_vm_verr(e, min, max); ptr = bc_vec_top(v); *ptr = val; *ptr_t = val; } #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND else if (left->t == BC_RESULT_SEED) bc_num_rng(l, &p->rng); #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND BC_SIG_LOCK; 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; } 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); r.t = BC_RESULT_VAR; r.d.loc.loc = idx; #if DC_ENABLED if (BC_IS_DC && (pop || copy)) { BcVec *v = bc_program_vec(p, idx, BC_TYPE_VAR); BcNum *num = bc_vec_top(v); if (BC_ERR(!BC_PROG_STACK(v, 2 - copy))) bc_vm_err(BC_ERROR_EXEC_STACK); assert(BC_PROG_STACK(v, 2 - copy)); if (!BC_PROG_STR(num)) { BC_SIG_LOCK; r.t = BC_RESULT_TEMP; bc_num_createCopy(&r.d.n, num); if (!copy) bc_vec_pop(v); bc_vec_push(&p->results, &r); BC_SIG_UNLOCK; return; } else { r.d.loc.loc = num->scale; r.t = BC_RESULT_STR; } if (!copy) bc_vec_pop(v); } #endif // DC_ENABLED bc_vec_push(&p->results, &r); } static void bc_program_pushArray(BcProgram *p, const char *restrict code, size_t *restrict bgn, uchar inst) { BcResult r, *operand; BcNum *num; BcBigDig temp; r.d.loc.loc = bc_program_index(code, bgn); #if BC_ENABLED if (inst == BC_INST_ARRAY) { r.t = BC_RESULT_ARRAY; bc_vec_push(&p->results, &r); return; } #endif // BC_ENABLED bc_program_prep(p, &operand, &num, 0); bc_num_bigdig(num, &temp); r.t = BC_RESULT_ARRAY_ELEM; r.d.loc.idx = (size_t) temp; BC_SIG_LOCK; bc_vec_pop(&p->results); bc_vec_push(&p->results, &r); BC_SIG_UNLOCK; } #if BC_ENABLED 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; copy.t = BC_RESULT_TEMP; bc_num_createCopy(©.d.n, num); BC_SETJMP_LOCKED(exit); BC_SIG_UNLOCK; res.t = BC_RESULT_ONE; inst2 = BC_INST_ASSIGN_PLUS + (inst & 0x01); bc_vec_push(&p->results, &res); bc_program_assign(p, inst2); BC_SIG_LOCK; bc_vec_pop(&p->results); bc_vec_push(&p->results, ©); BC_UNSETJMP; BC_SIG_UNLOCK; return; exit: BC_SIG_MAYLOCK; bc_num_free(©.d.n); BC_LONGJMP_CONT; } static void bc_program_call(BcProgram *p, const char *restrict code, size_t *restrict idx) { BcInstPtr ip; size_t i, nparams = bc_program_index(code, idx); BcFunc *f; BcVec *v; BcLoc *a; BcResultData param; BcResult *arg; ip.idx = 0; ip.func = bc_program_index(code, idx); f = bc_vec_item(&p->fns, ip.func); if (BC_ERR(!f->code.len)) bc_vm_verr(BC_ERROR_EXEC_UNDEF_FUNC, f->name); if (BC_ERR(nparams != f->nparams)) bc_vm_verr(BC_ERROR_EXEC_PARAMS, f->nparams, nparams); ip.len = p->results.len - nparams; assert(BC_PROG_STACK(&p->results, nparams)); if (BC_G) bc_program_prepGlobals(p); for (i = 0; i < nparams; ++i) { size_t j; bool last = true; arg = bc_vec_top(&p->results); if (BC_ERR(arg->t == BC_RESULT_VOID)) bc_vm_err(BC_ERROR_EXEC_VOID_VAL); a = bc_vec_item(&f->autos, nparams - 1 - i); // If I have already pushed to a var, I need to make sure I // get the previous version, not the already pushed one. if (arg->t == BC_RESULT_VAR || arg->t == BC_RESULT_ARRAY) { for (j = 0; j < i && last; ++j) { BcLoc *loc = bc_vec_item(&f->autos, nparams - 1 - j); last = (arg->d.loc.loc != loc->loc || (!loc->idx) != (arg->t == BC_RESULT_VAR)); } } bc_program_copyToVar(p, a->loc, (BcType) a->idx, last); } BC_SIG_LOCK; for (; i < f->autos.len; ++i) { a = bc_vec_item(&f->autos, i); v = bc_program_vec(p, a->loc, (BcType) a->idx); if (a->idx == BC_TYPE_VAR) { bc_num_init(¶m.n, BC_NUM_DEF_SIZE); bc_vec_push(v, ¶m.n); } else { assert(a->idx == BC_TYPE_ARRAY); bc_array_init(¶m.v, true); bc_vec_push(v, ¶m.v); } } bc_vec_push(&p->stack, &ip); BC_SIG_UNLOCK; } static void bc_program_return(BcProgram *p, uchar inst) { BcResult *res; BcFunc *f; BcInstPtr *ip = bc_vec_top(&p->stack); size_t i, nops = p->results.len - ip->len; assert(BC_PROG_STACK(&p->stack, 2)); assert(BC_PROG_STACK(&p->results, ip->len + (inst == BC_INST_RET))); f = bc_vec_item(&p->fns, ip->func); res = bc_program_prepResult(p); if (inst == BC_INST_RET) { BcNum *num; BcResult *operand; bc_program_operand(p, &operand, &num, 1); BC_SIG_LOCK; bc_num_createCopy(&res->d.n, num); } else if (inst == BC_INST_RET_VOID) res->t = BC_RESULT_VOID; else { BC_SIG_LOCK; bc_num_init(&res->d.n, BC_NUM_DEF_SIZE); } BC_SIG_MAYUNLOCK; // We need to pop arguments as well, so this takes that into account. for (i = 0; i < f->autos.len; ++i) { BcLoc *a = bc_vec_item(&f->autos, i); BcVec *v = bc_program_vec(p, a->loc, (BcType) a->idx); bc_vec_pop(v); } bc_program_retire(p, 1, nops); if (BC_G) bc_program_popGlobals(p, false); bc_vec_pop(&p->stack); } #endif // BC_ENABLED static void bc_program_builtin(BcProgram *p, uchar inst) { BcResult *opd, *res; BcNum *num; bool len = (inst == BC_INST_LENGTH); #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND assert(inst >= BC_INST_LENGTH && inst <= BC_INST_IRAND); #else // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND assert(inst >= BC_INST_LENGTH && inst <= BC_INST_ABS); #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND #ifndef BC_PROG_NO_STACK_CHECK if (BC_IS_DC) { if (BC_ERR(!BC_PROG_STACK(&p->results, 1))) bc_vm_err(BC_ERROR_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); #if DC_ENABLED if (!len && inst != BC_INST_SCALE_FUNC) bc_program_type_num(opd, num); #endif // DC_ENABLED if (inst == BC_INST_SQRT) bc_num_sqrt(num, &res->d.n, BC_PROG_SCALE(p)); else if (inst == BC_INST_ABS) { BC_SIG_LOCK; bc_num_createCopy(&res->d.n, num); BC_SIG_UNLOCK; res->d.n.neg = false; } #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND else if (inst == BC_INST_IRAND) { BC_SIG_LOCK; bc_num_init(&res->d.n, num->len - num->rdx); BC_SIG_UNLOCK; bc_num_irand(num, &res->d.n, &p->rng); } #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND else { BcBigDig val = 0; if (len) { #if BC_ENABLED if (BC_IS_BC && opd->t == BC_RESULT_ARRAY) { BcVec *v = (BcVec*) num; if (v->size == sizeof(uchar)) v = bc_program_dereference(p, v); assert(v->size == sizeof(BcNum)); val = (BcBigDig) v->len; } else #endif // BC_ENABLED { #if DC_ENABLED if (!BC_PROG_NUM(opd, num)) { size_t idx; char *str; idx = opd->t == BC_RESULT_STR ? opd->d.loc.loc : num->scale; str = *((char**) bc_vec_item(p->strs, idx)); val = (BcBigDig) strlen(str); } else #endif // DC_ENABLED { val = (BcBigDig) bc_num_len(num); } } } else if (BC_IS_BC || BC_PROG_NUM(opd, num)) val = (BcBigDig) bc_num_scale(num); BC_SIG_LOCK; bc_num_createFromBigdig(&res->d.n, val); BC_SIG_UNLOCK; } bc_program_retire(p, 1, 1); } #if DC_ENABLED static void bc_program_divmod(BcProgram *p) { BcResult *opd1, *opd2, *res, *res2; BcNum *n1, *n2; size_t req; bc_vec_expand(&p->results, p->results.len + 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); bc_program_binOpPrep(p, &opd1, &n1, &opd2, &n2, 2); req = bc_num_mulReq(n1, n2, BC_PROG_SCALE(p)); BC_SIG_LOCK; bc_num_init(&res->d.n, req); bc_num_init(&res2->d.n, req); BC_SIG_UNLOCK; bc_num_divmod(n1, n2, &res2->d.n, &res->d.n, BC_PROG_SCALE(p)); bc_program_retire(p, 2, 2); } static void bc_program_modexp(BcProgram *p) { BcResult *r1, *r2, *r3, *res; BcNum *n1, *n2, *n3; if (BC_ERR(!BC_PROG_STACK(&p->results, 3))) bc_vm_err(BC_ERROR_EXEC_STACK); assert(BC_PROG_STACK(&p->results, 3)); res = bc_program_prepResult(p); bc_program_operand(p, &r1, &n1, 3); bc_program_type_num(r1, n1); 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. 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); } static void bc_program_stackLen(BcProgram *p) { bc_program_pushBigdig(p, (BcBigDig) p->results.len, BC_RESULT_TEMP); } static uchar bc_program_asciifyNum(BcProgram *p, BcNum *n) { BcNum num; BcBigDig val = 0; bc_num_clear(&num); BC_SETJMP(num_err); BC_SIG_LOCK; bc_num_createCopy(&num, n); BC_SIG_UNLOCK; bc_num_truncate(&num, num.scale); num.neg = false; // This is guaranteed to not have a divide by 0 // because strmb is equal to UCHAR_MAX + 1. bc_num_mod(&num, &p->strmb, &num, 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. bc_num_bigdig2(&num, &val); num_err: BC_SIG_MAYLOCK; bc_num_free(&num); BC_LONGJMP_CONT; return (uchar) val; } static void bc_program_asciify(BcProgram *p) { BcResult *r, res; BcNum *n; char str[2], *str2; uchar c; size_t idx; if (BC_ERR(!BC_PROG_STACK(&p->results, 1))) bc_vm_err(BC_ERROR_EXEC_STACK); assert(BC_PROG_STACK(&p->results, 1)); bc_program_operand(p, &r, &n, 0); assert(n != NULL); assert(p->strs->len + BC_PROG_REQ_FUNCS == p->fns.len); if (BC_PROG_NUM(r, n)) c = bc_program_asciifyNum(p, n); else { size_t index = r->t == BC_RESULT_STR ? r->d.loc.loc : n->scale; str2 = *((char**) bc_vec_item(p->strs, index)); c = (uchar) str2[0]; } str[0] = (char) c; str[1] = '\0'; BC_SIG_LOCK; idx = bc_program_insertFunc(p, str) - BC_PROG_REQ_FUNCS; BC_SIG_UNLOCK; res.t = BC_RESULT_STR; res.d.loc.loc = idx; bc_vec_pop(&p->results); bc_vec_push(&p->results, &res); } static void bc_program_printStream(BcProgram *p) { BcResult *r; BcNum *n; if (BC_ERR(!BC_PROG_STACK(&p->results, 1))) bc_vm_err(BC_ERROR_EXEC_STACK); assert(BC_PROG_STACK(&p->results, 1)); bc_program_operand(p, &r, &n, 0); assert(n != NULL); if (BC_PROG_NUM(r, n)) bc_num_stream(n, p->strm); else { size_t idx = (r->t == BC_RESULT_STR) ? r->d.loc.loc : n->scale; bc_program_printChars(*((char**) bc_vec_item(p->strs, idx))); } } static void bc_program_nquit(BcProgram *p, uchar inst) { BcResult *opnd; BcNum *num; BcBigDig val; size_t i; assert(p->stack.len == p->tail_calls.len); if (inst == BC_INST_QUIT) val = 2; else { bc_program_prep(p, &opnd, &num, 0); bc_num_bigdig(num, &val); bc_vec_pop(&p->results); } for (i = 0; val && i < p->tail_calls.len; ++i) { size_t calls = *((size_t*) bc_vec_item_rev(&p->tail_calls, i)) + 1; if (calls >= val) val = 0; else val -= calls; } if (i == p->stack.len) { vm.status = BC_STATUS_QUIT; BC_VM_JMP; } else { bc_vec_npop(&p->stack, i); bc_vec_npop(&p->tail_calls, i); } } 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; BcParse prs; BcInstPtr ip; size_t fidx, sidx; BcNum *n; assert(p->stack.len == p->tail_calls.len); if (BC_ERR(!BC_PROG_STACK(&p->results, 1))) bc_vm_err(BC_ERROR_EXEC_STACK); assert(BC_PROG_STACK(&p->results, 1)); bc_program_operand(p, &r, &n, 0); if (cond) { bool exec; size_t idx, then_idx, else_idx; then_idx = bc_program_index(code, bgn); else_idx = bc_program_index(code, bgn); exec = (r->d.n.len != 0); idx = exec ? then_idx : else_idx; BC_SIG_LOCK; BC_SETJMP_LOCKED(exit); 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_vm_err(BC_ERROR_EXEC_TYPE); BC_UNSETJMP; BC_SIG_UNLOCK; sidx = n->scale; } 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) sidx = r->d.loc.loc; else return; } fidx = sidx + BC_PROG_REQ_FUNCS; str = *((char**) bc_vec_item(p->strs, sidx)); f = bc_vec_item(&p->fns, fidx); if (!f->code.len) { BC_SIG_LOCK; bc_parse_init(&prs, p, fidx); bc_lex_file(&prs.l, vm.file); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; bc_parse_text(&prs, str); vm.expr(&prs, BC_PARSE_NOCALL); BC_SIG_LOCK; BC_UNSETJMP; // We can just assert this here because // dc should parse everything until EOF. assert(prs.l.t == BC_LEX_EOF); bc_parse_free(&prs); BC_SIG_UNLOCK; } ip.idx = 0; ip.len = p->results.len; ip.func = fidx; bc_vec_pop(&p->results); // Tail call. if (p->stack.len > 1 && *bgn == len - 1 && code[*bgn] == BC_INST_POP_EXEC) { size_t *call_ptr = bc_vec_top(&p->tail_calls); *call_ptr += 1; bc_vec_pop(&p->stack); } else bc_vec_push(&p->tail_calls, &ip.idx); bc_vec_push(&p->stack, &ip); return; err: BC_SIG_MAYLOCK; bc_parse_free(&prs); f = bc_vec_item(&p->fns, fidx); bc_vec_npop(&f->code, f->code.len); exit: bc_vec_pop(&p->results); BC_LONGJMP_CONT; } 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 static void bc_program_pushGlobal(BcProgram *p, uchar inst) { BcResultType t; assert(inst >= BC_INST_IBASE && inst <= BC_INST_SCALE); t = inst - BC_INST_IBASE + BC_RESULT_IBASE; bc_program_pushBigdig(p, p->globals[inst - BC_INST_IBASE], t); } #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND static void bc_program_pushSeed(BcProgram *p) { BcResult *res; res = bc_program_prepResult(p); res->t = BC_RESULT_SEED; BC_SIG_LOCK; 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 && BC_ENABLE_RAND static void bc_program_addFunc(BcProgram *p, BcFunc *f, BcId *id_ptr) { BcInstPtr *ip; BC_SIG_ASSERT_LOCKED; bc_func_init(f, id_ptr->name); bc_vec_push(&p->fns, f); // This is to make sure pointers are updated if the array was moved. if (p->stack.len) { ip = bc_vec_top(&p->stack); bc_program_setVecs(p, (BcFunc*) bc_vec_item(&p->fns, ip->func)); } } size_t bc_program_insertFunc(BcProgram *p, const char *name) { BcId *id_ptr; BcFunc f; bool new; size_t idx; BC_SIG_ASSERT_LOCKED; assert(p != NULL && name != NULL); 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 (!new) { if (BC_IS_BC) { BcFunc *func = bc_vec_item(&p->fns, idx); bc_func_reset(func); } } else { bc_program_addFunc(p, &f, id_ptr); #if DC_ENABLED if (BC_IS_DC && idx >= BC_PROG_REQ_FUNCS) { bc_vec_push(p->strs, &id_ptr->name); assert(p->strs->len == p->fns.len - BC_PROG_REQ_FUNCS); } #endif // DC_ENABLED } return idx; } #ifndef NDEBUG void bc_program_free(BcProgram *p) { size_t i; BC_SIG_ASSERT_LOCKED; assert(p != NULL); for (i = 0; i < BC_PROG_GLOBALS_LEN; ++i) bc_vec_free(p->globals_v + i); 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); #if BC_ENABLED if (BC_IS_BC) bc_num_free(&p->last); #endif // BC_ENABLED #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND bc_rand_free(&p->rng); #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND #if DC_ENABLED if (BC_IS_DC) { bc_vec_free(&p->tail_calls); bc_vec_free(&p->strs_v); } #endif // DC_ENABLED } #endif // NDEBUG void bc_program_init(BcProgram *p) { BcInstPtr ip; size_t i; BcBigDig val = BC_BASE; BC_SIG_ASSERT_LOCKED; assert(p != NULL); memset(p, 0, sizeof(BcProgram)); memset(&ip, 0, sizeof(BcInstPtr)); for (i = 0; i < BC_PROG_GLOBALS_LEN; ++i) { bc_vec_init(p->globals_v + i, sizeof(BcBigDig), NULL); val = i == BC_PROG_GLOBALS_SCALE ? 0 : val; bc_vec_push(p->globals_v + i, &val); p->globals[i] = val; } #if DC_ENABLED if (BC_IS_DC) { bc_vec_init(&p->strs_v, sizeof(char*), bc_string_free); p->strs = &p->strs_v; bc_vec_init(&p->tail_calls, sizeof(size_t), NULL); i = 0; bc_vec_push(&p->tail_calls, &i); p->strm = UCHAR_MAX + 1; bc_num_setup(&p->strmb, p->strmb_num, BC_NUM_BIGDIG_LOG10); bc_num_bigdig2num(&p->strmb, p->strm); } #endif // DC_ENABLED #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND srand((unsigned int) time(NULL)); bc_rand_init(&p->rng); #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND bc_num_setup(&p->zero, p->zero_num, BC_PROG_ONE_CAP); bc_num_setup(&p->one, p->one_num, BC_PROG_ONE_CAP); bc_num_one(&p->one); #if BC_ENABLED if (BC_IS_BC) bc_num_init(&p->last, BC_NUM_DEF_SIZE); #endif // BC_ENABLED bc_vec_init(&p->fns, sizeof(BcFunc), bc_func_free); 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_vec_free); bc_map_init(&p->var_map); bc_vec_init(&p->arrs, sizeof(BcVec), bc_vec_free); bc_map_init(&p->arr_map); bc_vec_init(&p->results, sizeof(BcResult), bc_result_free); bc_vec_init(&p->stack, sizeof(BcInstPtr), NULL); bc_vec_push(&p->stack, &ip); bc_program_setVecs(p, (BcFunc*) bc_vec_item(&p->fns, BC_PROG_MAIN)); assert(p->consts != NULL && p->strs != NULL); } void bc_program_reset(BcProgram *p) { BcFunc *f; BcInstPtr *ip; BC_SIG_ASSERT_LOCKED; bc_vec_npop(&p->stack, p->stack.len - 1); bc_vec_npop(&p->results, p->results.len); #if BC_ENABLED if (BC_G) bc_program_popGlobals(p, true); #endif // BC_ENABLED f = bc_vec_item(&p->fns, BC_PROG_MAIN); ip = bc_vec_top(&p->stack); bc_program_setVecs(p, f); ip->idx = f->code.len; if (vm.sig) { bc_file_write(&vm.fout, bc_program_ready_msg, bc_program_ready_msg_len); bc_file_flush(&vm.fout); vm.sig = 0; } } void bc_program_exec(BcProgram *p) { size_t idx; BcResult r, *ptr; BcInstPtr *ip = bc_vec_top(&p->stack); BcFunc *func = (BcFunc*) bc_vec_item(&p->fns, ip->func); char *code = func->code.v; bool cond = false; #if BC_ENABLED BcNum *num; #endif // BC_ENABLED #ifndef NDEBUG size_t jmp_bufs_len; #endif // NDEBUG #ifndef NDEBUG jmp_bufs_len = vm.jmp_bufs.len; #endif // NDEBUG bc_program_setVecs(p, func); while (ip->idx < func->code.len) { BC_SIG_ASSERT_NOT_LOCKED; uchar inst = (uchar) code[(ip->idx)++]; switch (inst) { #if BC_ENABLED case BC_INST_JUMP_ZERO: { bc_program_prep(p, &ptr, &num, 0); cond = !bc_num_cmpZero(num); bc_vec_pop(&p->results); } // Fallthrough. case BC_INST_JUMP: { idx = bc_program_index(code, &ip->idx); if (inst == BC_INST_JUMP || cond) { size_t *addr = bc_vec_item(&func->labels, idx); assert(*addr != SIZE_MAX); ip->idx = *addr; } break; } case BC_INST_CALL: { assert(BC_IS_BC); bc_program_call(p, code, &ip->idx); ip = bc_vec_top(&p->stack); func = bc_vec_item(&p->fns, ip->func); code = func->code.v; bc_program_setVecs(p, func); break; } case BC_INST_INC: case BC_INST_DEC: { bc_program_incdec(p, inst); break; } case BC_INST_HALT: { vm.status = BC_STATUS_QUIT; BC_VM_JMP; break; } case BC_INST_RET: case BC_INST_RET0: case BC_INST_RET_VOID: { bc_program_return(p, inst); ip = bc_vec_top(&p->stack); func = bc_vec_item(&p->fns, ip->func); code = func->code.v; bc_program_setVecs(p, func); break; } #endif // BC_ENABLED case BC_INST_BOOL_OR: case BC_INST_BOOL_AND: case BC_INST_REL_EQ: case BC_INST_REL_LE: case BC_INST_REL_GE: case BC_INST_REL_NE: case BC_INST_REL_LT: case BC_INST_REL_GT: { bc_program_logical(p, inst); break; } case BC_INST_READ: { bc_program_read(p); ip = bc_vec_top(&p->stack); func = bc_vec_item(&p->fns, ip->func); code = func->code.v; bc_program_setVecs(p, func); break; } #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_INST_RAND: { bc_program_rand(p); break; } #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_INST_MAXIBASE: case BC_INST_MAXOBASE: case BC_INST_MAXSCALE: #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_INST_MAXRAND: #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND { BcBigDig dig = vm.maxes[inst - BC_INST_MAXIBASE]; bc_program_pushBigdig(p, dig, BC_RESULT_TEMP); break; } case BC_INST_VAR: { bc_program_pushVar(p, code, &ip->idx, false, false); break; } case BC_INST_ARRAY_ELEM: #if BC_ENABLED case BC_INST_ARRAY: #endif // BC_ENABLED { bc_program_pushArray(p, code, &ip->idx, inst); break; } case BC_INST_IBASE: case BC_INST_SCALE: case BC_INST_OBASE: { bc_program_pushGlobal(p, inst); break; } #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_INST_SEED: { bc_program_pushSeed(p); break; } #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_INST_LENGTH: case BC_INST_SCALE_FUNC: case BC_INST_SQRT: case BC_INST_ABS: #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND case BC_INST_IRAND: #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND { bc_program_builtin(p, inst); break; } case BC_INST_NUM: { bc_program_const(p, code, &ip->idx); break; } case BC_INST_ZERO: case BC_INST_ONE: #if BC_ENABLED case BC_INST_LAST: #endif // BC_ENABLED { r.t = BC_RESULT_ZERO + (inst - BC_INST_ZERO); bc_vec_push(&p->results, &r); break; } case BC_INST_PRINT: case BC_INST_PRINT_POP: case BC_INST_PRINT_STR: { bc_program_print(p, inst, 0); break; } case BC_INST_STR: { r.t = BC_RESULT_STR; r.d.loc.loc = bc_program_index(code, &ip->idx); bc_vec_push(&p->results, &r); break; } case BC_INST_POWER: case BC_INST_MULTIPLY: case BC_INST_DIVIDE: case BC_INST_MODULUS: case BC_INST_PLUS: case BC_INST_MINUS: #if BC_ENABLE_EXTRA_MATH case BC_INST_PLACES: case BC_INST_LSHIFT: case BC_INST_RSHIFT: #endif // BC_ENABLE_EXTRA_MATH { bc_program_op(p, inst); break; } case BC_INST_NEG: case BC_INST_BOOL_NOT: #if BC_ENABLE_EXTRA_MATH case BC_INST_TRUNC: #endif // BC_ENABLE_EXTRA_MATH { bc_program_unary(p, inst); break; } #if BC_ENABLED case BC_INST_ASSIGN_POWER: case BC_INST_ASSIGN_MULTIPLY: case BC_INST_ASSIGN_DIVIDE: case BC_INST_ASSIGN_MODULUS: case BC_INST_ASSIGN_PLUS: case BC_INST_ASSIGN_MINUS: #if BC_ENABLE_EXTRA_MATH case BC_INST_ASSIGN_PLACES: case BC_INST_ASSIGN_LSHIFT: case BC_INST_ASSIGN_RSHIFT: #endif // BC_ENABLE_EXTRA_MATH case BC_INST_ASSIGN: case BC_INST_ASSIGN_POWER_NO_VAL: case BC_INST_ASSIGN_MULTIPLY_NO_VAL: case BC_INST_ASSIGN_DIVIDE_NO_VAL: case BC_INST_ASSIGN_MODULUS_NO_VAL: case BC_INST_ASSIGN_PLUS_NO_VAL: case BC_INST_ASSIGN_MINUS_NO_VAL: #if BC_ENABLE_EXTRA_MATH case BC_INST_ASSIGN_PLACES_NO_VAL: case BC_INST_ASSIGN_LSHIFT_NO_VAL: case BC_INST_ASSIGN_RSHIFT_NO_VAL: #endif // BC_ENABLE_EXTRA_MATH #endif // BC_ENABLED case BC_INST_ASSIGN_NO_VAL: { bc_program_assign(p, inst); break; } case BC_INST_POP: { #ifndef BC_PROG_NO_STACK_CHECK if (!BC_IS_BC) { if (BC_ERR(!BC_PROG_STACK(&p->results, 1))) bc_vm_err(BC_ERROR_EXEC_STACK); } #endif // BC_PROG_NO_STACK_CHECK assert(BC_PROG_STACK(&p->results, 1)); bc_vec_pop(&p->results); break; } #if DC_ENABLED case BC_INST_POP_EXEC: { assert(BC_PROG_STACK(&p->stack, 2)); bc_vec_pop(&p->stack); bc_vec_pop(&p->tail_calls); ip = bc_vec_top(&p->stack); func = bc_vec_item(&p->fns, ip->func); code = func->code.v; bc_program_setVecs(p, func); break; } case BC_INST_MODEXP: { bc_program_modexp(p); break; } case BC_INST_DIVMOD: { bc_program_divmod(p); break; } case BC_INST_EXECUTE: case BC_INST_EXEC_COND: { cond = (inst == BC_INST_EXEC_COND); bc_program_execStr(p, code, &ip->idx, cond, func->code.len); ip = bc_vec_top(&p->stack); func = bc_vec_item(&p->fns, ip->func); code = func->code.v; bc_program_setVecs(p, func); break; } case BC_INST_PRINT_STACK: { bc_program_printStack(p); break; } case BC_INST_CLEAR_STACK: { bc_vec_npop(&p->results, p->results.len); break; } case BC_INST_STACK_LEN: { bc_program_stackLen(p); break; } case BC_INST_DUPLICATE: { if (BC_ERR(!BC_PROG_STACK(&p->results, 1))) bc_vm_err(BC_ERROR_EXEC_STACK); assert(BC_PROG_STACK(&p->results, 1)); ptr = bc_vec_top(&p->results); BC_SIG_LOCK; bc_result_copy(&r, ptr); bc_vec_push(&p->results, &r); BC_SIG_UNLOCK; break; } case BC_INST_SWAP: { BcResult *ptr2; if (BC_ERR(!BC_PROG_STACK(&p->results, 2))) bc_vm_err(BC_ERROR_EXEC_STACK); assert(BC_PROG_STACK(&p->results, 2)); ptr = bc_vec_item_rev(&p->results, 0); ptr2 = bc_vec_item_rev(&p->results, 1); memcpy(&r, ptr, sizeof(BcResult)); memcpy(ptr, ptr2, sizeof(BcResult)); memcpy(ptr2, &r, sizeof(BcResult)); break; } case BC_INST_ASCIIFY: { bc_program_asciify(p); ip = bc_vec_top(&p->stack); func = bc_vec_item(&p->fns, ip->func); code = func->code.v; bc_program_setVecs(p, func); break; } case BC_INST_PRINT_STREAM: { bc_program_printStream(p); break; } case BC_INST_LOAD: case BC_INST_PUSH_VAR: { bool copy = (inst == BC_INST_LOAD); bc_program_pushVar(p, code, &ip->idx, true, copy); break; } case BC_INST_PUSH_TO_VAR: { idx = bc_program_index(code, &ip->idx); bc_program_copyToVar(p, idx, BC_TYPE_VAR, true); break; } case BC_INST_QUIT: case BC_INST_NQUIT: { bc_program_nquit(p, inst); ip = bc_vec_top(&p->stack); func = bc_vec_item(&p->fns, ip->func); code = func->code.v; bc_program_setVecs(p, func); break; } #endif // DC_ENABLED #ifndef NDEBUG default: { abort(); } #endif // NDEBUG } #ifndef NDEBUG // This is to allow me to use a debugger to see the last instruction, // which will point to which function was the problem. assert(jmp_bufs_len == vm.jmp_bufs.len); #endif // NDEBUG } } #if BC_DEBUG_CODE #if BC_ENABLED && DC_ENABLED void bc_program_printStackDebug(BcProgram *p) { bc_file_puts(&vm.fout, "-------------- Stack ----------\n"); bc_program_printStack(p); bc_file_puts(&vm.fout, "-------------- 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'); } 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, "\n\n"); } } #endif // BC_ENABLED && DC_ENABLED #endif // BC_DEBUG_CODE Index: head/contrib/bc =================================================================== --- head/contrib/bc (revision 366317) +++ head/contrib/bc (revision 366318) Property changes on: head/contrib/bc ___________________________________________________________________ Modified: svn:mergeinfo ## -0,0 +0,2 ## Merged /vendor/bc/dist:r363900-366316 Merged /vendor/bc/3.1.6:r366317