Index: head/contrib/bc/Makefile.in =================================================================== --- head/contrib/bc/Makefile.in (revision 363090) +++ head/contrib/bc/Makefile.in (revision 363091) @@ -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.1 +VERSION = 3.1.3 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: - $(LOCALE_INSTALL) $(NLSPATH) $(MAIN_EXEC) $(DESTDIR) + %%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 363090) +++ head/contrib/bc/NEWS.md (revision 363091) @@ -1,876 +1,896 @@ # News +## 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/configure.sh =================================================================== --- head/contrib/bc/configure.sh (revision 363090) +++ head/contrib/bc/configure.sh (revision 363091) @@ -1,954 +1,971 @@ #! /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. # script="$0" scriptdir=$(dirname "$script") script=$(basename "$script") . "$scriptdir/functions.sh" usage() { if [ $# -gt 0 ]; then _usage_val=1 printf "%s\n\n" "$1" else _usage_val=0 fi printf 'usage: %s -h\n' "$script" printf ' %s --help\n' "$script" - printf ' %s [-bD|-dB|-c] [-EfgGHMNPT] [-O OPT_LEVEL] [-k KARATSUBA_LEN]\n' "$script" + printf ' %s [-bD|-dB|-c] [-EfgGHlMNPT] [-O OPT_LEVEL] [-k KARATSUBA_LEN]\n' "$script" printf ' %s \\\n' "$script" printf ' [--bc-only --disable-dc|--dc-only --disable-bc|--coverage] \\\n' printf ' [--debug --disable-extra-math --disable-generated-tests] \\\n' printf ' [--disable-history --disable-man-pages --disable-nls] \\\n' - printf ' [--disable-prompt --disable-strip] \\\n' + printf ' [--disable-prompt --disable-strip] [--install-all-locales] \\\n' printf ' [--opt=OPT_LEVEL] [--karatsuba-len=KARATSUBA_LEN] \\\n' printf ' [--prefix=PREFIX] [--bindir=BINDIR] [--datarootdir=DATAROOTDIR] \\\n' printf ' [--datadir=DATADIR] [--mandir=MANDIR] [--man1dir=MAN1DIR] \\\n' printf ' [--force] \\\n' printf '\n' printf ' -b, --bc-only\n' printf ' Build bc only. It is an error if "-d", "--dc-only", "-B", or "--disable-bc"\n' printf ' are specified too.\n' printf ' -B, --disable-bc\n' printf ' Disable bc. It is an error if "-b", "--bc-only", "-D", or "--disable-dc"\n' printf ' are specified too.\n' printf ' -c, --coverage\n' printf ' Generate test coverage code. Requires gcov and regcovr.\n' printf ' It is an error if either "-b" ("-D") or "-d" ("-B") is specified.\n' printf ' Requires a compiler that use gcc-compatible coverage options\n' printf ' -d, --dc-only\n' printf ' Build dc only. It is an error if "-b", "--bc-only", "-D", or "--disable-dc"\n' printf ' are specified too.\n' printf ' -D, --disable-dc\n' printf ' Disable dc. It is an error if "-d", "--dc-only" "-B", or "--disable-bc"\n' printf ' are specified too.\n' printf ' -E, --disable-extra-math\n' printf ' Disable extra math. This includes: "$" operator (truncate to integer),\n' printf ' "@" operator (set number of decimal places), and r(x, p) (rounding\n' printf ' function). Additionally, this option disables the extra printing\n' printf ' functions in the math library.\n' printf ' -f, --force\n' printf ' Force use of all enabled options, even if they do not work. This\n' printf ' option is to allow the maintainer a way to test that certain options\n' printf ' are not failing invisibly. (Development only.)' printf ' -g, --debug\n' printf ' Build in debug mode. Adds the "-g" flag, and if there are no\n' printf ' other CFLAGS, and "-O" was not given, this also adds the "-O0"\n' printf ' flag. If this flag is *not* given, "-DNDEBUG" is added to CPPFLAGS\n' printf ' and a strip flag is added to the link stage.\n' printf ' -G, --disable-generated-tests\n' printf ' Disable generating tests. This is for platforms that do not have a\n' printf ' GNU bc-compatible bc to generate tests.\n' printf ' -h, --help\n' printf ' Print this help message and exit.\n' printf ' -H, --disable-history\n' printf ' Disable history.\n' printf ' -k KARATSUBA_LEN, --karatsuba-len KARATSUBA_LEN\n' printf ' Set the karatsuba length to KARATSUBA_LEN (default is 64).\n' printf ' It is an error if KARATSUBA_LEN is not a number or is less than 16.\n' + printf ' -l, --install-all-locales\n' + printf ' Installs all locales, regardless of how many are on the system. This\n' + printf ' option is useful for package maintainers who want to make sure that\n' + printf ' a package contains all of the locales that end users might need.\n' printf ' -M, --disable-man-pages\n' printf ' Disable installing manpages.\n' printf ' -N, --disable-nls\n' printf ' Disable POSIX locale (NLS) support.\n' printf ' -O OPT_LEVEL, --opt OPT_LEVEL\n' printf ' Set the optimization level. This can also be included in the CFLAGS,\n' printf ' but it is provided, so maintainers can build optimized debug builds.\n' printf ' This is passed through to the compiler, so it must be supported.\n' printf ' -P, --disable-prompt\n' printf ' Disables the prompt in the built bc. The prompt will never show up,\n' printf ' or in other words, it will be permanently disabled and cannot be\n' printf ' enabled.\n' printf ' -T, --disable-strip\n' printf ' Disable stripping symbols from the compiled binary or binaries.\n' printf ' Stripping symbols only happens when debug mode is off.\n' printf ' --prefix PREFIX\n' printf ' The prefix to install to. Overrides "$PREFIX" if it exists.\n' printf ' If PREFIX is "/usr", install path will be "/usr/bin".\n' printf ' Default is "/usr/local".\n' printf ' --bindir BINDIR\n' printf ' The directory to install binaries. Overrides "$BINDIR" if it exists.\n' printf ' Default is "$PREFIX/bin".\n' printf ' --datarootdir DATAROOTDIR\n' printf ' The root location for data files. Overrides "$DATAROOTDIR" if it exists.\n' printf ' Default is "$PREFIX/share".\n' printf ' --datadir DATADIR\n' printf ' The location for data files. Overrides "$DATADIR" if it exists.\n' printf ' Default is "$DATAROOTDIR".\n' printf ' --mandir MANDIR\n' printf ' The location to install manpages to. Overrides "$MANDIR" if it exists.\n' printf ' Default is "$DATADIR/man".\n' printf ' --man1dir MAN1DIR\n' printf ' The location to install Section 1 manpages to. Overrides "$MAN1DIR" if\n' printf ' it exists. Default is "$MANDIR/man1".\n' printf '\n' printf 'In addition, the following environment variables are used:\n' printf '\n' printf ' CC C compiler. Must be compatible with POSIX c99. If there is a\n' printf ' space in the basename of the compiler, the items after the\n' printf ' first space are assumed to be compiler flags, and in that case,\n' printf ' the flags are automatically moved into CFLAGS. Default is\n' printf ' "c99".\n' printf ' HOSTCC Host C compiler. Must be compatible with POSIX c99. If there is\n' printf ' a space in the basename of the compiler, the items after the\n' printf ' first space are assumed to be compiler flags, and in the case,\n' printf ' the flags are automatically moved into HOSTCFLAGS. Default is\n' printf ' "$CC".\n' printf ' HOST_CC Same as HOSTCC. If HOSTCC also exists, it is used.\n' printf ' CFLAGS C compiler flags.\n' printf ' HOSTCFLAGS CFLAGS for HOSTCC. Default is "$CFLAGS".\n' printf ' HOST_CFLAGS Same as HOST_CFLAGS. If HOST_CFLAGS also exists, it is used.\n' printf ' CPPFLAGS C preprocessor flags. Default is "".\n' printf ' LDFLAGS Linker flags. Default is "".\n' printf ' PREFIX The prefix to install to. Default is "/usr/local".\n' printf ' If PREFIX is "/usr", install path will be "/usr/bin".\n' printf ' BINDIR The directory to install binaries. Default is "$PREFIX/bin".\n' printf ' DATAROOTDIR The root location for data files. Default is "$PREFIX/share".\n' printf ' DATADIR The location for data files. Default is "$DATAROOTDIR".\n' printf ' MANDIR The location to install manpages to. Default is "$DATADIR/man".\n' printf ' MAN1DIR The location to install Section 1 manpages to. Default is\n' printf ' "$MANDIR/man1".\n' printf ' NLSPATH The location to install locale catalogs to. Must be an absolute\n' printf ' path (or contain one). This is treated the same as the POSIX\n' printf ' definition of $NLSPATH (see POSIX environment variables for\n' printf ' more information). Default is "/usr/share/locale/%%L/%%N".\n' printf ' EXECSUFFIX The suffix to append to the executable names, used to not\n' printf ' interfere with other installed bc executables. Default is "".\n' printf ' EXECPREFIX The prefix to append to the executable names, used to not\n' printf ' interfere with other installed bc executables. Default is "".\n' printf ' DESTDIR For package creation. Default is "". If it is empty when\n' printf ' `%s` is run, it can also be passed to `make install`\n' "$script" printf ' later as an environment variable. If both are specified,\n' printf ' the one given to `%s` takes precedence.\n' "$script" printf ' LONG_BIT The number of bits in a C `long` type. This is mostly for the\n' printf ' embedded space since this `bc` uses `long`s internally for\n' printf ' overflow checking. In C99, a `long` is required to be 32 bits.\n' printf ' For most normal desktop systems, setting this is unnecessary,\n' printf ' except that 32-bit platforms with 64-bit longs may want to set\n' printf ' it to `32`. Default is the default of `LONG_BIT` for the target\n' printf ' platform. Minimum allowed is `32`. It is a build time error if\n' printf ' the specified value of `LONG_BIT` is greater than the default\n' printf ' value of `LONG_BIT` for the target platform.\n' printf ' GEN_HOST Whether to use `gen/strgen.c`, instead of `gen/strgen.sh`, to\n' printf ' produce the C files that contain the help texts as well as the\n' printf ' math libraries. By default, `gen/strgen.c` is used, compiled by\n' printf ' "$HOSTCC" and run on the host machine. Using `gen/strgen.sh`\n' printf ' removes the need to compile and run an executable on the host\n' printf ' machine since `gen/strgen.sh` is a POSIX shell script. However,\n' printf ' `gen/lib2.bc` is perilously close to 4095 characters, the max\n' printf ' supported length of a string literal in C99 (and it could be\n' printf ' added to in the future), and `gen/strgen.sh` generates a string\n' printf ' literal instead of an array, as `gen/strgen.c` does. For most\n' printf ' production-ready compilers, this limit probably is not\n' printf ' enforced, but it could be. Both options are still available for\n' printf ' this reason. If you are sure your compiler does not have the\n' printf ' limit and do not want to compile and run a binary on the host\n' printf ' machine, set this variable to "0". Any other value, or a\n' printf ' non-existent value, will cause the build system to compile and\n' printf ' run `gen/strgen.c`. Default is "".\n' printf ' GEN_EMU Emulator to run string generator code under (leave empty if not\n' printf ' necessary). This is not necessary when using `gen/strgen.sh`.\n' printf ' Default is "".\n' printf '\n' printf 'WARNING: even though `configure.sh` supports both option types, short and\n' printf 'long, it does not support handling both at the same time. Use only one type.\n' exit "$_usage_val" } replace_ext() { if [ "$#" -ne 3 ]; then err_exit "Invalid number of args to $0" fi _replace_ext_file="$1" _replace_ext_ext1="$2" _replace_ext_ext2="$3" _replace_ext_result=${_replace_ext_file%.$_replace_ext_ext1}.$_replace_ext_ext2 printf '%s\n' "$_replace_ext_result" } replace_exts() { if [ "$#" -ne 3 ]; then err_exit "Invalid number of args to $0" fi _replace_exts_files="$1" _replace_exts_ext1="$2" _replace_exts_ext2="$3" for _replace_exts_file in $_replace_exts_files; do _replace_exts_new_name=$(replace_ext "$_replace_exts_file" "$_replace_exts_ext1" "$_replace_exts_ext2") _replace_exts_result="$_replace_exts_result $_replace_exts_new_name" done printf '%s\n' "$_replace_exts_result" } replace() { if [ "$#" -ne 3 ]; then err_exit "Invalid number of args to $0" fi _replace_str="$1" _replace_needle="$2" _replace_replacement="$3" substring_replace "$_replace_str" "%%$_replace_needle%%" "$_replace_replacement" } gen_file_lists() { if [ "$#" -lt 3 ]; then err_exit "Invalid number of args to $0" fi _gen_file_lists_contents="$1" shift _gen_file_lists_filedir="$1" shift _gen_file_lists_typ="$1" shift # If there is an extra argument, and it # is zero, we keep the file lists empty. if [ "$#" -gt 0 ]; then _gen_file_lists_use="$1" else _gen_file_lists_use="1" fi _gen_file_lists_needle_src="${_gen_file_lists_typ}SRC" _gen_file_lists_needle_obj="${_gen_file_lists_typ}OBJ" _gen_file_lists_needle_gcda="${_gen_file_lists_typ}GCDA" _gen_file_lists_needle_gcno="${_gen_file_lists_typ}GCNO" if [ "$_gen_file_lists_use" -ne 0 ]; then _gen_file_lists_replacement=$(cd "$_gen_file_lists_filedir" && find . ! -name . -prune -name "*.c" | cut -d/ -f2 | sed "s@^@$_gen_file_lists_filedir/@g" | tr '\n' ' ') _gen_file_lists_contents=$(replace "$_gen_file_lists_contents" "$_gen_file_lists_needle_src" "$_gen_file_lists_replacement") _gen_file_lists_replacement=$(replace_exts "$_gen_file_lists_replacement" "c" "o") _gen_file_lists_contents=$(replace "$_gen_file_lists_contents" "$_gen_file_lists_needle_obj" "$_gen_file_lists_replacement") _gen_file_lists_replacement=$(replace_exts "$_gen_file_lists_replacement" "o" "gcda") _gen_file_lists_contents=$(replace "$_gen_file_lists_contents" "$_gen_file_lists_needle_gcda" "$_gen_file_lists_replacement") _gen_file_lists_replacement=$(replace_exts "$_gen_file_lists_replacement" "gcda" "gcno") _gen_file_lists_contents=$(replace "$_gen_file_lists_contents" "$_gen_file_lists_needle_gcno" "$_gen_file_lists_replacement") else _gen_file_lists_contents=$(replace "$_gen_file_lists_contents" "$_gen_file_lists_needle_src" "") _gen_file_lists_contents=$(replace "$_gen_file_lists_contents" "$_gen_file_lists_needle_obj" "") _gen_file_lists_contents=$(replace "$_gen_file_lists_contents" "$_gen_file_lists_needle_gcda" "") _gen_file_lists_contents=$(replace "$_gen_file_lists_contents" "$_gen_file_lists_needle_gcno" "") fi printf '%s\n' "$_gen_file_lists_contents" } bc_only=0 dc_only=0 coverage=0 karatsuba_len=32 debug=0 hist=1 extra_math=1 optimization="" generate_tests=1 install_manpages=1 nls=1 prompt=1 force=0 strip_bin=1 +all_locales=0 -while getopts "bBcdDEfgGhHk:MNO:PST-" opt; do +while getopts "bBcdDEfgGhHk:lMNO:PST-" opt; do case "$opt" in b) bc_only=1 ;; B) dc_only=1 ;; c) coverage=1 ;; d) dc_only=1 ;; D) bc_only=1 ;; E) extra_math=0 ;; f) force=1 ;; g) debug=1 ;; G) generate_tests=0 ;; h) usage ;; H) hist=0 ;; k) karatsuba_len="$OPTARG" ;; + l) all_locales=1 ;; M) install_manpages=0 ;; N) nls=0 ;; O) optimization="$OPTARG" ;; P) prompt=0 ;; T) strip_bin=0 ;; -) arg="$1" arg="${arg#--}" LONG_OPTARG="${arg#*=}" case $arg in help) usage ;; bc-only) bc_only=1 ;; dc-only) dc_only=1 ;; coverage) coverage=1 ;; debug) debug=1 ;; force) force=1 ;; prefix=?*) PREFIX="$LONG_OPTARG" ;; prefix) if [ "$#" -lt 2 ]; then usage "No argument given for '--$arg' option" fi PREFIX="$2" shift ;; bindir=?*) BINDIR="$LONG_OPTARG" ;; bindir) if [ "$#" -lt 2 ]; then usage "No argument given for '--$arg' option" fi BINDIR="$2" shift ;; datarootdir=?*) DATAROOTDIR="$LONG_OPTARG" ;; datarootdir) if [ "$#" -lt 2 ]; then usage "No argument given for '--$arg' option" fi DATAROOTDIR="$2" shift ;; datadir=?*) DATADIR="$LONG_OPTARG" ;; datadir) if [ "$#" -lt 2 ]; then usage "No argument given for '--$arg' option" fi DATADIR="$2" shift ;; mandir=?*) MANDIR="$LONG_OPTARG" ;; mandir) if [ "$#" -lt 2 ]; then usage "No argument given for '--$arg' option" fi MANDIR="$2" shift ;; man1dir=?*) MAN1DIR="$LONG_OPTARG" ;; man1dir) if [ "$#" -lt 2 ]; then usage "No argument given for '--$arg' option" fi MAN1DIR="$2" shift ;; localedir=?*) LOCALEDIR="$LONG_OPTARG" ;; localedir) if [ "$#" -lt 2 ]; then usage "No argument given for '--$arg' option" fi LOCALEDIR="$2" shift ;; karatsuba-len=?*) karatsuba_len="$LONG_OPTARG" ;; karatsuba-len) if [ "$#" -lt 2 ]; then usage "No argument given for '--$arg' option" fi karatsuba_len="$1" shift ;; opt=?*) optimization="$LONG_OPTARG" ;; opt) if [ "$#" -lt 2 ]; then usage "No argument given for '--$arg' option" fi optimization="$1" shift ;; disable-bc) dc_only=1 ;; disable-dc) bc_only=1 ;; disable-extra-math) extra_math=0 ;; disable-generated-tests) generate_tests=0 ;; disable-history) hist=0 ;; disable-man-pages) install_manpages=0 ;; disable-nls) nls=0 ;; disable-prompt) prompt=0 ;; disable-strip) strip_bin=0 ;; + install-all-locales) all_locales=1 ;; help* | bc-only* | dc-only* | coverage* | debug*) usage "No arg allowed for --$arg option" ;; disable-bc* | disable-dc* | disable-extra-math*) usage "No arg allowed for --$arg option" ;; disable-generated-tests* | disable-history*) usage "No arg allowed for --$arg option" ;; disable-man-pages* | disable-nls* | disable-strip*) usage "No arg allowed for --$arg option" ;; + install-all-locales*) + usage "No arg allowed for --$arg option" ;; '') break ;; # "--" terminates argument processing * ) usage "Invalid option $LONG_OPTARG" ;; esac shift OPTIND=1 ;; ?) usage "Invalid option $opt" ;; esac done if [ "$bc_only" -eq 1 ] && [ "$dc_only" -eq 1 ]; then usage "Can only specify one of -b(-D) or -d(-B)" fi case $karatsuba_len in (*[!0-9]*|'') usage "KARATSUBA_LEN is not a number" ;; (*) ;; esac if [ "$karatsuba_len" -lt 16 ]; then usage "KARATSUBA_LEN is less than 16" fi set -e if [ -z "${LONG_BIT+set}" ]; then LONG_BIT_DEFINE="" elif [ "$LONG_BIT" -lt 32 ]; then usage "LONG_BIT is less than 32" else LONG_BIT_DEFINE="-DBC_LONG_BIT=\$(BC_LONG_BIT)" fi if [ -z "$CC" ]; then CC="c99" else ccbase=$(basename "$CC") suffix=" *" prefix="* " if [ "${ccbase%%$suffix}" != "$ccbase" ]; then ccflags="${ccbase#$prefix}" cc="${ccbase%%$suffix}" ccdir=$(dirname "$CC") if [ "$ccdir" = "." ] && [ "${CC#.}" = "$CC" ]; then ccdir="" else ccdir="$ccdir/" fi CC="${ccdir}${cc}" CFLAGS="$CFLAGS $ccflags" fi fi if [ -z "$HOSTCC" ] && [ -z "$HOST_CC" ]; then HOSTCC="$CC" elif [ -z "$HOSTCC" ]; then HOSTCC="$HOST_CC" fi if [ "$HOSTCC" != "$CC" ]; then ccbase=$(basename "$HOSTCC") suffix=" *" prefix="* " if [ "${ccbase%%$suffix}" != "$ccbase" ]; then ccflags="${ccbase#$prefix}" cc="${ccbase%%$suffix}" ccdir=$(dirname "$HOSTCC") if [ "$ccdir" = "." ] && [ "${HOSTCC#.}" = "$HOSTCC" ]; then ccdir="" else ccdir="$ccdir/" fi HOSTCC="${ccdir}${cc}" HOSTCFLAGS="$HOSTCFLAGS $ccflags" fi fi if [ -z "${HOSTCFLAGS+set}" ] && [ -z "${HOST_CFLAGS+set}" ]; then HOSTCFLAGS="$CFLAGS" elif [ -z "${HOSTCFLAGS+set}" ]; then HOSTCFLAGS="$HOST_CFLAGS" fi link="@printf 'No link necessary\\\\n'" main_exec="BC" executable="BC_EXEC" bc_test="@tests/all.sh bc $extra_math 1 $generate_tests 0 \$(BC_EXEC)" bc_time_test="@tests/all.sh bc $extra_math 1 $generate_tests 1 \$(BC_EXEC)" dc_test="@tests/all.sh dc $extra_math 1 $generate_tests 0 \$(DC_EXEC)" dc_time_test="@tests/all.sh dc $extra_math 1 $generate_tests 1 \$(DC_EXEC)" timeconst="@tests/bc/timeconst.sh tests/bc/scripts/timeconst.bc \$(BC_EXEC)" # In order to have cleanup at exit, we need to be in # debug mode, so don't run valgrind without that. if [ "$debug" -ne 0 ]; then vg_bc_test="@tests/all.sh bc $extra_math 1 $generate_tests 0 valgrind \$(VALGRIND_ARGS) \$(BC_EXEC)" vg_dc_test="@tests/all.sh dc $extra_math 1 $generate_tests 0 valgrind \$(VALGRIND_ARGS) \$(DC_EXEC)" else vg_bc_test="@printf 'Cannot run valgrind without debug flags\\\\n'" vg_dc_test="@printf 'Cannot run valgrind without debug flags\\\\n'" fi karatsuba="@printf 'karatsuba cannot be run because one of bc or dc is not built\\\\n'" karatsuba_test="@printf 'karatsuba cannot be run because one of bc or dc is not built\\\\n'" bc_lib="\$(GEN_DIR)/lib.o" bc_help="\$(GEN_DIR)/bc_help.o" dc_help="\$(GEN_DIR)/dc_help.o" if [ "$bc_only" -eq 1 ]; then bc=1 dc=0 dc_help="" executables="bc" dc_test="@printf 'No dc tests to run\\\\n'" dc_time_test="@printf 'No dc tests to run\\\\n'" vg_dc_test="@printf 'No dc tests to run\\\\n'" install_prereqs=" install_bc_manpage" uninstall_prereqs=" uninstall_bc" uninstall_man_prereqs=" uninstall_bc_manpage" elif [ "$dc_only" -eq 1 ]; then bc=0 dc=1 bc_lib="" bc_help="" executables="dc" main_exec="DC" executable="DC_EXEC" bc_test="@printf 'No bc tests to run\\\\n'" bc_time_test="@printf 'No bc tests to run\\\\n'" vg_bc_test="@printf 'No bc tests to run\\\\n'" timeconst="@printf 'timeconst cannot be run because bc is not built\\\\n'" install_prereqs=" install_dc_manpage" uninstall_prereqs=" uninstall_dc" uninstall_man_prereqs=" uninstall_dc_manpage" else bc=1 dc=1 executables="bc and dc" link="\$(LINK) \$(BIN) \$(EXEC_PREFIX)\$(DC)" karatsuba="@\$(KARATSUBA) 30 0 \$(BC_EXEC)" karatsuba_test="@\$(KARATSUBA) 1 100 \$(BC_EXEC)" install_prereqs=" install_bc_manpage install_dc_manpage" uninstall_prereqs=" uninstall_bc uninstall_dc" uninstall_man_prereqs=" uninstall_bc_manpage uninstall_dc_manpage" fi if [ "$debug" -eq 1 ]; then if [ -z "$CFLAGS" ] && [ -z "$optimization" ]; then CFLAGS="-O0" fi CFLAGS="-g $CFLAGS" else CPPFLAGS="-DNDEBUG $CPPFLAGS" if [ "$strip_bin" -ne 0 ]; then LDFLAGS="-s $LDFLAGS" fi fi if [ -n "$optimization" ]; then CFLAGS="-O$optimization $CFLAGS" fi if [ "$coverage" -eq 1 ]; then if [ "$bc_only" -eq 1 ] || [ "$dc_only" -eq 1 ]; then usage "Can only specify -c without -b or -d" fi CFLAGS="-fprofile-arcs -ftest-coverage -g -O0 $CFLAGS" CPPFLAGS="-DNDEBUG $CPPFLAGS" COVERAGE_OUTPUT="@gcov -pabcdf \$(GCDA) \$(BC_GCDA) \$(DC_GCDA) \$(HISTORY_GCDA) \$(RAND_GCDA)" COVERAGE_OUTPUT="$COVERAGE_OUTPUT;\$(RM) -f \$(GEN)*.gc*" COVERAGE_OUTPUT="$COVERAGE_OUTPUT;gcovr --html-details --output index.html" COVERAGE_PREREQS=" test coverage_output" else COVERAGE_OUTPUT="@printf 'Coverage not generated\\\\n'" COVERAGE_PREREQS="" fi if [ -z "${DESTDIR+set}" ]; then destdir="" else destdir="DESTDIR = $DESTDIR" fi if [ -z "${PREFIX+set}" ]; then PREFIX="/usr/local" fi if [ -z "${BINDIR+set}" ]; then BINDIR="$PREFIX/bin" fi if [ "$install_manpages" -ne 0 ] || [ "$nls" -ne 0 ]; then if [ -z "${DATAROOTDIR+set}" ]; then DATAROOTDIR="$PREFIX/share" fi fi if [ "$install_manpages" -ne 0 ]; then if [ -z "${DATADIR+set}" ]; then DATADIR="$DATAROOTDIR" fi if [ -z "${MANDIR+set}" ]; then MANDIR="$DATADIR/man" fi if [ -z "${MAN1DIR+set}" ]; then MAN1DIR="$MANDIR/man1" fi else install_prereqs="" uninstall_man_prereqs="" fi if [ "$nls" -ne 0 ]; then set +e printf 'Testing NLS...\n' flags="-DBC_ENABLE_NLS=1 -DBC_ENABLED=$bc -DDC_ENABLED=$dc" flags="$flags -DBC_ENABLE_HISTORY=$hist" flags="$flags -DBC_ENABLE_EXTRA_MATH=$extra_math -I./include/" flags="$flags -D_POSIX_C_SOURCE=200809L -D_XOPEN_SOURCE=700" "$CC" $CPPFLAGS $CFLAGS $flags -c "src/vm.c" -o "$scriptdir/vm.o" > /dev/null 2>&1 err="$?" rm -rf "$scriptdir/vm.o" # If this errors, it is probably because of building on Windows, # and NLS is not supported on Windows, so disable it. if [ "$err" -ne 0 ]; then printf 'NLS does not work.\n' if [ $force -eq 0 ]; then printf 'Disabling NLS...\n\n' nls=0 else printf 'Forcing NLS...\n\n' fi else printf 'NLS works.\n\n' printf 'Testing gencat...\n' gencat "$scriptdir/en_US.cat" "$scriptdir/locales/en_US.msg" > /dev/null 2>&1 err="$?" rm -rf "$scriptdir/en_US.cat" if [ "$err" -ne 0 ]; then printf 'gencat does not work.\n' if [ $force -eq 0 ]; then printf 'Disabling NLS...\n\n' nls=0 else printf 'Forcing NLS...\n\n' fi else printf 'gencat works.\n\n' if [ "$HOSTCC" != "$CC" ]; then printf 'Cross-compile detected.\n\n' printf 'WARNING: Catalog files generated with gencat may not be portable\n' printf ' across different architectures.\n\n' fi if [ -z "$NLSPATH" ]; then NLSPATH="/usr/share/locale/%L/%N" fi install_locales_prereqs=" install_locales" uninstall_locales_prereqs=" uninstall_locales" fi fi set -e else install_locales_prereqs="" uninstall_locales_prereqs="" + all_locales=0 fi +if [ "$nls" -ne 0 ] && [ "$all_locales" -ne 0 ]; then + install_locales="\$(LOCALE_INSTALL) -l \$(NLSPATH) \$(MAIN_EXEC) \$(DESTDIR)" +else + install_locales="\$(LOCALE_INSTALL) \$(NLSPATH) \$(MAIN_EXEC) \$(DESTDIR)" +fi + if [ "$hist" -eq 1 ]; then set +e printf 'Testing history...\n' flags="-DBC_ENABLE_HISTORY=1 -DBC_ENABLED=$bc -DDC_ENABLED=$dc" flags="$flags -DBC_ENABLE_NLS=$nls" flags="$flags -DBC_ENABLE_EXTRA_MATH=$extra_math -I./include/" flags="$flags -D_POSIX_C_SOURCE=200809L -D_XOPEN_SOURCE=700" "$CC" $CPPFLAGS $CFLAGS $flags -c "src/history/history.c" -o "$scriptdir/history.o" > /dev/null 2>&1 err="$?" rm -rf "$scriptdir/history.o" # If this errors, it is probably because of building on Windows, # and history is not supported on Windows, so disable it. if [ "$err" -ne 0 ]; then printf 'History does not work.\n' if [ $force -eq 0 ]; then printf 'Disabling history...\n\n' hist=0 else printf 'Forcing history...\n\n' fi else printf 'History works.\n\n' fi set -e fi if [ "$extra_math" -eq 1 ] && [ "$bc" -ne 0 ]; then BC_LIB2_O="\$(GEN_DIR)/lib2.o" else BC_LIB2_O="" fi GEN="strgen" GEN_EXEC_TARGET="\$(HOSTCC) \$(HOSTCFLAGS) -o \$(GEN_EXEC) \$(GEN_C)" CLEAN_PREREQS=" clean_gen" if [ -z "${GEN_HOST+set}" ]; then GEN_HOST=1 else if [ "$GEN_HOST" -eq 0 ]; then GEN="strgen.sh" GEN_EXEC_TARGET="@printf 'Do not need to build gen/strgen.c\\\\n'" CLEAN_PREREQS="" fi fi manpage_args="" if [ "$extra_math" -eq 0 ]; then manpage_args="E" fi if [ "$hist" -eq 0 ]; then manpage_args="${manpage_args}H" fi if [ "$nls" -eq 0 ]; then manpage_args="${manpage_args}N" fi if [ "$prompt" -eq 0 ]; then manpage_args="${manpage_args}P" fi if [ "$manpage_args" = "" ]; then manpage_args="A" fi # Print out the values; this is for debugging. if [ "$bc" -ne 0 ]; then printf 'Building bc\n' else printf 'Not building bc\n' fi if [ "$dc" -ne 0 ]; then printf 'Building dc\n' else printf 'Not building dc\n' fi printf '\n' printf 'BC_ENABLE_HISTORY=%s\n' "$hist" printf 'BC_ENABLE_EXTRA_MATH=%s\n' "$extra_math" printf 'BC_ENABLE_NLS=%s\n' "$nls" printf 'BC_ENABLE_PROMPT=%s\n' "$prompt" printf '\n' printf 'BC_NUM_KARATSUBA_LEN=%s\n' "$karatsuba_len" printf '\n' printf 'CC=%s\n' "$CC" printf 'CFLAGS=%s\n' "$CFLAGS" printf 'HOSTCC=%s\n' "$HOSTCC" printf 'HOSTCFLAGS=%s\n' "$HOSTCFLAGS" printf 'CPPFLAGS=%s\n' "$CPPFLAGS" printf 'LDFLAGS=%s\n' "$LDFLAGS" printf 'PREFIX=%s\n' "$PREFIX" printf 'BINDIR=%s\n' "$BINDIR" printf 'DATAROOTDIR=%s\n' "$DATAROOTDIR" printf 'DATADIR=%s\n' "$DATADIR" printf 'MANDIR=%s\n' "$MANDIR" printf 'MAN1DIR=%s\n' "$MAN1DIR" printf 'NLSPATH=%s\n' "$NLSPATH" printf 'EXECSUFFIX=%s\n' "$EXECSUFFIX" printf 'EXECPREFIX=%s\n' "$EXECPREFIX" printf 'DESTDIR=%s\n' "$DESTDIR" printf 'LONG_BIT=%s\n' "$LONG_BIT" printf 'GEN_HOST=%s\n' "$GEN_HOST" printf 'GEN_EMU=%s\n' "$GEN_EMU" contents=$(cat "$scriptdir/Makefile.in") needle="WARNING" replacement='*** WARNING: Autogenerated from Makefile.in. DO NOT MODIFY ***' contents=$(replace "$contents" "$needle" "$replacement") contents=$(gen_file_lists "$contents" "$scriptdir/src" "") contents=$(gen_file_lists "$contents" "$scriptdir/src/bc" "BC_" "$bc") contents=$(gen_file_lists "$contents" "$scriptdir/src/dc" "DC_" "$dc") contents=$(gen_file_lists "$contents" "$scriptdir/src/history" "HISTORY_" "$hist") contents=$(gen_file_lists "$contents" "$scriptdir/src/rand" "RAND_" "$extra_math") contents=$(replace "$contents" "BC_ENABLED" "$bc") contents=$(replace "$contents" "DC_ENABLED" "$dc") contents=$(replace "$contents" "LINK" "$link") contents=$(replace "$contents" "HISTORY" "$hist") contents=$(replace "$contents" "EXTRA_MATH" "$extra_math") contents=$(replace "$contents" "NLS" "$nls") contents=$(replace "$contents" "PROMPT" "$prompt") contents=$(replace "$contents" "BC_LIB_O" "$bc_lib") contents=$(replace "$contents" "BC_HELP_O" "$bc_help") contents=$(replace "$contents" "DC_HELP_O" "$dc_help") contents=$(replace "$contents" "BC_LIB2_O" "$BC_LIB2_O") contents=$(replace "$contents" "KARATSUBA_LEN" "$karatsuba_len") contents=$(replace "$contents" "NLSPATH" "$NLSPATH") contents=$(replace "$contents" "DESTDIR" "$destdir") contents=$(replace "$contents" "EXECSUFFIX" "$EXECSUFFIX") contents=$(replace "$contents" "EXECPREFIX" "$EXECPREFIX") contents=$(replace "$contents" "BINDIR" "$BINDIR") contents=$(replace "$contents" "MAN1DIR" "$MAN1DIR") contents=$(replace "$contents" "CFLAGS" "$CFLAGS") contents=$(replace "$contents" "HOSTCFLAGS" "$HOSTCFLAGS") contents=$(replace "$contents" "CPPFLAGS" "$CPPFLAGS") contents=$(replace "$contents" "LDFLAGS" "$LDFLAGS") contents=$(replace "$contents" "CC" "$CC") contents=$(replace "$contents" "HOSTCC" "$HOSTCC") contents=$(replace "$contents" "COVERAGE_OUTPUT" "$COVERAGE_OUTPUT") contents=$(replace "$contents" "COVERAGE_PREREQS" "$COVERAGE_PREREQS") contents=$(replace "$contents" "INSTALL_PREREQS" "$install_prereqs") +contents=$(replace "$contents" "INSTALL_LOCALES" "$install_locales") contents=$(replace "$contents" "INSTALL_LOCALES_PREREQS" "$install_locales_prereqs") contents=$(replace "$contents" "UNINSTALL_MAN_PREREQS" "$uninstall_man_prereqs") contents=$(replace "$contents" "UNINSTALL_PREREQS" "$uninstall_prereqs") contents=$(replace "$contents" "UNINSTALL_LOCALES_PREREQS" "$uninstall_locales_prereqs") contents=$(replace "$contents" "EXECUTABLES" "$executables") contents=$(replace "$contents" "MAIN_EXEC" "$main_exec") contents=$(replace "$contents" "EXEC" "$executable") contents=$(replace "$contents" "BC_TEST" "$bc_test") contents=$(replace "$contents" "BC_TIME_TEST" "$bc_time_test") contents=$(replace "$contents" "DC_TEST" "$dc_test") contents=$(replace "$contents" "DC_TIME_TEST" "$dc_time_test") contents=$(replace "$contents" "VG_BC_TEST" "$vg_bc_test") contents=$(replace "$contents" "VG_DC_TEST" "$vg_dc_test") contents=$(replace "$contents" "TIMECONST" "$timeconst") contents=$(replace "$contents" "KARATSUBA" "$karatsuba") contents=$(replace "$contents" "KARATSUBA_TEST" "$karatsuba_test") contents=$(replace "$contents" "LONG_BIT" "$LONG_BIT") contents=$(replace "$contents" "LONG_BIT_DEFINE" "$LONG_BIT_DEFINE") contents=$(replace "$contents" "GEN" "$GEN") contents=$(replace "$contents" "GEN_EXEC_TARGET" "$GEN_EXEC_TARGET") contents=$(replace "$contents" "CLEAN_PREREQS" "$CLEAN_PREREQS") contents=$(replace "$contents" "GEN_EMU" "$GEN_EMU") printf '%s\n' "$contents" > "$scriptdir/Makefile" cd "$scriptdir" cp -f manuals/bc/$manpage_args.1.md manuals/bc.1.md cp -f manuals/bc/$manpage_args.1 manuals/bc.1 cp -f manuals/dc/$manpage_args.1.md manuals/dc.1.md cp -f manuals/dc/$manpage_args.1 manuals/dc.1 make clean > /dev/null Index: head/contrib/bc/include/vm.h =================================================================== --- head/contrib/bc/include/vm.h (revision 363090) +++ head/contrib/bc/include/vm.h (revision 363091) @@ -1,392 +1,392 @@ /* * ***************************************************************************** * * 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's VM. * */ #ifndef BC_VM_H #define BC_VM_H #include #include #include #if BC_ENABLE_NLS # ifdef _WIN32 # error NLS is not supported on Windows. # endif // _WIN32 #include #endif // BC_ENABLE_NLS #include #include #include #include #include #include #if !BC_ENABLED && !DC_ENABLED #error Must define BC_ENABLED, DC_ENABLED, or both #endif // CHAR_BIT must be at least 6. #if CHAR_BIT < 6 #error CHAR_BIT must be at least 6. #endif #ifndef BC_ENABLE_NLS #define BC_ENABLE_NLS (0) #endif // BC_ENABLE_NLS #ifndef MAINEXEC #define MAINEXEC bc #endif #ifndef EXECPREFIX #define EXECPREFIX #endif #define GEN_STR(V) #V #define GEN_STR2(V) GEN_STR(V) #define BC_VERSION GEN_STR2(VERSION) #define BC_EXECPREFIX GEN_STR2(EXECPREFIX) #define BC_MAINEXEC GEN_STR2(MAINEXEC) // Windows has deprecated isatty(). #ifdef _WIN32 #define isatty _isatty #endif // _WIN32 #if DC_ENABLED #define DC_FLAG_X (UINTMAX_C(1)<<0) #endif // DC_ENABLED #if BC_ENABLED #define BC_FLAG_W (UINTMAX_C(1)<<1) #define BC_FLAG_S (UINTMAX_C(1)<<2) #define BC_FLAG_L (UINTMAX_C(1)<<3) #define BC_FLAG_G (UINTMAX_C(1)<<4) #endif // BC_ENABLED #define BC_FLAG_Q (UINTMAX_C(1)<<5) #define BC_FLAG_I (UINTMAX_C(1)<<6) #define BC_FLAG_P (UINTMAX_C(1)<<7) #define BC_FLAG_TTYIN (UINTMAX_C(1)<<8) #define BC_FLAG_TTY (UINTMAX_C(1)<<9) #define BC_TTYIN (vm.flags & BC_FLAG_TTYIN) #define BC_TTY (vm.flags & BC_FLAG_TTY) #if BC_ENABLED -#define BC_S (BC_ENABLED && (vm.flags & BC_FLAG_S)) -#define BC_W (BC_ENABLED && (vm.flags & BC_FLAG_W)) -#define BC_L (BC_ENABLED && (vm.flags & BC_FLAG_L)) -#define BC_G (BC_ENABLED && (vm.flags & BC_FLAG_G)) +#define BC_S (vm.flags & BC_FLAG_S) +#define BC_W (vm.flags & BC_FLAG_W) +#define BC_L (vm.flags & BC_FLAG_L) +#define BC_G (vm.flags & BC_FLAG_G) #endif // BC_ENABLED #if DC_ENABLED #define DC_X (vm.flags & DC_FLAG_X) #endif // DC_ENABLED #define BC_I (vm.flags & BC_FLAG_I) #define BC_P (vm.flags & BC_FLAG_P) #if BC_ENABLED #define BC_IS_POSIX (BC_S || BC_W) #if DC_ENABLED #define BC_IS_BC (vm.name[0] != 'd') #define BC_IS_DC (vm.name[0] == 'd') #else // DC_ENABLED #define BC_IS_BC (1) #define BC_IS_DC (0) #endif // DC_ENABLED #else // BC_ENABLED #define BC_IS_POSIX (0) #define BC_IS_BC (0) #define BC_IS_DC (1) #endif // BC_ENABLED #if BC_ENABLED #define BC_USE_PROMPT (!BC_P && BC_TTY && !BC_IS_POSIX) #else // BC_ENABLED #define BC_USE_PROMPT (!BC_P && BC_TTY) #endif // BC_ENABLED #define BC_MAX(a, b) ((a) > (b) ? (a) : (b)) #define BC_MIN(a, b) ((a) < (b) ? (a) : (b)) #define BC_MAX_OBASE ((BcBigDig) (BC_BASE_POW)) #define BC_MAX_DIM ((BcBigDig) (SIZE_MAX - 1)) #define BC_MAX_SCALE ((BcBigDig) (BC_NUM_BIGDIG_MAX - 1)) #define BC_MAX_STRING ((BcBigDig) (BC_NUM_BIGDIG_MAX - 1)) #define BC_MAX_NAME BC_MAX_STRING #define BC_MAX_NUM BC_MAX_SCALE #if BC_ENABLE_EXTRA_MATH #define BC_MAX_RAND ((BcBigDig) (((BcRand) 0) - 1)) #endif // BC_ENABLE_EXTRA_MATH #define BC_MAX_EXP ((ulong) (BC_NUM_BIGDIG_MAX)) #define BC_MAX_VARS ((ulong) (SIZE_MAX - 1)) #if BC_DEBUG_CODE #define BC_VM_JMP bc_vm_jmp(__func__) #else // BC_DEBUG_CODE #define BC_VM_JMP bc_vm_jmp() #endif // BC_DEBUG_CODE #define BC_SIG_EXC \ BC_UNLIKELY(vm.status != (sig_atomic_t) BC_STATUS_SUCCESS || vm.sig) #define BC_NO_SIG_EXC \ BC_LIKELY(vm.status == (sig_atomic_t) BC_STATUS_SUCCESS && !vm.sig) #ifndef NDEBUG #define BC_SIG_ASSERT_LOCKED do { assert(vm.sig_lock); } while (0) #define BC_SIG_ASSERT_NOT_LOCKED do { assert(vm.sig_lock == 0); } while (0) #else // NDEBUG #define BC_SIG_ASSERT_LOCKED #define BC_SIG_ASSERT_NOT_LOCKED #endif // NDEBUG #define BC_SIG_LOCK \ do { \ BC_SIG_ASSERT_NOT_LOCKED; \ vm.sig_lock = 1; \ } while (0) #define BC_SIG_UNLOCK \ do { \ BC_SIG_ASSERT_LOCKED; \ vm.sig_lock = 0; \ if (BC_SIG_EXC) BC_VM_JMP; \ } while (0) #define BC_SIG_MAYLOCK \ do { \ vm.sig_lock = 1; \ } while (0) #define BC_SIG_MAYUNLOCK \ do { \ vm.sig_lock = 0; \ if (BC_SIG_EXC) BC_VM_JMP; \ } while (0) #define BC_SIG_TRYLOCK(v) \ do { \ v = vm.sig_lock; \ vm.sig_lock = 1; \ } while (0) #define BC_SIG_TRYUNLOCK(v) \ do { \ vm.sig_lock = (v); \ if (!(v) && BC_SIG_EXC) BC_VM_JMP; \ } while (0) #define BC_SETJMP(l) \ do { \ sigjmp_buf sjb; \ BC_SIG_LOCK; \ if (sigsetjmp(sjb, 0)) { \ assert(BC_SIG_EXC); \ goto l; \ } \ bc_vec_push(&vm.jmp_bufs, &sjb); \ BC_SIG_UNLOCK; \ } while (0) #define BC_SETJMP_LOCKED(l) \ do { \ sigjmp_buf sjb; \ BC_SIG_ASSERT_LOCKED; \ if (sigsetjmp(sjb, 0)) { \ assert(BC_SIG_EXC); \ goto l; \ } \ bc_vec_push(&vm.jmp_bufs, &sjb); \ } while (0) #define BC_LONGJMP_CONT \ do { \ BC_SIG_ASSERT_LOCKED; \ if (!vm.sig_pop) bc_vec_pop(&vm.jmp_bufs); \ BC_SIG_UNLOCK; \ } while (0) #define BC_UNSETJMP \ do { \ BC_SIG_ASSERT_LOCKED; \ bc_vec_pop(&vm.jmp_bufs); \ } while (0) #define BC_LONGJMP_STOP \ do { \ vm.sig_pop = 0; \ vm.sig = 0; \ } while (0) #define BC_VM_BUF_SIZE (1<<12) #define BC_VM_STDOUT_BUF_SIZE (1<<11) #define BC_VM_STDERR_BUF_SIZE (1<<10) #define BC_VM_STDIN_BUF_SIZE (BC_VM_STDERR_BUF_SIZE - 1) #define BC_VM_SAFE_RESULT(r) ((r)->t >= BC_RESULT_TEMP) #define bc_vm_err(e) (bc_vm_error((e), 0)) #define bc_vm_verr(e, ...) (bc_vm_error((e), 0, __VA_ARGS__)) #define BC_STATUS_IS_ERROR(s) \ ((s) >= BC_STATUS_ERROR_MATH && (s) <= BC_STATUS_ERROR_FATAL) #define BC_VM_INVALID_CATALOG ((nl_catd) -1) // dc does not use is_stdin. #if !BC_ENABLED #define bc_vm_process(text, is_stdin) bc_vm_process(text) #else // BC_ENABLED #endif // BC_ENABLED typedef struct BcVm { volatile sig_atomic_t status; volatile sig_atomic_t sig_pop; BcParse prs; BcProgram prog; BcVec jmp_bufs; BcVec temps; const char* file; const char *sigmsg; volatile sig_atomic_t sig_lock; volatile sig_atomic_t sig; uchar siglen; uchar read_ret; uint16_t flags; uint16_t nchars; uint16_t line_len; bool eof; BcBigDig maxes[BC_PROG_GLOBALS_LEN + BC_ENABLE_EXTRA_MATH]; BcVec files; BcVec exprs; const char *name; const char *help; #if BC_ENABLE_HISTORY BcHistory history; #endif // BC_ENABLE_HISTORY BcLexNext next; BcParseParse parse; BcParseExpr expr; const char *func_header; const char *err_ids[BC_ERR_IDX_NELEMS + BC_ENABLED]; const char *err_msgs[BC_ERROR_NELEMS]; const char *locale; BcBigDig last_base; BcBigDig last_pow; BcBigDig last_exp; BcBigDig last_rem; char *env_args_buffer; BcVec env_args; BcNum max; BcDig max_num[BC_NUM_BIGDIG_LOG10]; BcFile fout; BcFile ferr; #if BC_ENABLE_NLS nl_catd catalog; #endif // BC_ENABLE_NLS char *buf; size_t buf_len; } BcVm; void bc_vm_info(const char* const help); void bc_vm_boot(int argc, char *argv[], const char *env_len, const char* const env_args, const char* env_exp_quit); void bc_vm_shutdown(void); void bc_vm_printf(const char *fmt, ...); void bc_vm_putchar(int c); size_t bc_vm_arraySize(size_t n, size_t size); size_t bc_vm_growSize(size_t a, size_t b); void* bc_vm_malloc(size_t n); void* bc_vm_realloc(void *ptr, size_t n); char* bc_vm_strdup(const char *str); #if BC_DEBUG_CODE void bc_vm_jmp(const char *f); #else // BC_DEBUG_CODE void bc_vm_jmp(void); #endif // BC_DEBUG_CODE void bc_vm_error(BcError e, size_t line, ...); extern const char bc_copyright[]; extern const char* const bc_err_line; extern const char* const bc_err_func_header; extern const char *bc_errs[]; extern const uchar bc_err_ids[]; extern const char* const bc_err_msgs[]; extern BcVm vm; extern char output_bufs[BC_VM_BUF_SIZE]; #endif // BC_VM_H Index: head/contrib/bc/locale_install.sh =================================================================== --- head/contrib/bc/locale_install.sh (revision 363090) +++ head/contrib/bc/locale_install.sh (revision 363091) @@ -1,230 +1,252 @@ #! /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() { + if [ $# -eq 1 ]; then + printf '%s\n' "$1" + fi printf "usage: %s NLSPATH main_exec [DESTDIR]\n" "$0" 1>&2 exit 1 } gencatfile() { _gencatfile_loc="$1" shift _gencatfile_file="$1" shift mkdir -p $(dirname "$_gencatfile_loc") gencat "$_gencatfile_loc" "$_gencatfile_file" > /dev/null 2>&1 } localeexists() { _localeexists_locales="$1" shift _localeexists_locale="$1" shift _localeexists_destdir="$1" shift if [ "$_localeexists_destdir" != "" ]; then _localeexists_char="@" _localeexists_locale="${_localeexists_locale%%_localeexists_char*}" _localeexists_char="." _localeexists_locale="${_localeexists_locale##*$_localeexists_char}" fi test ! -z "${_localeexists_locales##*$_localeexists_locale*}" return $? } splitpath() { _splitpath_path="$1" shift if [ "$_splitpath_path" = "${_splitpath_path#/}" ]; then printf 'Must use absolute paths\n' exit 1 fi if [ "${_splitpath_path#\n*}" != "$_splitpath_path" ]; then exit 1 fi _splitpath_list="" _splitpath_item="" while [ "$_splitpath_path" != "/" ]; do _splitpath_item=$(basename "$_splitpath_path") _splitpath_list=$(printf '\n%s%s' "$_splitpath_item" "$_splitpath_list") _splitpath_path=$(dirname "$_splitpath_path") done if [ "$_splitpath_list" != "/" ]; then _splitpath_list="${_splitpath_list#?}" fi printf '%s' "$_splitpath_list" } relpath() { _relpath_path1="$1" shift _relpath_path2="$1" shift _relpath_nl=$(printf '\nx') _relpath_nl="${_relpath_nl%x}" _relpath_splitpath1=`splitpath "$_relpath_path1"` _relpath_splitpath2=`splitpath "$_relpath_path2"` _relpath_path="" _relpath_temp1="$_relpath_splitpath1" IFS="$_relpath_nl" for _relpath_part in $_relpath_temp1; do _relpath_temp2="${_relpath_splitpath2#$_relpath_part$_relpath_nl}" if [ "$_relpath_temp2" = "$_relpath_splitpath2" ]; then break fi _relpath_splitpath2="$_relpath_temp2" _relpath_splitpath1="${_relpath_splitpath1#$_relpath_part$_relpath_nl}" done for _relpath_part in $_relpath_splitpath2; do _relpath_path="../$_relpath_path" done _relpath_path="${_relpath_path%../}" for _relpath_part in $_relpath_splitpath1; do _relpath_path="$_relpath_path$_relpath_part/" done _relpath_path="${_relpath_path%/}" unset IFS printf '%s\n' "$_relpath_path" } script="$0" scriptdir=$(dirname "$script") . "$scriptdir/functions.sh" +all_locales=0 + +while getopts "l" opt; do + + case "$opt" in + l) all_locales=1 ; shift ;; + ?) usage "Invalid option $opt" ;; + esac + +done + test "$#" -ge 2 || usage nlspath="$1" shift main_exec="$1" shift if [ "$#" -ge 1 ]; then destdir="$1" shift else destdir="" fi "$scriptdir/locale_uninstall.sh" "$nlspath" "$main_exec" "$destdir" locales_dir="$scriptdir/locales" # What this does is if installing to a package, it installs all locales that # match supported charsets instead of installing all directly supported locales. if [ "$destdir" = "" ]; then locales=$(locale -a) else locales=$(locale -m) fi for file in $locales_dir/*.msg; do locale=$(basename "$file" ".msg") - loc=$(gen_nlspath "$destdir/$nlspath" "$locale" "$main_exec") - localeexists "$locales" "$locale" "$destdir" - err="$?" + if [ "$all_locales" -eq 0 ]; then - if [ "$err" -eq 0 ]; then - continue + localeexists "$locales" "$locale" "$destdir" + err="$?" + + if [ "$err" -eq 0 ]; then + continue + fi fi if [ -L "$file" ]; then continue fi + loc=$(gen_nlspath "$destdir/$nlspath" "$locale" "$main_exec") + gencatfile "$loc" "$file" done for file in $locales_dir/*.msg; do locale=$(basename "$file" ".msg") - loc=$(gen_nlspath "$destdir/$nlspath" "$locale" "$main_exec") - localeexists "$locales" "$locale" "$destdir" - err="$?" + if [ "$all_locales" -eq 0 ]; then - if [ "$err" -eq 0 ]; then - continue + localeexists "$locales" "$locale" "$destdir" + err="$?" + + if [ "$err" -eq 0 ]; then + continue + fi fi + + loc=$(gen_nlspath "$destdir/$nlspath" "$locale" "$main_exec") mkdir -p $(dirname "$loc") if [ -L "$file" ]; then link=$(readlink "$file") linkdir=$(dirname "$file") locale=$(basename "$link" .msg) linksrc=$(gen_nlspath "$nlspath" "$locale" "$main_exec") relloc="${loc##$destdir/}" rel=$(relpath "$linksrc" "$relloc") if [ ! -f "$destdir/$linksrc" ]; then gencatfile "$destdir/$linksrc" "$linkdir/$link" fi ln -fs "$rel" "$loc" fi done Index: head/contrib/bc/locale_uninstall.sh =================================================================== --- head/contrib/bc/locale_uninstall.sh (revision 363090) +++ head/contrib/bc/locale_uninstall.sh (revision 363091) @@ -1,65 +1,66 @@ #! /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 NLSPATH main_exec [DESTDIR]\n" "$0" 1>&2 exit 1 } script="$0" scriptdir=$(dirname "$script") . "$scriptdir/functions.sh" INSTALL="$scriptdir/safe-install.sh" test "$#" -ge 2 || usage nlspath="$1" shift main_exec="$1" shift if [ "$#" -ge 1 ]; then destdir="$1" shift else destdir="" fi # I do something clever here. I am replacing the locale spot with # a wildcard, which should make it search all locale directories. # This way, we can delete catalogs for locales that we had to install # because they are symlinks. locales=$(gen_nlspath "$destdir/$nlspath" "*" "$main_exec") +locales=$(ls $locales 2> /dev/null) for l in $locales; do rm -f "$l" done Index: head/contrib/bc/manuals/build.md =================================================================== --- head/contrib/bc/manuals/build.md (revision 363090) +++ head/contrib/bc/manuals/build.md (revision 363091) @@ -1,671 +1,671 @@ # Build This `bc` attempts to be as portable as possible. It can be built on any POSIX-compliant system. To accomplish that, a POSIX-compatible, custom `configure.sh` script is used to select build options, compiler, and compiler flags and generate a `Makefile`. The general form of configuring, building, and installing this `bc` is as follows: ``` [ENVIRONMENT_VARIABLE=...] ./configure.sh [build_options...] make make install ``` To get all of the options, including any useful environment variables, use either one of the following commands: ``` ./configure.sh -h ./configure.sh --help ``` ***WARNING***: even though `configure.sh` supports both option types, short and long, it does not support handling both at the same time. Use only one type. To learn the available `make` targets run the following command after running the `configure.sh` script: ``` make help ``` See [Build Environment Variables][4] for a more detailed description of all accepted environment variables and [Build Options][5] for more detail about all accepted build options. ## Cross Compiling To cross-compile this `bc`, an appropriate compiler must be present and assigned to the environment variable `HOSTCC` or `HOST_CC` (the two are equivalent, though `HOSTCC` is prioritized). This is in order to bootstrap core file(s), if the architectures are not compatible (i.e., unlike i686 on x86_64). Thus, the approach is: ``` HOSTCC="/path/to/native/compiler" ./configure.sh make make install ``` `HOST_CC` will work in exactly the same way. `HOSTCFLAGS` and `HOST_CFLAGS` can be used to set compiler flags for `HOSTCC`. (The two are equivalent, as `HOSTCC` and `HOST_CC` are.) `HOSTCFLAGS` is prioritized over `HOST_CFLAGS`. If neither are present, `HOSTCC` (or `HOST_CC`) uses `CFLAGS` (see [Build Environment Variables][4] for more details). It is expected that `CC` produces code for the target system and `HOSTCC` produces code for the host system. See [Build Environment Variables][4] for more details. If an emulator is necessary to run the bootstrap binaries, it can be set with the environment variable `GEN_EMU`. ## Build Environment Variables This `bc` supports `CC`, `HOSTCC`, `HOST_CC`, `CFLAGS`, `HOSTCFLAGS`, `HOST_CFLAGS`, `CPPFLAGS`, `LDFLAGS`, `LDLIBS`, `PREFIX`, `DESTDIR`, `BINDIR`, `DATAROOTDIR`, `DATADIR`, `MANDIR`, `MAN1DIR`, `LOCALEDIR` `EXECSUFFIX`, `EXECPREFIX`, `LONG_BIT`, `GEN_HOST`, and `GEN_EMU` environment variables in `configure.sh`. Any values of those variables given to `configure.sh` will be put into the generated Makefile. More detail on what those environment variables do can be found in the following sections. ### `CC` C compiler for the target system. `CC` must be compatible with POSIX `c99` behavior and options. However, **I encourage users to use any C99 or C11 compatible compiler they wish.** If there is a space in the basename of the compiler, the items after the first space are assumed to be compiler flags, and in that case, the flags are automatically moved into CFLAGS. Defaults to `c99`. ### `HOSTCC` or `HOST_CC` C compiler for the host system, used only in [cross compiling][6]. Must be compatible with POSIX `c99` behavior and options. If there is a space in the basename of the compiler, the items after the first space are assumed to be compiler flags, and in that case, the flags are automatically moved into HOSTCFLAGS. Defaults to `$CC`. ### `CFLAGS` Command-line flags that will be passed verbatim to `CC`. Defaults to empty. ### `HOSTCFLAGS` or `HOST_CFLAGS` Command-line flags that will be passed verbatim to `HOSTCC` or `HOST_CC`. Defaults to `$CFLAGS`. ### `CPPFLAGS` Command-line flags for the C preprocessor. These are also passed verbatim to both compilers (`CC` and `HOSTCC`); they are supported just for legacy reasons. Defaults to empty. ### `LDFLAGS` Command-line flags for the linker. These are also passed verbatim to both compilers (`CC` and `HOSTCC`); they are supported just for legacy reasons. Defaults to empty. ### `LDLIBS` Libraries to link to. These are also passed verbatim to both compilers (`CC` and `HOSTCC`); they are supported just for legacy reasons and for cross compiling with different C standard libraries (like [musl][3]). Defaults to empty. ### `PREFIX` The prefix to install to. Can be overridden by passing the `--prefix` option to `configure.sh`. Defaults to `/usr/local`. ### `DESTDIR` Path to prepend onto `PREFIX`. This is mostly for distro and package maintainers. This can be passed either to `configure.sh` or `make install`. If it is passed to both, the one given to `configure.sh` takes precedence. Defaults to empty. ### `BINDIR` The directory to install binaries in. Can be overridden by passing the `--bindir` option to `configure.sh`. Defaults to `$PREFIX/bin`. ### `DATAROOTDIR` The root directory to install data files in. Can be overridden by passing the `--datarootdir` option to `configure.sh`. Defaults to `$PREFIX/share`. ### `DATADIR` The directory to install data files in. Can be overridden by passing the `--datadir` option to `configure.sh`. Defaults to `$DATAROOTDIR`. ### `MANDIR` The directory to install manpages in. Can be overridden by passing the `--mandir` option to `configure.sh`. Defaults to `$DATADIR/man` ### `MAN1DIR` The directory to install Section 1 manpages in. Because both `bc` and `dc` are Section 1 commands, this is the only relevant section directory. Can be overridden by passing the `--man1dir` option to `configure.sh`. Defaults to `$MANDIR/man1`. ### `LOCALEDIR` The directory to install locales in. Can be overridden by passing the `--localedir` option to `configure.sh`. Defaults to `$DATAROOTDIR/locale`. ### `EXECSUFFIX` The suffix to append onto the executable names *when installing*. This is for packagers and distro maintainers who want this `bc` as an option, but do not want to replace the default `bc`. Defaults to empty. ### `EXECPREFIX` The prefix to append onto the executable names *when building and installing*. This is for packagers and distro maintainers who want this `bc` as an option, but do not want to replace the default `bc`. Defaults to empty. ### `LONG_BIT` The number of bits in a C `long` type. This is mostly for the embedded space. This `bc` uses `long`s internally for overflow checking. In C99, a `long` is required to be 32 bits. For this reason, on 8-bit and 16-bit microcontrollers, the generated code to do math with `long` types may be inefficient. For most normal desktop systems, setting this is unnecessary, except that 32-bit platforms with 64-bit longs may want to set it to `32`. Defaults to the default value of `LONG_BIT` for the target platform. For compliance with the `bc` spec, the minimum allowed value is `32`. It is an error if the specified value is greater than the default value of `LONG_BIT` for the target platform. ### `GEN_HOST` Whether to use `gen/strgen.c`, instead of `gen/strgen.sh`, to produce the C files that contain the help texts as well as the math libraries. By default, `gen/strgen.c` is used, compiled by `$HOSTCC` and run on the host machine. Using `gen/strgen.sh` removes the need to compile and run an executable on the host machine since `gen/strgen.sh` is a POSIX shell script. However, `gen/lib2.bc` is perilously close to 4095 characters, the max supported length of a string literal in C99 (and it could be added to in the future), and `gen/strgen.sh` generates a string literal instead of an array, as `gen/strgen.c` does. For most production-ready compilers, this limit probably is not enforced, but it could be. Both options are still available for this reason. If you are sure your compiler does not have the limit and do not want to compile and run a binary on the host machine, set this variable to "0". Any other value, or a non-existent value, will cause the build system to compile and run `gen/strgen.c`. Default is "". ### `GEN_EMU` The emulator to run bootstrap binaries under. This is only if the binaries produced by `HOSTCC` (or `HOST_CC`) need to be run under an emulator to work. Defaults to empty. ## Build Options This `bc` comes with several build options, all of which are enabled by default. All options can be used with each other, with a few exceptions that will be noted below. **NOTE**: All long options with mandatory argumenst accept either one of the following forms: ``` --option arg --option=arg ``` ### `bc` Only To build `bc` only (no `dc`), use any one of the following commands for the configure step: ``` ./configure.sh -b ./configure.sh --bc-only ./configure.sh -D ./configure.sh --disable-dc ``` Those commands are all equivalent. ***Warning***: It is an error to use those options if `bc` has also been disabled (see below). ### `dc` Only To build `dc` only (no `bc`), use either one of the following commands for the configure step: ``` ./configure.sh -d ./configure.sh --dc-only ./configure.sh -B ./configure.sh --disable-bc ``` Those commands are all equivalent. ***Warning***: It is an error to use those options if `dc` has also been disabled (see above). ### History To disable signal handling, pass either the `-H` flag or the `--disable-history` option to `configure.sh`, as follows: ``` ./configure.sh -H ./configure.sh --disable-history ``` Both commands are equivalent. History is automatically disabled when building for Windows or on another platform that does not support the terminal handling that is required. ***WARNING***: Of all of the code in the `bc`, this is the only code that is not completely portable. If the `bc` does not work on your platform, your first step should be to retry with history disabled. ### NLS (Locale Support) To disable locale support (use only English), pass either the `-N` flag or the `--disable-nls` option to `configure.sh`, as follows: ``` ./configure.sh -N ./configure.sh --disable-nls ``` Both commands are equivalent. NLS (locale support) is automatically disabled when building for Windows or on another platform that does not support the POSIX locale API or utilities. ### Prompt By default, `bc` and `dc` print a prompt when in interactive mode. They both have the command-line option `-P`/`--no-prompt`, which turns that off, but it can be disabled permanently in the build by passing the `-P` flag or the `--disable-prompt` option to `configure.sh`, as follows: ``` ./configure.sh -P ./configure.sh --disable-prompt ``` Both commands are equivalent. -### Long Options +### Locales -By default, `bc` and `dc` support long options like `--mathlib` and -`--interactive`. However, support for these options requires `getopt_long()` -which is not in the POSIX standard. For those platforms that do *not* have -`getopt_long()` it will be disabled automatically, or if you wish to disable -them regardless, you can pass the `-L` flag or the `--disable-long-options` -option to `configure.sh`, as follows: +By default, `bc` and `dc` do not install all locales, but only the enabled +locales. If `DESTDIR` exists and is not empty, then they will install all of +the locales that exist on the system. The `-l` flag or `--install-all-locales` +option skips all of that and just installs all of the locales that `bc` and `dc` +have, regardless. To enable that behavior, you can pass the `-l` flag or the +`--install-all-locales` option to `configure.sh`, as follows: ``` -./configure.sh -L -./configure.sh --disable-long-options +./configure.sh -l +./configure.sh --install-all-locales ``` Both commands are equivalent. ### Extra Math This `bc` has 7 extra operators: * `$` (truncation to integer) * `@` (set precision) * `@=` (set precision and assign) * `<<` (shift number left, shifts radix right) * `<<=` (shift number left and assign) * `>>` (shift number right, shifts radix left) * `>>=` (shift number right and assign) There is no assignment version of `$` because it is a unary operator. The assignment versions of the above operators are not available in `dc`, but the others are, as the operators `$`, `@`, `H`, and `h`, respectively. In addition, this `bc` has the option of outputting in scientific notation or engineering notation. It can also take input in scientific or engineering notation. On top of that, it has a pseudo-random number generator. (See the full manual for more details.) Extra operators, scientific notation, engineering notation, and the pseudo-random number generator can be disabled by passing either the `-E` flag or the `--disable-extra-math` option to `configure.sh`, as follows: ``` ./configure.sh -E ./configure.sh --disable-extra-math ``` Both commands are equivalent. This `bc` also has a larger library that is only enabled if extra operators and the pseudo-random number generator are. More information about the functions can be found in the Extended Library section of the full manual. ### Manpages To disable installing manpages, pass either the `-M` flag or the `--disable-man-pages` option to `configure.sh` as follows: ``` ./configure.sh -M ./configure.sh --disable-man-pages ``` Both commands are equivalent. ### Karatsuba Length The Karatsuba length is the point at which `bc` and `dc` switch from Karatsuba multiplication to brute force, `O(n^2)` multiplication. It can be set by passing the `-k` flag or the `--karatsuba-len` option to `configure.sh` as follows: ``` ./configure.sh -k64 ./configure.sh --karatsuba-len 64 ``` Both commands are equivalent. Default is `64`. ***WARNING***: The Karatsuba Length must be a **integer** greater than or equal to `16` (to prevent stack overflow). If it is not, `configure.sh` will give an error. ### Install Options The relevant `autotools`-style install options are supported in `configure.sh`: * `--prefix` * `--bindir` * `--datarootdir` * `--datadir` * `--mandir` * `--man1dir` * `--localedir` An example is: ``` ./configure.sh --prefix=/usr --localedir /usr/share/nls make make install ``` They correspond to the environment variables `$PREFIX`, `$BINDIR`, `$DATAROOTDIR`, `$DATADIR`, `$MANDIR`, `$MAN1DIR`, and `$LOCALEDIR`, respectively. ***WARNING***: If the option is given, the value of the corresponding environment variable is overridden. ***WARNING***: If any long command-line options are used, the long form of all other command-line options must be used. Mixing long and short options is not supported. ## Optimization The `configure.sh` script will accept an optimization level to pass to the compiler. Because `bc` is orders of magnitude faster with optimization, I ***highly*** recommend package and distro maintainers pass the highest optimization level available in `CC` to `configure.sh` with the `-O` flag or `--opt` option, as follows: ``` ./configure.sh -O3 ./configure.sh --opt 3 ``` Both commands are equivalent. The build and install can then be run as normal: ``` make make install ``` As usual, `configure.sh` will also accept additional `CFLAGS` on the command line, so for SSE4 architectures, the following can add a bit more speed: ``` CFLAGS="-march=native -msse4" ./configure.sh -O3 make make install ``` Building with link-time optimization (`-flto` in clang) can further increase the performance. I ***highly*** recommend doing so. I do **NOT*** recommend building with `-march=native`; doing so reduces this `bc`'s performance. Manual stripping is not necessary; non-debug builds are automatically stripped in the link stage. ## Debug Builds Debug builds (which also disable optimization if no optimization level is given and if no extra `CFLAGS` are given) can be enabled with either the `-g` flag or the `--debug` option, as follows: ``` ./configure.sh -g ./configure.sh --debug ``` Both commands are equivalent. The build and install can then be run as normal: ``` make make install ``` ## Stripping Binaries By default, when `bc` and `dc` are not built in debug mode, the binaries are stripped. Stripping can be disabled with either the `-T` or the `--disable-strip` option, as follows: ``` ./configure.sh -T ./configure.sh --disable-strip ``` Both commands are equivalent. The build and install can then be run as normal: ``` make make install ``` ## Binary Size When built with both calculators, all available features, and `-Os` using `clang` and `musl`, the executable is 140.4 kb (140,386 bytes) on `x86_64`. That isn't much for what is contained in the binary, but if necessary, it can be reduced. The single largest user of space is the `bc` calculator. If just `dc` is needed, the size can be reduced to 107.6 kb (107,584 bytes). The next largest user of space is history support. If that is not needed, size can be reduced (for a build with both calculators) to 119.9 kb (119,866 bytes). There are several reasons that history is a bigger user of space than `dc` itself: * `dc`'s lexer and parser are *tiny* compared to `bc`'s because `dc` code is almost already in the form that it is executed in, while `bc` has to not only adjust the form to be executable, it has to parse functions, loops, `if` statements, and other extra features. * `dc` does not have much extra code in the interpreter. * History has a lot of const data for supporting `UTF-8` terminals. * History pulls in a bunch of more code from the `libc`. The next biggest user is extra math support. Without it, the size is reduced to 124.0 kb (123,986 bytes) with history and 107.6 kb (107,560 bytes) without history. The reasons why extra math support is bigger than `dc`, besides the fact that `dc` is small already, are: * Extra math supports adds an extra math library that takes several kilobytes of constant data space. * Extra math support includes support for a pseudo-random number generator, including the code to convert a series of pseudo-random numbers into a number of arbitrary size. * Extra math support adds several operators. The next biggest user is `dc`, so if just `bc` is needed, the size can be reduced to 128.1 kb (128,096 bytes) with history and extra math support, 107.6 kb (107,576 bytes) without history and with extra math support, and 95.3 kb (95,272 bytes) without history and without extra math support. *Note*: all of these binary sizes were compiled using `musl` `1.2.0` as the `libc`, making a fully static executable, with `clang` `9.0.1` (well, `musl-clang` using `clang` `9.0.1`) as the compiler and using `-Os` optimizations. These builds were done on an `x86_64` machine running Gentoo Linux. ## Testing The default test suite can be run with the following command: ``` make test ``` To test `bc` only, run the following command: ``` make test_bc ``` To test `dc` only, run the following command: ``` make test_dc ``` This `bc`, if built, assumes a working, GNU-compatible `bc`, installed on the system and in the `PATH`, to generate some tests, unless the `-G` flag or `--disable-generated-tests` option is given to `configure.sh`, as follows: ``` ./configure.sh -G ./configure.sh --disable-generated-tests ``` After running `configure.sh`, build and run tests as follows: ``` make make test ``` This `dc` also assumes a working, GNU-compatible `dc`, installed on the system and in the `PATH`, to generate some tests, unless one of the above options is given to `configure.sh`. To generate test coverage, pass the `-c` flag or the `--coverage` option to `configure.sh` as follows: ``` ./configure.sh -c ./configure.sh --coverage ``` Both commands are equivalent. ***WARNING***: Both `bc` and `dc` must be built for test coverage. Otherwise, `configure.sh` will give an error. [1]: https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html [2]: https://www.gnu.org/software/bc/ [3]: https://www.musl-libc.org/ [4]: #build-environment-variables [5]: #build-options [6]: #cross-compiling Index: head/contrib/bc/src/vm.c =================================================================== --- head/contrib/bc/src/vm.c (revision 363090) +++ head/contrib/bc/src/vm.c (revision 363091) @@ -1,858 +1,871 @@ /* * ***************************************************************************** * * 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 common to all of bc and dc. * */ #include #include #include #include #include #include #include #ifndef _WIN32 #include #include #else // _WIN32 #define WIN32_LEAN_AND_MEAN #include #include #endif // _WIN32 #include #include #include #include #include #include #if BC_DEBUG_CODE BC_NORETURN void bc_vm_jmp(const char* f) { #else // BC_DEBUG_CODE BC_NORETURN void bc_vm_jmp(void) { #endif assert(BC_SIG_EXC); BC_SIG_MAYLOCK; #if BC_DEBUG_CODE bc_file_puts(&vm.ferr, "Longjmp: "); bc_file_puts(&vm.ferr, f); bc_file_putchar(&vm.ferr, '\n'); bc_file_flush(&vm.ferr); #endif // BC_DEBUG_CODE #ifndef NDEBUG assert(vm.jmp_bufs.len - (size_t) vm.sig_pop); #endif // NDEBUG if (vm.sig_pop) bc_vec_pop(&vm.jmp_bufs); else vm.sig_pop = 1; siglongjmp(*((sigjmp_buf*) bc_vec_top(&vm.jmp_bufs)), 1); } static void bc_vm_sig(int sig) { // There is already a signal in flight. if (vm.status == (sig_atomic_t) BC_STATUS_QUIT || vm.sig) { if (!BC_TTY || sig != SIGINT) vm.status = BC_STATUS_QUIT; return; } if (BC_TTY && sig == SIGINT) { int err = errno; if (write(STDOUT_FILENO, vm.sigmsg, vm.siglen) != (ssize_t) vm.siglen) vm.status = BC_STATUS_ERROR_FATAL; else vm.sig = 1; errno = err; } else vm.status = BC_STATUS_QUIT; assert(vm.jmp_bufs.len); if (!vm.sig_lock) BC_VM_JMP; } void bc_vm_info(const char* const help) { BC_SIG_ASSERT_LOCKED; bc_file_puts(&vm.fout, vm.name); bc_file_putchar(&vm.fout, ' '); bc_file_puts(&vm.fout, BC_VERSION); bc_file_putchar(&vm.fout, '\n'); bc_file_puts(&vm.fout, bc_copyright); if (help) { bc_file_putchar(&vm.fout, '\n'); bc_file_printf(&vm.fout, help, vm.name, vm.name); } bc_file_flush(&vm.fout); } void bc_vm_error(BcError e, size_t line, ...) { BcStatus s; va_list args; uchar id = bc_err_ids[e]; const char* err_type = vm.err_ids[id]; sig_atomic_t lock; assert(e < BC_ERROR_NELEMS); assert(!vm.sig_pop); #if BC_ENABLED if (!BC_S && e >= BC_ERROR_POSIX_START) { if (BC_W) { // Make sure to not return an error. id = UCHAR_MAX; err_type = vm.err_ids[BC_ERR_IDX_WARN]; } else return; } #endif // BC_ENABLED BC_SIG_TRYLOCK(lock); // Make sure all of stdout is written first. s = bc_file_flushErr(&vm.fout); if (BC_ERR(s == BC_STATUS_ERROR_FATAL)) { vm.status = (sig_atomic_t) s; BC_VM_JMP; } va_start(args, line); bc_file_putchar(&vm.ferr, '\n'); bc_file_puts(&vm.ferr, err_type); bc_file_putchar(&vm.ferr, ' '); bc_file_vprintf(&vm.ferr, vm.err_msgs[e], args); va_end(args); if (BC_NO_ERR(vm.file)) { // This is the condition for parsing vs runtime. // If line is not 0, it is parsing. if (line) { bc_file_puts(&vm.ferr, "\n "); bc_file_puts(&vm.ferr, vm.file); bc_file_printf(&vm.ferr, bc_err_line, line); } else { BcInstPtr *ip = bc_vec_item_rev(&vm.prog.stack, 0); BcFunc *f = bc_vec_item(&vm.prog.fns, ip->func); bc_file_puts(&vm.ferr, "\n "); bc_file_puts(&vm.ferr, vm.func_header); bc_file_putchar(&vm.ferr, ' '); bc_file_puts(&vm.ferr, f->name); #if BC_ENABLED if (BC_IS_BC && ip->func != BC_PROG_MAIN && ip->func != BC_PROG_READ) { bc_file_puts(&vm.ferr, "()"); } #endif // BC_ENABLED } } bc_file_puts(&vm.ferr, "\n\n"); s = bc_file_flushErr(&vm.ferr); vm.status = s == BC_STATUS_ERROR_FATAL ? (sig_atomic_t) s : (sig_atomic_t) (uchar) (id + 1); if (BC_ERR(vm.status)) BC_VM_JMP; BC_SIG_TRYUNLOCK(lock); } static void bc_vm_envArgs(const char* const env_args_name) { char *env_args = getenv(env_args_name), *buf, *start; char instr = '\0'; BC_SIG_ASSERT_LOCKED; if (env_args == NULL) return; start = buf = vm.env_args_buffer = bc_vm_strdup(env_args); assert(buf != NULL); bc_vec_init(&vm.env_args, sizeof(char*), NULL); bc_vec_push(&vm.env_args, &env_args_name); while (*buf) { if (!isspace(*buf)) { if (*buf == '"' || *buf == '\'') { instr = *buf; buf += 1; if (*buf == instr) { instr = '\0'; buf += 1; continue; } } bc_vec_push(&vm.env_args, &buf); while (*buf && ((!instr && !isspace(*buf)) || (instr && *buf != instr))) { buf += 1; } if (*buf) { if (instr) instr = '\0'; *buf = '\0'; buf += 1; start = buf; } else if (instr) bc_vm_error(BC_ERROR_FATAL_OPTION, 0, start); } else buf += 1; } // Make sure to push a NULL pointer at the end. buf = NULL; bc_vec_push(&vm.env_args, &buf); bc_args((int) vm.env_args.len - 1, bc_vec_item(&vm.env_args, 0)); } static size_t bc_vm_envLen(const char *var) { char *lenv = getenv(var); size_t i, len = BC_NUM_PRINT_WIDTH; int num; if (lenv == NULL) return len; len = strlen(lenv); for (num = 1, i = 0; num && i < len; ++i) num = isdigit(lenv[i]); if (num) { len = (size_t) atoi(lenv) - 1; if (len < 2 || len >= UINT16_MAX) len = BC_NUM_PRINT_WIDTH; } else len = BC_NUM_PRINT_WIDTH; return len; } void bc_vm_shutdown(void) { BC_SIG_ASSERT_LOCKED; #if BC_ENABLE_NLS if (vm.catalog != BC_VM_INVALID_CATALOG) catclose(vm.catalog); #endif // BC_ENABLE_NLS #if BC_ENABLE_HISTORY // This must always run to ensure that the terminal is back to normal. if (BC_TTY) bc_history_free(&vm.history); #endif // BC_ENABLE_HISTORY #ifndef NDEBUG bc_vec_free(&vm.env_args); free(vm.env_args_buffer); bc_vec_free(&vm.files); bc_vec_free(&vm.exprs); bc_program_free(&vm.prog); bc_parse_free(&vm.prs); { size_t i; for (i = 0; i < vm.temps.len; ++i) free(((BcNum*) bc_vec_item(&vm.temps, i))->num); bc_vec_free(&vm.temps); } #endif // NDEBUG bc_file_free(&vm.fout); bc_file_free(&vm.ferr); } inline size_t bc_vm_arraySize(size_t n, size_t size) { size_t res = n * size; if (BC_ERR(res >= SIZE_MAX || (n != 0 && res / n != size))) bc_vm_err(BC_ERROR_FATAL_ALLOC_ERR); return res; } inline size_t bc_vm_growSize(size_t a, size_t b) { size_t res = a + b; if (BC_ERR(res >= SIZE_MAX || res < a || res < b)) bc_vm_err(BC_ERROR_FATAL_ALLOC_ERR); return res; } void* bc_vm_malloc(size_t n) { void* ptr; BC_SIG_ASSERT_LOCKED; ptr = malloc(n); if (BC_ERR(ptr == NULL)) bc_vm_err(BC_ERROR_FATAL_ALLOC_ERR); return ptr; } void* bc_vm_realloc(void *ptr, size_t n) { void* temp; BC_SIG_ASSERT_LOCKED; temp = realloc(ptr, n); if (BC_ERR(temp == NULL)) bc_vm_err(BC_ERROR_FATAL_ALLOC_ERR); return temp; } char* bc_vm_strdup(const char *str) { char *s; BC_SIG_ASSERT_LOCKED; s = strdup(str); if (BC_ERR(!s)) bc_vm_err(BC_ERROR_FATAL_ALLOC_ERR); return s; } void bc_vm_printf(const char *fmt, ...) { va_list args; BC_SIG_LOCK; va_start(args, fmt); bc_file_vprintf(&vm.fout, fmt, args); va_end(args); vm.nchars = 0; BC_SIG_UNLOCK; } void bc_vm_putchar(int c) { bc_file_putchar(&vm.fout, (uchar) c); vm.nchars = (c == '\n' ? 0 : vm.nchars + 1); } static void bc_vm_clean(void) { BcVec *fns = &vm.prog.fns; BcFunc *f = bc_vec_item(fns, BC_PROG_MAIN); BcInstPtr *ip = bc_vec_item(&vm.prog.stack, 0); bool good = ((vm.status && vm.status != BC_STATUS_QUIT) || vm.sig); if (good) bc_program_reset(&vm.prog); #if BC_ENABLED if (good && BC_IS_BC) good = !BC_PARSE_NO_EXEC(&vm.prs); #endif // BC_ENABLED #if DC_ENABLED if (BC_IS_DC) { size_t i; good = true; for (i = 0; good && i < vm.prog.results.len; ++i) { BcResult *r = (BcResult*) bc_vec_item(&vm.prog.results, i); good = BC_VM_SAFE_RESULT(r); } } #endif // DC_ENABLED // If this condition is true, we can get rid of strings, // constants, and code. This is an idea from busybox. if (good && vm.prog.stack.len == 1 && ip->idx == f->code.len) { #if BC_ENABLED if (BC_IS_BC) { bc_vec_npop(&f->labels, f->labels.len); bc_vec_npop(&f->strs, f->strs.len); bc_vec_npop(&f->consts, f->consts.len); } #endif // BC_ENABLED #if DC_ENABLED // Note to self: you cannot delete strings and functions. Deal with it. if (BC_IS_DC) bc_vec_npop(vm.prog.consts, vm.prog.consts->len); #endif // DC_ENABLED bc_vec_npop(&f->code, f->code.len); ip->idx = 0; } } static void bc_vm_process(const char *text, bool is_stdin) { bc_parse_text(&vm.prs, text); do { #if BC_ENABLED if (vm.prs.l.t == BC_LEX_KW_DEFINE) vm.parse(&vm.prs); #endif // BC_ENABLED while (BC_PARSE_CAN_PARSE(vm.prs)) vm.parse(&vm.prs); #if BC_ENABLED if (BC_IS_BC) { uint16_t *flags = BC_PARSE_TOP_FLAG_PTR(&vm.prs); if (!is_stdin && vm.prs.flags.len == 1 && *flags == BC_PARSE_FLAG_IF_END) { bc_parse_noElse(&vm.prs); } if (BC_PARSE_NO_EXEC(&vm.prs)) return; } #endif // BC_ENABLED bc_program_exec(&vm.prog); assert(BC_IS_DC || vm.prog.results.len == 0); if (BC_I) bc_file_flush(&vm.fout); } while (vm.prs.l.t != BC_LEX_EOF); } static void bc_vm_file(const char *file) { char *data = NULL; assert(!vm.sig_pop); bc_lex_file(&vm.prs.l, file); BC_SIG_LOCK; bc_read_file(file, &data); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; bc_vm_process(data, false); #if BC_ENABLED if (BC_IS_BC && BC_ERR(BC_PARSE_NO_EXEC(&vm.prs))) bc_parse_err(&vm.prs, BC_ERROR_PARSE_BLOCK); #endif // BC_ENABLED err: BC_SIG_MAYLOCK; free(data); bc_vm_clean(); // bc_program_reset(), called by bc_vm_clean(), resets the status. // We want it to clear the sig_pop variable in case it was set. if (vm.status == (sig_atomic_t) BC_STATUS_SUCCESS) BC_LONGJMP_STOP; BC_LONGJMP_CONT; } static void bc_vm_stdin(void) { BcStatus s; BcVec buf, buffer; size_t string = 0; bool comment = false, hash = false; bc_lex_file(&vm.prs.l, bc_program_stdin_name); BC_SIG_LOCK; bc_vec_init(&buffer, sizeof(uchar), NULL); bc_vec_init(&buf, sizeof(uchar), NULL); bc_vec_pushByte(&buffer, '\0'); BC_SETJMP_LOCKED(err); BC_SIG_UNLOCK; restart: // This loop is complex because the vm tries not to send any lines that end // with a backslash to the parser. The reason for that is because the parser // treats a backslash+newline combo as whitespace, per the bc spec. In that // case, and for strings and comments, the parser will expect more stuff. while ((!(s = bc_read_line(&buf, ">>> ")) || (vm.eof = (s == BC_STATUS_EOF))) && buf.len > 1) { char c2, *str = buf.v; size_t i, len = buf.len - 1; for (i = 0; i < len; ++i) { bool notend = len > i + 1; uchar c = (uchar) str[i]; hash = (!comment && !string && ((hash && c != '\n') || (!hash && c == '#'))); if (!hash && !comment && (i - 1 > len || str[i - 1] != '\\')) { if (BC_IS_BC) string ^= (c == '"'); else if (c == ']') string -= 1; else if (c == '[') string += 1; } if (BC_IS_BC && !hash && !string && notend) { c2 = str[i + 1]; if (c == '/' && !comment && c2 == '*') { comment = true; i += 1; } else if (c == '*' && comment && c2 == '/') { comment = false; i += 1; } } } bc_vec_concat(&buffer, buf.v); if (string || comment) continue; if (len >= 2 && str[len - 2] == '\\' && str[len - 1] == '\n') continue; #if BC_ENABLE_HISTORY if (vm.history.stdin_has_data) continue; #endif // BC_ENABLE_HISTORY bc_vm_process(buffer.v, true); bc_vec_empty(&buffer); if (vm.eof) break; else bc_vm_clean(); } if (!BC_STATUS_IS_ERROR(s)) { if (BC_ERR(comment)) bc_parse_err(&vm.prs, BC_ERROR_PARSE_COMMENT); else if (BC_ERR(string)) bc_parse_err(&vm.prs, BC_ERROR_PARSE_STRING); #if BC_ENABLED - else if (BC_IS_BC && BC_ERR(BC_PARSE_NO_EXEC(&vm.prs))) - bc_parse_err(&vm.prs, BC_ERROR_PARSE_BLOCK); + else if (BC_IS_BC && BC_ERR(BC_PARSE_NO_EXEC(&vm.prs))) { + + size_t i; + bool good = true; + + for (i = 0; good && i < vm.prs.flags.len; ++i) { + uint16_t flag = *((uint16_t*) bc_vec_item(&vm.prs.flags, i)); + good = ((flag & BC_PARSE_FLAG_BRACE) != BC_PARSE_FLAG_BRACE); + } + + if (good) { + while (BC_PARSE_IF_END(&vm.prs)) bc_vm_process("else {}", true); + } + else bc_parse_err(&vm.prs, BC_ERROR_PARSE_BLOCK); + } #endif // BC_ENABLED } err: BC_SIG_MAYLOCK; bc_vm_clean(); vm.status = vm.status == BC_STATUS_ERROR_FATAL || vm.status == BC_STATUS_QUIT || !BC_I ? vm.status : BC_STATUS_SUCCESS; if (!vm.status && !vm.eof) { bc_vec_empty(&buffer); BC_LONGJMP_STOP; BC_SIG_UNLOCK; goto restart; } bc_vec_free(&buf); bc_vec_free(&buffer); BC_LONGJMP_CONT; } #if BC_ENABLED static void bc_vm_load(const char *name, const char *text) { bc_lex_file(&vm.prs.l, name); bc_parse_text(&vm.prs, text); while (vm.prs.l.t != BC_LEX_EOF) vm.parse(&vm.prs); } #endif // BC_ENABLED static void bc_vm_defaultMsgs(void) { size_t i; vm.func_header = bc_err_func_header; for (i = 0; i < BC_ERR_IDX_NELEMS + BC_ENABLED; ++i) vm.err_ids[i] = bc_errs[i]; for (i = 0; i < BC_ERROR_NELEMS; ++i) vm.err_msgs[i] = bc_err_msgs[i]; } static void bc_vm_gettext(void) { #if BC_ENABLE_NLS uchar id = 0; int set = 1, msg = 1; size_t i; if (vm.locale == NULL) { vm.catalog = BC_VM_INVALID_CATALOG; bc_vm_defaultMsgs(); return; } vm.catalog = catopen(BC_MAINEXEC, NL_CAT_LOCALE); if (vm.catalog == BC_VM_INVALID_CATALOG) { bc_vm_defaultMsgs(); return; } vm.func_header = catgets(vm.catalog, set, msg, bc_err_func_header); for (set += 1; msg <= BC_ERR_IDX_NELEMS + BC_ENABLED; ++msg) vm.err_ids[msg - 1] = catgets(vm.catalog, set, msg, bc_errs[msg - 1]); i = 0; id = bc_err_ids[i]; for (set = id + 3, msg = 1; i < BC_ERROR_NELEMS; ++i, ++msg) { if (id != bc_err_ids[i]) { msg = 1; id = bc_err_ids[i]; set = id + 3; } vm.err_msgs[i] = catgets(vm.catalog, set, msg, bc_err_msgs[i]); } #else // BC_ENABLE_NLS bc_vm_defaultMsgs(); #endif // BC_ENABLE_NLS } static void bc_vm_exec(const char* env_exp_exit) { size_t i; bool has_file = false; BcVec buf; #if BC_ENABLED if (BC_IS_BC && (vm.flags & BC_FLAG_L)) { bc_vm_load(bc_lib_name, bc_lib); #if BC_ENABLE_EXTRA_MATH if (!BC_IS_POSIX) bc_vm_load(bc_lib2_name, bc_lib2); #endif // BC_ENABLE_EXTRA_MATH } #endif // BC_ENABLED if (vm.exprs.len) { size_t len = vm.exprs.len - 1; bool more; BC_SIG_LOCK; bc_vec_init(&buf, sizeof(uchar), NULL); #ifndef NDEBUG BC_SETJMP_LOCKED(err); #endif // NDEBUG BC_SIG_UNLOCK; bc_lex_file(&vm.prs.l, bc_program_exprs_name); do { more = bc_read_buf(&buf, vm.exprs.v, &len); bc_vec_pushByte(&buf, '\0'); bc_vm_process(buf.v, false); bc_vec_npop(&buf, buf.len); } while (more); BC_SIG_LOCK; bc_vec_free(&buf); #ifndef NDEBUG BC_UNSETJMP; #endif // NDEBUG BC_SIG_UNLOCK; if (getenv(env_exp_exit) != NULL) return; } for (i = 0; i < vm.files.len; ++i) { char *path = *((char**) bc_vec_item(&vm.files, i)); if (!strcmp(path, "")) continue; has_file = true; bc_vm_file(path); } if (BC_IS_BC || !has_file) bc_vm_stdin(); // These are all protected by ifndef NDEBUG because if these are needed, bc is // goingi to exit anyway, and I see no reason to include this code in a release // build when the OS is going to free all of the resources anyway. #ifndef NDEBUG return; err: BC_SIG_MAYLOCK; bc_vec_free(&buf); BC_LONGJMP_CONT; #endif // NDEBUG } void bc_vm_boot(int argc, char *argv[], const char *env_len, const char* const env_args, const char* env_exp_exit) { int ttyin, ttyout, ttyerr; struct sigaction sa; BC_SIG_ASSERT_LOCKED; ttyin = isatty(STDIN_FILENO); ttyout = isatty(STDOUT_FILENO); ttyerr = isatty(STDERR_FILENO); vm.flags |= ttyin ? BC_FLAG_TTYIN : 0; vm.flags |= (ttyin != 0 && ttyout != 0 && ttyerr != 0) ? BC_FLAG_TTY : 0; vm.flags |= ttyin && ttyout ? BC_FLAG_I : 0; sigemptyset(&sa.sa_mask); sa.sa_handler = bc_vm_sig; sa.sa_flags = SA_NODEFER; sigaction(SIGTERM, &sa, NULL); sigaction(SIGQUIT, &sa, NULL); sigaction(SIGINT, &sa, NULL); #if BC_ENABLE_HISTORY if (BC_TTY) sigaction(SIGHUP, &sa, NULL); #endif // BC_ENABLE_HISTORY memcpy(vm.max_num, bc_num_bigdigMax, bc_num_bigdigMax_size * sizeof(BcDig)); bc_num_setup(&vm.max, vm.max_num, BC_NUM_BIGDIG_LOG10); vm.max.len = bc_num_bigdigMax_size; vm.file = NULL; bc_vm_gettext(); bc_file_init(&vm.ferr, STDERR_FILENO, output_bufs + BC_VM_STDOUT_BUF_SIZE, BC_VM_STDERR_BUF_SIZE); bc_file_init(&vm.fout, STDOUT_FILENO, output_bufs, BC_VM_STDOUT_BUF_SIZE); vm.buf = output_bufs + BC_VM_STDOUT_BUF_SIZE + BC_VM_STDERR_BUF_SIZE; vm.line_len = (uint16_t) bc_vm_envLen(env_len); bc_vec_clear(&vm.files); bc_vec_clear(&vm.exprs); bc_vec_init(&vm.temps, sizeof(BcNum), NULL); bc_program_init(&vm.prog); bc_parse_init(&vm.prs, &vm.prog, BC_PROG_MAIN); #if BC_ENABLE_HISTORY if (BC_TTY) bc_history_init(&vm.history); #endif // BC_ENABLE_HISTORY #if BC_ENABLED if (BC_IS_BC) vm.flags |= BC_FLAG_S * (getenv("POSIXLY_CORRECT") != NULL); #endif // BC_ENABLED bc_vm_envArgs(env_args); bc_args(argc, argv); #if BC_ENABLED if (BC_IS_POSIX) vm.flags &= ~(BC_FLAG_G); #endif // BC_ENABLED vm.maxes[BC_PROG_GLOBALS_IBASE] = BC_NUM_MAX_POSIX_IBASE; vm.maxes[BC_PROG_GLOBALS_OBASE] = BC_MAX_OBASE; vm.maxes[BC_PROG_GLOBALS_SCALE] = BC_MAX_SCALE; #if BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND vm.maxes[BC_PROG_MAX_RAND] = ((BcRand) 0) - 1; #endif // BC_ENABLE_EXTRA_MATH && BC_ENABLE_RAND #if BC_ENABLED if (BC_IS_BC && !BC_IS_POSIX) vm.maxes[BC_PROG_GLOBALS_IBASE] = BC_NUM_MAX_IBASE; #endif // BC_ENABLED if (BC_IS_BC && BC_I && !(vm.flags & BC_FLAG_Q)) bc_vm_info(NULL); BC_SIG_UNLOCK; bc_vm_exec(env_exp_exit); } Index: head/contrib/bc/tests/bc/stdin.txt =================================================================== --- head/contrib/bc/tests/bc/stdin.txt (revision 363090) +++ head/contrib/bc/tests/bc/stdin.txt (revision 363091) @@ -1,15 +1,16 @@ #stuff # "string in a hash comment" # /* comment in a hash comment */ 1 /* c */ + 2 "String /* with partial comment" "String /* with full comment */" 1 /* Comment with partial "string */ + 2 2 /* Comment with full "string" */ + 3 3 /* Comment with a # hash comment */ + 4 "String with a # hash comment" 1 + \ 2 i = 4 read() i *= 5 +if (1 < 3) 1 Index: head/contrib/bc/tests/bc/stdin_results.txt =================================================================== --- head/contrib/bc/tests/bc/stdin_results.txt (revision 363090) +++ head/contrib/bc/tests/bc/stdin_results.txt (revision 363091) @@ -1,6 +1,7 @@ 3 String /* with partial commentString /* with full comment */3 5 7 String with a # hash comment3 20 +1 Index: head/contrib/bc/tests/stdin.sh =================================================================== --- head/contrib/bc/tests/stdin.sh (revision 363090) +++ head/contrib/bc/tests/stdin.sh (revision 363091) @@ -1,73 +1,81 @@ #! /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. # set -e script="$0" testdir=$(dirname "$script") if [ "$#" -lt 1 ]; then printf 'usage: %s dir [exe [args...]]\n' "$0" printf 'valid dirs are:\n' printf '\n' cat "$testdir/all.txt" printf '\n' exit 1 fi d="$1" shift if [ "$#" -gt 0 ]; then exe="$1" shift else exe="$testdir/../bin/$d" fi out="$testdir/../.log_${d}_test.txt" if [ "$d" = "bc" ]; then options="-ilq" else options="-x" fi rm -f "$out" printf 'Running %s stdin tests...' "$d" cat "$testdir/$d/stdin.txt" | "$exe" "$@" "$options" > "$out" 2> /dev/null - diff "$testdir/$d/stdin_results.txt" "$out" + +if [ "$d" = "bc" ]; then + + cat "$testdir/$d/stdin1.txt" | "$exe" "$@" "$options" > "$out" 2> /dev/null + diff "$testdir/$d/stdin1_results.txt" "$out" + + cat "$testdir/$d/stdin2.txt" | "$exe" "$@" "$options" > "$out" 2> /dev/null + diff "$testdir/$d/stdin2_results.txt" "$out" +fi rm -f "$out1" printf 'pass\n' Index: head/contrib/bc =================================================================== --- head/contrib/bc (revision 363090) +++ head/contrib/bc (revision 363091) Property changes on: head/contrib/bc ___________________________________________________________________ Added: svn:mergeinfo ## -0,0 +0,1 ## Merged /vendor/bc/dist:r362987-363090