diff --git a/contrib/bc/NEWS.md b/contrib/bc/NEWS.md index c66e7b164c8a..c78bddd27e76 100644 --- a/contrib/bc/NEWS.md +++ b/contrib/bc/NEWS.md @@ -1,1095 +1,1104 @@ # News +## 4.0.2 + +This is a production release that fixes two bugs: + +1. If no files are used and the first statement on `stdin` is invalid, `scale` + would not be set to `20` even if `-l` was used. +2. When using history, `bc` failed to respond properly to `SIGSTOP` and + `SIGTSTP`. + ## 4.0.1 This is a production release that only adds one thing: flushing output when it is printed with a print statement. ## 4.0.0 This is a production release with many fixes, a new command-line option, and a big surprise: * A bug was fixed in `dc`'s `P` command where the item on the stack was *not* popped. * Various bugs in the manuals have been fixed. * A known bug was fixed where history did not interact well with prompts printed by user code without newlines. * A new command-line option, `-R` and `--no-read-prompt` was added to disable just the prompt when using `read()` (`bc`) or `?` (`dc`). * And finally, **official support for Windows was added**. The last item is why this is a major version bump. Currently, only one set of build options (extra math and prompt enabled, history and NLS/locale support disabled, both calculators enabled) is supported on Windows. However, both debug and release builds are supported. In addition, Windows builds are supported for the the library (`bcl`). For more details about how to build on Windows, see the [README][5] or the [build manual][13]. ## 3.3.4 This is a production release that fixes a small bug. The bug was that output was not flushed before a `read()` call, so prompts without a newline on the end were not flushed before the `read()` call. This is such a tiny bug that users only need to upgrade if they are affected. ## 3.3.3 This is a production release with one tweak and fixes for manuals. The tweak is that `length(0)` returns `1` instead of `0`. In `3.3.1`, I changed it so `length(0.x)`, where `x` could be any number of digits, returned the `scale`, but `length(0)` still returned `0` because I believe that `0` has `0` significant digits. After request of FreeBSD and considering the arguments of a mathematician, compatibility with other `bc`'s, and the expectations of users, I decided to make the change. The fixes for manuals fixed a bug where `--` was rendered as `-`. ## 3.3.2 This is a production release that fixes a divide-by-zero bug in `root()` in the [extended math library][16]. All previous versions with `root()` have the bug. ## 3.3.1 This is a production release that fixes a bug. The bug was in the reporting of number length when the value was 0. ## 3.3.0 This is a production release that changes one behavior and fixes documentation bugs. The changed behavior is the treatment of `-e` and `-f` when given through `BC_ENV_ARGS` or `DC_ENV_ARGS`. Now `bc` and `dc` do not exit when those options (or their equivalents) are given through those environment variables. However, `bc` and `dc` still exit when they or their equivalents are given on the command-line. ## 3.2.7 This is a production release that removes a small non-portable shell operation in `configure.sh`. This problem was only noticed on OpenBSD, not FreeBSD or Linux. Non-OpenBSD users do ***NOT*** need to upgrade, although NetBSD users may also need to upgrade. ## 3.2.6 This is a production release that fixes the build on FreeBSD. There was a syntax error in `configure.sh` that the Linux shell did not catch, and FreeBSD depends on the existence of `tests/all.sh`. All users that already upgraded to `3.2.5` should update to this release, with my apologies for the poor release of `3.2.5`. Other users should skip `3.2.5` in favor of this version. ## 3.2.5 This is a production release that fixes several bugs and adds a couple small things. The two most important bugs were bugs that causes `dc` to access memory out-of-bounds (crash in debug builds). This was found by upgrading to `afl++` from `afl`. Both were caused by a failure to distinguish between the same two cases. Another bug was the failure to put all of the licenses in the `LICENSE.md` file. Third, some warnings by `scan-build` were found and eliminated. This needed one big change: `bc` and `dc` now bail out as fast as possible on fatal errors instead of unwinding the stack. Fourth, the pseudo-random number now attempts to seed itself with `/dev/random` if `/dev/urandom` fails. Finally, this release has a few quality-of-life changes to the build system. The usage should not change at all; the only thing that changed was making sure the `Makefile.in` was written to rebuild properly when headers changed and to not rebuild when not necessary. ## 3.2.4 This is a production release that fixes a warning on `gcc` 6 or older, which does not have an attribute that is used. Users do ***NOT*** need to upgrade if they don't use `gcc` 6 or older. ## 3.2.3 This is a production release that fixes a bug in `gen/strgen.sh`. I recently changed `gen/strgen.c`, but I did not change `gen/strgen.sh`. Users that do not use `gen/strgen.sh` do not need to upgrade. ## 3.2.2 This is a production release that fixes a portability bug in `configure.sh`. The bug was using the GNU `find` extension `-wholename`. ## 3.2.1 This is a production release that has one fix for `bcl(3)`. It is technically not a bug fix since the behavior is undefined, but the `BclNumber`s that `bcl_divmod()` returns will be set to `BCL_ERROR_INVALID_NUM` if there is an error. Previously, they were not set. ## 3.2.0 This is a production release that has one bug fix and a major addition. The bug fix was a missing `auto` variable in the bessel `j()` function in the math library. The major addition is a way to build a version of `bc`'s math code as a library. This is done with the `-a` option to `configure.sh`. The API for the library can be read in `./manuals/bcl.3.md` or `man bcl` once the library is installed with `make install`. This library was requested by developers before I even finished version 1.0, but I could not figure out how to do it until now. If the library has API breaking changes, the major version of `bc` will be incremented. ## 3.1.6 This is a production release that fixes a new warning from Clang 12 for FreeBSD and also removes some possible undefined behavior found by UBSan that compilers did not seem to take advantage of. Users do ***NOT*** need to upgrade, if they do not want to. ## 3.1.5 This is a production release that fixes the Chinese locales (which caused `bc` to crash) and a crash caused by `bc` executing code when it should not have been able to. ***ALL USERS SHOULD UPGRADE.*** ## 3.1.4 This is a production release that fixes one bug, changes two behaviors, and removes one environment variable. The bug is like the one in the last release except it applies if files are being executed. I also made the fix more general. The behavior that was changed is that `bc` now exits when given `-e`, `-f`, `--expression` or `--file`. However, if the last one of those is `-f-` (using `stdin` as the file), `bc` does not exit. If `-f-` exists and is not the last of the `-e` and `-f` options (and equivalents), `bc` gives a fatal error and exits. Next, I removed the `BC_EXPR_EXIT` and `DC_EXPR_EXIT` environment variables since their use is not needed with the behavior change. Finally, I made it so `bc` does not print the header, though the `-q` and `--quiet` options were kept for compatibility with GNU `bc`. ## 3.1.3 This is a production release that fixes one minor bug: if `bc` was invoked like the following, it would error: ``` echo "if (1 < 3) 1" | bc ``` Unless users run into this bug, they do not need to upgrade, but it is suggested that they do. ## 3.1.2 This is a production release that adds a way to install *all* locales. Users do ***NOT*** need to upgrade. For package maintainers wishing to make use of the change, just pass `-l` to `configure.sh`. ## 3.1.1 This is a production release that adds two Spanish locales. Users do ***NOT*** need to upgrade, unless they want those locales. ## 3.1.0 This is a production release that adjusts one behavior, fixes eight bugs, and improves manpages for FreeBSD. Because this release fixes bugs, **users and package maintainers should update to this version as soon as possible**. The behavior that was adjusted was how code from the `-e` and `-f` arguments (and equivalents) were executed. They used to be executed as one big chunk, but in this release, they are now executed line-by-line. The first bug fix in how output to `stdout` was handled in `SIGINT`. If a `SIGINT` came in, the `stdout` buffer was not correctly flushed. In fact, a clean-up function was not getting called. This release fixes that bug. The second bug is in how `dc` handled input from `stdin`. This affected `bc` as well since it was a mishandling of the `stdin` buffer. The third fixed bug was that `bc` and `dc` could `abort()` (in debug mode) when receiving a `SIGTERM`. This one was a race condition with pushing and popping items onto and out of vectors. The fourth bug fixed was that `bc` could leave extra items on the stack and thus, not properly clean up some memory. (The memory would still get `free()`'ed, but it would not be `free()`'ed when it could have been.) The next two bugs were bugs in `bc`'s parser that caused crashes when executing the resulting code. The last two bugs were crashes in `dc` that resulted from mishandling of strings. The manpage improvement was done by switching from [ronn][20] to [Pandoc][21] to generate manpages. Pandoc generates much cleaner manpages and doesn't leave blank lines where they shouldn't be. ## 3.0.3 This is a production release that adds one new feature: specific manpages. Before this release, `bc` and `dc` only used one manpage each that referred to various build options. This release changes it so there is one manpage set per relevant build type. Each manual only has information about its particular build, and `configure.sh` selects the correct set for install. ## 3.0.2 This is a production release that adds `utf8` locale symlinks and removes an unused `auto` variable from the `ceil()` function in the [extended math library][16]. Users do ***NOT*** need to update unless they want the locales. ## 3.0.1 This is a production release with two small changes. Users do ***NOT*** need to upgrade to this release; however, if they haven't upgraded to `3.0.0` yet, it may be worthwhile to upgrade to this release. The first change is fixing a compiler warning on FreeBSD with strict warnings on. The second change is to make the new implementation of `ceil()` in `lib2.bc` much more efficient. ## 3.0.0 *Notes for package maintainers:* *First, the `2.7.0` release series saw a change in the option parsing. This made me change one error message and add a few others. The error message that was changed removed one format specifier. This means that `printf()` will seqfault on old locale files. Unfortunately, `bc` cannot use any locale files except the global ones that are already installed, so it will use the previous ones while running tests during install. **If `bc` segfaults while running arg tests when updating, it is because the global locale files have not been replaced. Make sure to either prevent the test suite from running on update or remove the old locale files before updating.** (Removing the locale files can be done with `make uninstall` or by running the `locale_uninstall.sh` 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/ diff --git a/contrib/bc/include/history.h b/contrib/bc/include/history.h index 469785a118a9..444a2a107ac5 100644 --- a/contrib/bc/include/history.h +++ b/contrib/bc/include/history.h @@ -1,261 +1,262 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2021 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. * * ***************************************************************************** * * Adapted from the following: * * linenoise.c -- guerrilla line editing library against the idea that a * line editing lib needs to be 20,000 lines of C code. * * You can find the original source code at: * http://github.com/antirez/linenoise * * You can find the fork that this code is based on at: * https://github.com/rain-1/linenoise-mob * * ------------------------------------------------------------------------ * * This code is also under the following license: * * Copyright (c) 2010-2016, Salvatore Sanfilippo * Copyright (c) 2010-2013, Pieter Noordhuis * * 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 line history. * */ #ifndef BC_HISTORY_H #define BC_HISTORY_H #ifndef BC_ENABLE_HISTORY #define BC_ENABLE_HISTORY (1) #endif // BC_ENABLE_HISTORY #if BC_ENABLE_HISTORY #ifdef _WIN32 #error History is not supported on Windows. #endif // _WIN32 #include #include #include #include #include #include #include #include #include #include #if BC_DEBUG_CODE #include #endif // BC_DEBUG_CODE #define BC_HIST_DEF_COLS (80) #define BC_HIST_MAX_LEN (128) #define BC_HIST_MAX_LINE (4095) #define BC_HIST_SEQ_SIZE (64) #define BC_HIST_BUF_LEN(h) ((h)->buf.len - 1) #define BC_HIST_READ(s, n) (bc_history_read((s), (n)) == -1) #define BC_HIST_NEXT (false) #define BC_HIST_PREV (true) #if BC_DEBUG_CODE #define BC_HISTORY_DEBUG_BUF_SIZE (1024) #define lndebug(...) \ do { \ if (bc_history_debug_fp.fd == 0) { \ bc_history_debug_buf = bc_vm_malloc(BC_HISTORY_DEBUG_BUF_SIZE); \ bc_file_init(&bc_history_debug_fp, \ open("/tmp/lndebug.txt", O_APPEND), \ BC_HISTORY_DEBUG_BUF_SIZE); \ bc_file_printf(&bc_history_debug_fp, \ "[%zu %zu %zu] p: %d, rows: %d, " \ "rpos: %d, max: %zu, oldmax: %d\n", \ l->len, l->pos, l->oldcolpos, plen, rows, rpos, \ l->maxrows, old_rows); \ } \ bc_file_printf(&bc_history_debug_fp, ", " __VA_ARGS__); \ bc_file_flush(&bc_history_debug_fp); \ } while (0) #else // BC_DEBUG_CODE #define lndebug(fmt, ...) #endif // BC_DEBUG_CODE #if !BC_ENABLE_PROMPT #define bc_history_line(h, vec, prompt) bc_history_line(h, vec) #define bc_history_raw(h, prompt) bc_history_raw(h) #define bc_history_edit(h, prompt) bc_history_edit(h) #endif // BC_ENABLE_PROMPT typedef enum BcHistoryAction { BC_ACTION_NULL = 0, BC_ACTION_CTRL_A = 1, BC_ACTION_CTRL_B = 2, BC_ACTION_CTRL_C = 3, BC_ACTION_CTRL_D = 4, BC_ACTION_CTRL_E = 5, BC_ACTION_CTRL_F = 6, BC_ACTION_CTRL_H = 8, BC_ACTION_TAB = 9, BC_ACTION_LINE_FEED = 10, BC_ACTION_CTRL_K = 11, BC_ACTION_CTRL_L = 12, BC_ACTION_ENTER = 13, BC_ACTION_CTRL_N = 14, BC_ACTION_CTRL_P = 16, + BC_ACTION_CTRL_S = 19, BC_ACTION_CTRL_T = 20, BC_ACTION_CTRL_U = 21, BC_ACTION_CTRL_W = 23, BC_ACTION_CTRL_Z = 26, BC_ACTION_ESC = 27, BC_ACTION_BACKSPACE = 127 } BcHistoryAction; /** * This represents the state during line editing. We pass this state * to functions implementing specific editing functionalities. */ typedef struct BcHistory { /// Edited line buffer. BcVec buf; /// The history. BcVec history; /// Any material printed without a trailing newline. BcVec extras; #if BC_ENABLE_PROMPT /// Prompt to display. const char *prompt; /// Prompt length. size_t plen; #endif // BC_ENABLE_PROMPT /// Prompt column length. size_t pcol; /// Current cursor position. size_t pos; /// Previous refresh cursor column position. size_t oldcolpos; /// Number of columns in terminal. size_t cols; /// The history index we are currently editing. size_t idx; /// The original terminal state. struct termios orig_termios; /// These next three are here because pahole found a 4 byte hole here. /// This is to signal that there is more, so we don't process yet. bool stdin_has_data; /// Whether we are in rawmode. bool rawMode; /// Whether the terminal is bad. bool badTerm; /// This is to check if stdin has more data. fd_set rdset; /// This is to check if stdin has more data. struct timespec ts; /// This is to check if stdin has more data. sigset_t sigmask; } BcHistory; BcStatus bc_history_line(BcHistory *h, BcVec *vec, const char *prompt); void bc_history_init(BcHistory *h); void bc_history_free(BcHistory *h); extern const char *bc_history_bad_terms[]; extern const char bc_history_tab[]; extern const size_t bc_history_tab_len; extern const char bc_history_ctrlc[]; extern const uint32_t bc_history_wchars[][2]; extern const size_t bc_history_wchars_len; extern const uint32_t bc_history_combo_chars[]; extern const size_t bc_history_combo_chars_len; #if BC_DEBUG_CODE extern BcFile bc_history_debug_fp; extern char *bc_history_debug_buf; void bc_history_printKeyCodes(BcHistory* l); #endif // BC_DEBUG_CODE #endif // BC_ENABLE_HISTORY #endif // BC_HISTORY_H diff --git a/contrib/bc/include/version.h b/contrib/bc/include/version.h index ab4823bd7c2a..42eb3a11d2c0 100644 --- a/contrib/bc/include/version.h +++ b/contrib/bc/include/version.h @@ -1,41 +1,41 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2021 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 processing command-line arguments. * */ #ifndef BC_VERSION_H #define BC_VERSION_H -#define VERSION 4.0.1 +#define VERSION 4.0.2 #endif // BC_VERSION_H diff --git a/contrib/bc/src/history.c b/contrib/bc/src/history.c index c0d54fe35234..317d9193036c 100644 --- a/contrib/bc/src/history.c +++ b/contrib/bc/src/history.c @@ -1,1465 +1,1468 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2021 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. * * ***************************************************************************** * * Adapted from the following: * * linenoise.c -- guerrilla line editing library against the idea that a * line editing lib needs to be 20,000 lines of C code. * * You can find the original source code at: * http://github.com/antirez/linenoise * * You can find the fork that this code is based on at: * https://github.com/rain-1/linenoise-mob * * ------------------------------------------------------------------------ * * This code is also under the following license: * * Copyright (c) 2010-2016, Salvatore Sanfilippo * Copyright (c) 2010-2013, Pieter Noordhuis * * 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. * * ------------------------------------------------------------------------ * * Does a number of crazy assumptions that happen to be true in 99.9999% of * the 2010 UNIX computers around. * * References: * - http://invisible-island.net/xterm/ctlseqs/ctlseqs.html * - http://www.3waylabs.com/nw/WWW/products/wizcon/vt220.html * * Todo list: * - Filter bogus Ctrl+ combinations. * - Win32 support * * Bloat: * - History search like Ctrl+r in readline? * * List of escape sequences used by this program, we do everything just * with three sequences. In order to be so cheap we may have some * flickering effect with some slow terminal, but the lesser sequences * the more compatible. * * EL (Erase Line) * Sequence: ESC [ n K * Effect: if n is 0 or missing, clear from cursor to end of line * Effect: if n is 1, clear from beginning of line to cursor * Effect: if n is 2, clear entire line * * CUF (CUrsor Forward) * Sequence: ESC [ n C * Effect: moves cursor forward n chars * * CUB (CUrsor Backward) * Sequence: ESC [ n D * Effect: moves cursor backward n chars * * The following is used to get the terminal width if getting * the width with the TIOCGWINSZ ioctl fails * * DSR (Device Status Report) * Sequence: ESC [ 6 n * Effect: reports the current cusor position as ESC [ n ; m R * where n is the row and m is the column * * When multi line mode is enabled, we also use two additional escape * sequences. However multi line editing is disabled by default. * * CUU (CUrsor Up) * Sequence: ESC [ n A * Effect: moves cursor up of n chars. * * CUD (CUrsor Down) * Sequence: ESC [ n B * Effect: moves cursor down of n chars. * * When bc_history_clearScreen() is called, two additional escape sequences * are used in order to clear the screen and position the cursor at home * position. * * CUP (CUrsor Position) * Sequence: ESC [ H * Effect: moves the cursor to upper left corner * * ED (Erase Display) * Sequence: ESC [ 2 J * Effect: clear the whole screen * * ***************************************************************************** * * Code for line history. * */ #if BC_ENABLE_HISTORY #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static void bc_history_add(BcHistory *h, char *line); static void bc_history_add_empty(BcHistory *h); /** * Check if the code is a wide character. */ static bool bc_history_wchar(uint32_t cp) { size_t i; for (i = 0; i < bc_history_wchars_len; ++i) { // Ranges are listed in ascending order. Therefore, once the // whole range is higher than the codepoint we're testing, the // codepoint won't be found in any remaining range => bail early. if (bc_history_wchars[i][0] > cp) return false; // Test this range. if (bc_history_wchars[i][0] <= cp && cp <= bc_history_wchars[i][1]) return true; } return false; } /** * Check if the code is a combining character. */ static bool bc_history_comboChar(uint32_t cp) { size_t i; for (i = 0; i < bc_history_combo_chars_len; ++i) { // Combining chars are listed in ascending order, so once we pass // the codepoint of interest, we know it's not a combining char. if (bc_history_combo_chars[i] > cp) return false; if (bc_history_combo_chars[i] == cp) return true; } return false; } /** * Get length of previous UTF8 character. */ static size_t bc_history_prevCharLen(const char *buf, size_t pos) { size_t end = pos; for (pos -= 1; pos < end && (buf[pos] & 0xC0) == 0x80; --pos); return end - (pos >= end ? 0 : pos); } /** * Convert UTF-8 to Unicode code point. */ static size_t bc_history_codePoint(const char *s, size_t len, uint32_t *cp) { if (len) { uchar byte = (uchar) s[0]; if ((byte & 0x80) == 0) { *cp = byte; return 1; } else if ((byte & 0xE0) == 0xC0) { if (len >= 2) { *cp = (((uint32_t) (s[0] & 0x1F)) << 6) | ((uint32_t) (s[1] & 0x3F)); return 2; } } else if ((byte & 0xF0) == 0xE0) { if (len >= 3) { *cp = (((uint32_t) (s[0] & 0x0F)) << 12) | (((uint32_t) (s[1] & 0x3F)) << 6) | ((uint32_t) (s[2] & 0x3F)); return 3; } } else if ((byte & 0xF8) == 0xF0) { if (len >= 4) { *cp = (((uint32_t) (s[0] & 0x07)) << 18) | (((uint32_t) (s[1] & 0x3F)) << 12) | (((uint32_t) (s[2] & 0x3F)) << 6) | ((uint32_t) (s[3] & 0x3F)); return 4; } } else { *cp = 0xFFFD; return 1; } } *cp = 0; return 1; } /** * Get length of next grapheme. */ static size_t bc_history_nextLen(const char *buf, size_t buf_len, size_t pos, size_t *col_len) { uint32_t cp; size_t beg = pos; size_t len = bc_history_codePoint(buf + pos, buf_len - pos, &cp); if (bc_history_comboChar(cp)) { // Currently unreachable? return 0; } if (col_len != NULL) *col_len = bc_history_wchar(cp) ? 2 : 1; pos += len; while (pos < buf_len) { len = bc_history_codePoint(buf + pos, buf_len - pos, &cp); if (!bc_history_comboChar(cp)) return pos - beg; pos += len; } return pos - beg; } /** * Get length of previous grapheme. */ static size_t bc_history_prevLen(const char *buf, size_t pos, size_t *col_len) { size_t end = pos; while (pos > 0) { uint32_t cp; size_t len = bc_history_prevCharLen(buf, pos); pos -= len; bc_history_codePoint(buf + pos, len, &cp); if (!bc_history_comboChar(cp)) { if (col_len != NULL) *col_len = 1 + (bc_history_wchar(cp) != 0); return end - pos; } } // Currently unreachable? return 0; } static ssize_t bc_history_read(char *buf, size_t n) { ssize_t ret; BC_SIG_LOCK; do { ret = read(STDIN_FILENO, buf, n); } while (ret == EINTR); BC_SIG_UNLOCK; return ret; } /** * Read a Unicode code point from a file. */ static BcStatus bc_history_readCode(char *buf, size_t buf_len, uint32_t *cp, size_t *nread) { ssize_t n; assert(buf_len >= 1); n = bc_history_read(buf, 1); if (BC_ERR(n <= 0)) goto err; uchar byte = (uchar) buf[0]; if ((byte & 0x80) != 0) { if ((byte & 0xE0) == 0xC0) { assert(buf_len >= 2); n = bc_history_read(buf + 1, 1); if (BC_ERR(n <= 0)) goto err; } else if ((byte & 0xF0) == 0xE0) { assert(buf_len >= 3); n = bc_history_read(buf + 1, 2); if (BC_ERR(n <= 0)) goto err; } else if ((byte & 0xF8) == 0xF0) { assert(buf_len >= 3); n = bc_history_read(buf + 1, 3); if (BC_ERR(n <= 0)) goto err; } else { n = -1; goto err; } } *nread = bc_history_codePoint(buf, buf_len, cp); return BC_STATUS_SUCCESS; err: if (BC_ERR(n < 0)) bc_vm_fatalError(BC_ERR_FATAL_IO_ERR); else *nread = (size_t) n; return BC_STATUS_EOF; } /** * Get column length from begining of buffer to current byte position. */ static size_t bc_history_colPos(const char *buf, size_t buf_len, size_t pos) { size_t ret = 0, off = 0; while (off < pos) { size_t col_len, len; len = bc_history_nextLen(buf, buf_len, off, &col_len); off += len; ret += col_len; } return ret; } /** * Return true if the terminal name is in the list of terminals we know are * not able to understand basic escape sequences. */ static inline bool bc_history_isBadTerm(void) { size_t i; char *term = getenv("TERM"); if (term == NULL) return false; for (i = 0; bc_history_bad_terms[i]; ++i) { if (!strcasecmp(term, bc_history_bad_terms[i])) return true; } return false; } /** * Raw mode: 1960's black magic. */ static void bc_history_enableRaw(BcHistory *h) { struct termios raw; int err; assert(BC_TTYIN); if (h->rawMode) return; BC_SIG_LOCK; if (BC_ERR(tcgetattr(STDIN_FILENO, &h->orig_termios) == -1)) bc_vm_fatalError(BC_ERR_FATAL_IO_ERR); BC_SIG_UNLOCK; // Modify the original mode. raw = h->orig_termios; // Input modes: no break, no CR to NL, no parity check, no strip char, // no start/stop output control. raw.c_iflag &= (unsigned int) (~(BRKINT | ICRNL | INPCK | ISTRIP | IXON)); // Control modes - set 8 bit chars. raw.c_cflag |= (CS8); // Local modes - choing off, canonical off, no extended functions, // no signal chars (^Z,^C). raw.c_lflag &= (unsigned int) (~(ECHO | ICANON | IEXTEN | ISIG)); // Control chars - set return condition: min number of bytes and timer. // We want read to give every single byte, w/o timeout (1 byte, no timer). raw.c_cc[VMIN] = 1; raw.c_cc[VTIME] = 0; BC_SIG_LOCK; // Put terminal in raw mode after flushing. do { err = tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw); } while (BC_ERR(err < 0) && errno == EINTR); BC_SIG_UNLOCK; if (BC_ERR(err < 0)) bc_vm_fatalError(BC_ERR_FATAL_IO_ERR); h->rawMode = true; } static void bc_history_disableRaw(BcHistory *h) { sig_atomic_t lock; // Don't even check the return value as it's too late. if (!h->rawMode) return; BC_SIG_TRYLOCK(lock); if (BC_ERR(tcsetattr(STDIN_FILENO, TCSAFLUSH, &h->orig_termios) != -1)) h->rawMode = false; BC_SIG_TRYUNLOCK(lock); } /** * Use the ESC [6n escape sequence to query the horizontal cursor position * and return it. On error -1 is returned, on success the position of the * cursor. */ static size_t bc_history_cursorPos(void) { char buf[BC_HIST_SEQ_SIZE]; char *ptr, *ptr2; size_t cols, rows, i; // Report cursor location. bc_file_write(&vm.fout, bc_flush_none, "\x1b[6n", 4); bc_file_flush(&vm.fout, bc_flush_none); // Read the response: ESC [ rows ; cols R. for (i = 0; i < sizeof(buf) - 1; ++i) { if (bc_history_read(buf + i, 1) != 1 || buf[i] == 'R') break; } buf[i] = '\0'; if (BC_ERR(buf[0] != BC_ACTION_ESC || buf[1] != '[')) return SIZE_MAX; // Parse it. ptr = buf + 2; rows = strtoul(ptr, &ptr2, 10); if (BC_ERR(!rows || ptr2[0] != ';')) return SIZE_MAX; ptr = ptr2 + 1; cols = strtoul(ptr, NULL, 10); if (BC_ERR(!cols)) return SIZE_MAX; return cols <= UINT16_MAX ? cols : 0; } /** * Try to get the number of columns in the current terminal, or assume 80 * if it fails. */ static size_t bc_history_columns(void) { struct winsize ws; int ret; BC_SIG_LOCK; ret = ioctl(vm.fout.fd, TIOCGWINSZ, &ws); BC_SIG_UNLOCK; if (BC_ERR(ret == -1 || !ws.ws_col)) { // Calling ioctl() failed. Try to query the terminal itself. size_t start, cols; // Get the initial position so we can restore it later. start = bc_history_cursorPos(); if (BC_ERR(start == SIZE_MAX)) return BC_HIST_DEF_COLS; // Go to right margin and get position. bc_file_write(&vm.fout, bc_flush_none, "\x1b[999C", 6); bc_file_flush(&vm.fout, bc_flush_none); cols = bc_history_cursorPos(); if (BC_ERR(cols == SIZE_MAX)) return BC_HIST_DEF_COLS; // Restore position. if (cols > start) { bc_file_printf(&vm.fout, "\x1b[%zuD", cols - start); bc_file_flush(&vm.fout, bc_flush_none); } return cols; } return ws.ws_col; } #if BC_ENABLE_PROMPT /** * Check if text is an ANSI escape sequence. */ static bool bc_history_ansiEscape(const char *buf, size_t buf_len, size_t *len) { if (buf_len > 2 && !memcmp("\033[", buf, 2)) { size_t off = 2; while (off < buf_len) { char c = buf[off++]; if ((c >= 'A' && c <= 'K' && c != 'I') || c == 'S' || c == 'T' || c == 'f' || c == 'm') { *len = off; return true; } } } return false; } /** * Get column length of prompt text. */ static size_t bc_history_promptColLen(const char *prompt, size_t plen) { char buf[BC_HIST_MAX_LINE + 1]; size_t buf_len = 0, off = 0; while (off < plen) { size_t len; if (bc_history_ansiEscape(prompt + off, plen - off, &len)) { off += len; continue; } buf[buf_len++] = prompt[off++]; } return bc_history_colPos(buf, buf_len, buf_len); } #endif // BC_ENABLE_PROMPT /** * Rewrites the currently edited line accordingly to the buffer content, * cursor position, and number of columns of the terminal. */ static void bc_history_refresh(BcHistory *h) { char* buf = h->buf.v; size_t colpos, len = BC_HIST_BUF_LEN(h), pos = h->pos; bc_file_flush(&vm.fout, bc_flush_none); while(h->pcol + bc_history_colPos(buf, len, pos) >= h->cols) { size_t chlen = bc_history_nextLen(buf, len, 0, NULL); buf += chlen; len -= chlen; pos -= chlen; } while (h->pcol + bc_history_colPos(buf, len, len) > h->cols) len -= bc_history_prevLen(buf, len, NULL); // Cursor to left edge. bc_file_write(&vm.fout, bc_flush_none, "\r", 1); // Take the extra stuff into account. if (h->extras.len > 1) { len += h->extras.len - 1; pos += h->extras.len - 1; bc_file_write(&vm.fout, bc_flush_none, h->extras.v, h->extras.len - 1); } // Write the prompt, if desired. #if BC_ENABLE_PROMPT if (BC_USE_PROMPT) bc_file_write(&vm.fout, bc_flush_none, h->prompt, h->plen); #endif // BC_ENABLE_PROMPT bc_file_write(&vm.fout, bc_flush_none, buf, BC_HIST_BUF_LEN(h)); // Erase to right. bc_file_write(&vm.fout, bc_flush_none, "\x1b[0K", 4); // Move cursor to original position. colpos = bc_history_colPos(buf, len, pos) + h->pcol; if (colpos) bc_file_printf(&vm.fout, "\r\x1b[%zuC", colpos); bc_file_flush(&vm.fout, bc_flush_none); } /** * Insert the character 'c' at cursor current position. */ static void bc_history_edit_insert(BcHistory *h, const char *cbuf, size_t clen) { bc_vec_grow(&h->buf, clen); if (h->pos == BC_HIST_BUF_LEN(h)) { size_t colpos = 0, len; memcpy(bc_vec_item(&h->buf, h->pos), cbuf, clen); h->pos += clen; h->buf.len += clen - 1; bc_vec_pushByte(&h->buf, '\0'); len = BC_HIST_BUF_LEN(h) + h->extras.len - 1; #if BC_ENABLE_PROMPT colpos = bc_history_promptColLen(h->prompt, h->plen); #endif // BC_ENABLE_PROMPT colpos += bc_history_colPos(h->buf.v, len, len); if (colpos < h->cols) { // Avoid a full update of the line in the trivial case. bc_file_write(&vm.fout, bc_flush_none, cbuf, clen); bc_file_flush(&vm.fout, bc_flush_none); } else bc_history_refresh(h); } else { size_t amt = BC_HIST_BUF_LEN(h) - h->pos; memmove(h->buf.v + h->pos + clen, h->buf.v + h->pos, amt); memcpy(h->buf.v + h->pos, cbuf, clen); h->pos += clen; h->buf.len += clen; h->buf.v[BC_HIST_BUF_LEN(h)] = '\0'; bc_history_refresh(h); } } /** * Move cursor to the left. */ static void bc_history_edit_left(BcHistory *h) { if (h->pos <= 0) return; h->pos -= bc_history_prevLen(h->buf.v, h->pos, NULL); bc_history_refresh(h); } /** * Move cursor on the right. */ static void bc_history_edit_right(BcHistory *h) { if (h->pos == BC_HIST_BUF_LEN(h)) return; h->pos += bc_history_nextLen(h->buf.v, BC_HIST_BUF_LEN(h), h->pos, NULL); bc_history_refresh(h); } /** * Move cursor to the end of the current word. */ static void bc_history_edit_wordEnd(BcHistory *h) { size_t len = BC_HIST_BUF_LEN(h); if (!len || h->pos >= len) return; while (h->pos < len && isspace(h->buf.v[h->pos])) h->pos += 1; while (h->pos < len && !isspace(h->buf.v[h->pos])) h->pos += 1; bc_history_refresh(h); } /** * Move cursor to the start of the current word. */ static void bc_history_edit_wordStart(BcHistory *h) { size_t len = BC_HIST_BUF_LEN(h); if (!len) return; while (h->pos > 0 && isspace(h->buf.v[h->pos - 1])) h->pos -= 1; while (h->pos > 0 && !isspace(h->buf.v[h->pos - 1])) h->pos -= 1; bc_history_refresh(h); } /** * Move cursor to the start of the line. */ static void bc_history_edit_home(BcHistory *h) { if (!h->pos) return; h->pos = 0; bc_history_refresh(h); } /** * Move cursor to the end of the line. */ static void bc_history_edit_end(BcHistory *h) { if (h->pos == BC_HIST_BUF_LEN(h)) return; h->pos = BC_HIST_BUF_LEN(h); bc_history_refresh(h); } /** * Substitute the currently edited line with the next or previous history * entry as specified by 'dir' (direction). */ static void bc_history_edit_next(BcHistory *h, bool dir) { const char *dup, *str; if (h->history.len <= 1) return; BC_SIG_LOCK; if (h->buf.v[0]) dup = bc_vm_strdup(h->buf.v); else dup = ""; // Update the current history entry before // overwriting it with the next one. bc_vec_replaceAt(&h->history, h->history.len - 1 - h->idx, &dup); BC_SIG_UNLOCK; // Show the new entry. h->idx += (dir == BC_HIST_PREV ? 1 : SIZE_MAX); if (h->idx == SIZE_MAX) { h->idx = 0; return; } else if (h->idx >= h->history.len) { h->idx = h->history.len - 1; return; } str = *((char**) bc_vec_item(&h->history, h->history.len - 1 - h->idx)); bc_vec_string(&h->buf, strlen(str), str); assert(h->buf.len > 0); h->pos = BC_HIST_BUF_LEN(h); bc_history_refresh(h); } /** * Delete the character at the right of the cursor without altering the cursor * position. Basically this is what happens with the "Delete" keyboard key. */ static void bc_history_edit_delete(BcHistory *h) { size_t chlen, len = BC_HIST_BUF_LEN(h); if (!len || h->pos >= len) return; chlen = bc_history_nextLen(h->buf.v, len, h->pos, NULL); memmove(h->buf.v + h->pos, h->buf.v + h->pos + chlen, len - h->pos - chlen); h->buf.len -= chlen; h->buf.v[BC_HIST_BUF_LEN(h)] = '\0'; bc_history_refresh(h); } static void bc_history_edit_backspace(BcHistory *h) { size_t chlen, len = BC_HIST_BUF_LEN(h); if (!h->pos || !len) return; chlen = bc_history_prevLen(h->buf.v, h->pos, NULL); memmove(h->buf.v + h->pos - chlen, h->buf.v + h->pos, len - h->pos); h->pos -= chlen; h->buf.len -= chlen; h->buf.v[BC_HIST_BUF_LEN(h)] = '\0'; bc_history_refresh(h); } /** * Delete the previous word, maintaining the cursor at the start of the * current word. */ static void bc_history_edit_deletePrevWord(BcHistory *h) { size_t diff, old_pos = h->pos; while (h->pos > 0 && h->buf.v[h->pos - 1] == ' ') --h->pos; while (h->pos > 0 && h->buf.v[h->pos - 1] != ' ') --h->pos; diff = old_pos - h->pos; memmove(h->buf.v + h->pos, h->buf.v + old_pos, BC_HIST_BUF_LEN(h) - old_pos + 1); h->buf.len -= diff; bc_history_refresh(h); } /** * Delete the next word, maintaining the cursor at the same position. */ static void bc_history_edit_deleteNextWord(BcHistory *h) { size_t next_end = h->pos, len = BC_HIST_BUF_LEN(h); while (next_end < len && h->buf.v[next_end] == ' ') ++next_end; while (next_end < len && h->buf.v[next_end] != ' ') ++next_end; memmove(h->buf.v + h->pos, h->buf.v + next_end, len - next_end); h->buf.len -= next_end - h->pos; bc_history_refresh(h); } static void bc_history_swap(BcHistory *h) { size_t pcl, ncl; char auxb[5]; pcl = bc_history_prevLen(h->buf.v, h->pos, NULL); ncl = bc_history_nextLen(h->buf.v, BC_HIST_BUF_LEN(h), h->pos, NULL); // To perform a swap we need: // * nonzero char length to the left // * not at the end of the line if (pcl && h->pos != BC_HIST_BUF_LEN(h) && pcl < 5 && ncl < 5) { memcpy(auxb, h->buf.v + h->pos - pcl, pcl); memcpy(h->buf.v + h->pos - pcl, h->buf.v + h->pos, ncl); memcpy(h->buf.v + h->pos - pcl + ncl, auxb, pcl); h->pos += -pcl + ncl; bc_history_refresh(h); } } /** * Handle escape sequences. */ static void bc_history_escape(BcHistory *h) { char c, seq[3]; if (BC_ERR(BC_HIST_READ(seq, 1))) return; c = seq[0]; // ESC ? sequences. if (c != '[' && c != 'O') { if (c == 'f') bc_history_edit_wordEnd(h); else if (c == 'b') bc_history_edit_wordStart(h); else if (c == 'd') bc_history_edit_deleteNextWord(h); } else { if (BC_ERR(BC_HIST_READ(seq + 1, 1))) bc_vm_fatalError(BC_ERR_FATAL_IO_ERR); // ESC [ sequences. if (c == '[') { c = seq[1]; if (c >= '0' && c <= '9') { // Extended escape, read additional byte. if (BC_ERR(BC_HIST_READ(seq + 2, 1))) bc_vm_fatalError(BC_ERR_FATAL_IO_ERR); if (seq[2] == '~' && c == '3') bc_history_edit_delete(h); else if(seq[2] == ';') { if (BC_ERR(BC_HIST_READ(seq, 2))) bc_vm_fatalError(BC_ERR_FATAL_IO_ERR); if (seq[0] != '5') return; else if (seq[1] == 'C') bc_history_edit_wordEnd(h); else if (seq[1] == 'D') bc_history_edit_wordStart(h); } } else { switch(c) { // Up. case 'A': { bc_history_edit_next(h, BC_HIST_PREV); break; } // Down. case 'B': { bc_history_edit_next(h, BC_HIST_NEXT); break; } // Right. case 'C': { bc_history_edit_right(h); break; } // Left. case 'D': { bc_history_edit_left(h); break; } // Home. case 'H': case '1': { bc_history_edit_home(h); break; } // End. case 'F': case '4': { bc_history_edit_end(h); break; } case 'd': { bc_history_edit_deleteNextWord(h); break; } } } } // ESC O sequences. else if (c == 'O') { switch (seq[1]) { case 'A': { bc_history_edit_next(h, BC_HIST_PREV); break; } case 'B': { bc_history_edit_next(h, BC_HIST_NEXT); break; } case 'C': { bc_history_edit_right(h); break; } case 'D': { bc_history_edit_left(h); break; } case 'F': { bc_history_edit_end(h); break; } case 'H': { bc_history_edit_home(h); break; } } } } } static void bc_history_reset(BcHistory *h) { h->oldcolpos = h->pos = h->idx = 0; h->cols = bc_history_columns(); // The latest history entry is always our current buffer, that // initially is just an empty string. bc_history_add_empty(h); // Buffer starts empty. bc_vec_empty(&h->buf); } static void bc_history_printCtrl(BcHistory *h, unsigned int c) { char str[3] = "^A"; const char newline[2] = "\n"; str[1] = (char) (c + 'A' - BC_ACTION_CTRL_A); bc_vec_concat(&h->buf, str); bc_history_refresh(h); bc_vec_npop(&h->buf, sizeof(str)); bc_vec_pushByte(&h->buf, '\0'); if (c != BC_ACTION_CTRL_C && c != BC_ACTION_CTRL_D) { bc_file_write(&vm.fout, bc_flush_none, newline, sizeof(newline) - 1); bc_history_refresh(h); } } /** * This function is the core of the line editing capability of bc history. * It expects 'fd' to be already in "raw mode" so that every key pressed * will be returned ASAP to read(). */ static BcStatus bc_history_edit(BcHistory *h, const char *prompt) { bc_history_reset(h); // Don't write the saved output the first time. This is because it has // already been written to output. In other words, don't uncomment the // line below or add anything like it. // bc_file_write(&vm.fout, bc_flush_none, h->extras.v, h->extras.len - 1); #if BC_ENABLE_PROMPT if (BC_USE_PROMPT) { h->prompt = prompt; h->plen = strlen(prompt); h->pcol = bc_history_promptColLen(prompt, h->plen); bc_file_write(&vm.fout, bc_flush_none, prompt, h->plen); bc_file_flush(&vm.fout, bc_flush_none); } #endif // BC_ENABLE_PROMPT for (;;) { BcStatus s; // Large enough for any encoding? char cbuf[32]; unsigned int c = 0; size_t nread = 0; s = bc_history_readCode(cbuf, sizeof(cbuf), &c, &nread); if (BC_ERR(s)) return s; switch (c) { case BC_ACTION_LINE_FEED: case BC_ACTION_ENTER: { bc_vec_pop(&h->history); return s; } case BC_ACTION_TAB: { memcpy(cbuf, bc_history_tab, bc_history_tab_len + 1); bc_history_edit_insert(h, cbuf, bc_history_tab_len); break; } case BC_ACTION_CTRL_C: { bc_history_printCtrl(h, c); bc_file_write(&vm.fout, bc_flush_none, vm.sigmsg, vm.siglen); bc_file_write(&vm.fout, bc_flush_none, bc_program_ready_msg, bc_program_ready_msg_len); bc_history_reset(h); bc_history_refresh(h); break; } case BC_ACTION_BACKSPACE: case BC_ACTION_CTRL_H: { bc_history_edit_backspace(h); break; } // Act as end-of-file. case BC_ACTION_CTRL_D: { bc_history_printCtrl(h, c); return BC_STATUS_EOF; } // Swaps current character with previous. case BC_ACTION_CTRL_T: { bc_history_swap(h); break; } case BC_ACTION_CTRL_B: { bc_history_edit_left(h); break; } case BC_ACTION_CTRL_F: { bc_history_edit_right(h); break; } case BC_ACTION_CTRL_P: { bc_history_edit_next(h, BC_HIST_PREV); break; } case BC_ACTION_CTRL_N: { bc_history_edit_next(h, BC_HIST_NEXT); break; } case BC_ACTION_ESC: { bc_history_escape(h); break; } // Delete the whole line. case BC_ACTION_CTRL_U: { bc_vec_string(&h->buf, 0, ""); h->pos = 0; bc_history_refresh(h); break; } // Delete from current to end of line. case BC_ACTION_CTRL_K: { bc_vec_npop(&h->buf, h->buf.len - h->pos); bc_vec_pushByte(&h->buf, '\0'); bc_history_refresh(h); break; } // Go to the start of the line. case BC_ACTION_CTRL_A: { bc_history_edit_home(h); break; } // Go to the end of the line. case BC_ACTION_CTRL_E: { bc_history_edit_end(h); break; } // Clear screen. case BC_ACTION_CTRL_L: { bc_file_write(&vm.fout, bc_flush_none, "\x1b[H\x1b[2J", 7); bc_history_refresh(h); break; } // Delete previous word. case BC_ACTION_CTRL_W: { bc_history_edit_deletePrevWord(h); break; } default: { - if (c >= BC_ACTION_CTRL_A && c <= BC_ACTION_CTRL_Z) + if (c >= BC_ACTION_CTRL_A && c <= BC_ACTION_CTRL_Z) { bc_history_printCtrl(h, c); + if (c == BC_ACTION_CTRL_Z) raise(SIGTSTP); + if (c == BC_ACTION_CTRL_S) raise(SIGSTOP); + } else bc_history_edit_insert(h, cbuf, nread); break; } } } return BC_STATUS_SUCCESS; } static inline bool bc_history_stdinHasData(BcHistory *h) { int n; return pselect(1, &h->rdset, NULL, NULL, &h->ts, &h->sigmask) > 0 || (ioctl(STDIN_FILENO, FIONREAD, &n) >= 0 && n > 0); } /** * This function calls the line editing function bc_history_edit() * using the STDIN file descriptor set in raw mode. */ static BcStatus bc_history_raw(BcHistory *h, const char *prompt) { BcStatus s; assert(vm.fout.len == 0); bc_history_enableRaw(h); s = bc_history_edit(h, prompt); h->stdin_has_data = bc_history_stdinHasData(h); if (!h->stdin_has_data) bc_history_disableRaw(h); bc_file_write(&vm.fout, bc_flush_none, "\n", 1); bc_file_flush(&vm.fout, bc_flush_none); return s; } BcStatus bc_history_line(BcHistory *h, BcVec *vec, const char *prompt) { BcStatus s; char* line; s = bc_history_raw(h, prompt); assert(!s || s == BC_STATUS_EOF); bc_vec_string(vec, BC_HIST_BUF_LEN(h), h->buf.v); if (h->buf.v[0]) { BC_SIG_LOCK; line = bc_vm_strdup(h->buf.v); BC_SIG_UNLOCK; bc_history_add(h, line); } else bc_history_add_empty(h); bc_vec_concat(vec, "\n"); return s; } static void bc_history_add(BcHistory *h, char *line) { if (h->history.len) { char *s = *((char**) bc_vec_item_rev(&h->history, 0)); if (!strcmp(s, line)) { BC_SIG_LOCK; free(line); BC_SIG_UNLOCK; return; } } bc_vec_push(&h->history, &line); } static void bc_history_add_empty(BcHistory *h) { const char *line = ""; if (h->history.len) { char *s = *((char**) bc_vec_item_rev(&h->history, 0)); if (!s[0]) return; } bc_vec_push(&h->history, &line); } static void bc_history_string_free(void *str) { char *s = *((char**) str); BC_SIG_ASSERT_LOCKED; if (s[0]) free(s); } void bc_history_init(BcHistory *h) { BC_SIG_ASSERT_LOCKED; bc_vec_init(&h->buf, sizeof(char), NULL); bc_vec_init(&h->history, sizeof(char*), bc_history_string_free); bc_vec_init(&h->extras, sizeof(char), NULL); FD_ZERO(&h->rdset); FD_SET(STDIN_FILENO, &h->rdset); h->ts.tv_sec = 0; h->ts.tv_nsec = 0; sigemptyset(&h->sigmask); sigaddset(&h->sigmask, SIGINT); h->rawMode = h->stdin_has_data = false; h->badTerm = bc_history_isBadTerm(); } void bc_history_free(BcHistory *h) { BC_SIG_ASSERT_LOCKED; bc_history_disableRaw(h); #ifndef NDEBUG bc_vec_free(&h->buf); bc_vec_free(&h->history); bc_vec_free(&h->extras); #endif // NDEBUG } /** * This special mode is used by bc history in order to print scan codes * on screen for debugging / development purposes. */ #if BC_DEBUG_CODE void bc_history_printKeyCodes(BcHistory *h) { char quit[4]; bc_vm_printf("Linenoise key codes debugging mode.\n" "Press keys to see scan codes. " "Type 'quit' at any time to exit.\n"); bc_history_enableRaw(h); memset(quit, ' ', 4); while(true) { char c; ssize_t nread; nread = bc_history_read(&c, 1); if (nread <= 0) continue; // Shift string to left. memmove(quit, quit + 1, sizeof(quit) - 1); // Insert current char on the right. quit[sizeof(quit) - 1] = c; if (!memcmp(quit, "quit", sizeof(quit))) break; bc_vm_printf("'%c' %lu (type quit to exit)\n", isprint(c) ? c : '?', (unsigned long) c); // Go left edge manually, we are in raw mode. bc_vm_putchar('\r', bc_flush_none); bc_file_flush(&vm.fout, bc_flush_none); } bc_history_disableRaw(h); } #endif // BC_DEBUG_CODE #endif // BC_ENABLE_HISTORY diff --git a/contrib/bc/src/vm.c b/contrib/bc/src/vm.c index e7ee8d35ba54..d01c8fd6860f 100644 --- a/contrib/bc/src/vm.c +++ b/contrib/bc/src/vm.c @@ -1,1021 +1,1023 @@ /* * ***************************************************************************** * * SPDX-License-Identifier: BSD-2-Clause * * Copyright (c) 2018-2021 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 char output_bufs[BC_VM_BUF_SIZE]; BcVm vm; #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, bc_flush_none, "Longjmp: "); bc_file_puts(&vm.ferr, bc_flush_none, f); bc_file_putchar(&vm.ferr, bc_flush_none, '\n'); bc_file_flush(&vm.ferr, bc_flush_none); #endif // BC_DEBUG_CODE #ifndef NDEBUG assert(vm.jmp_bufs.len - (size_t) vm.sig_pop); #endif // NDEBUG if (vm.jmp_bufs.len == 0) abort(); if (vm.sig_pop) bc_vec_pop(&vm.jmp_bufs); else vm.sig_pop = 1; siglongjmp(*((sigjmp_buf*) bc_vec_top(&vm.jmp_bufs)), 1); } #if !BC_ENABLE_LIBRARY 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; } static void bc_vm_sigaction(void) { #ifndef _WIN32 struct sigaction sa; 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 #else // _WIN32 signal(SIGTERM, bc_vm_sig); #endif // _WIN32 } void bc_vm_info(const char* const help) { BC_SIG_ASSERT_LOCKED; bc_file_puts(&vm.fout, bc_flush_none, vm.name); bc_file_putchar(&vm.fout, bc_flush_none, ' '); bc_file_puts(&vm.fout, bc_flush_none, BC_VERSION); bc_file_putchar(&vm.fout, bc_flush_none, '\n'); bc_file_puts(&vm.fout, bc_flush_none, bc_copyright); if (help) { bc_file_putchar(&vm.fout, bc_flush_none, '\n'); bc_file_printf(&vm.fout, help, vm.name, vm.name, BC_VERSION, BC_BUILD_TYPE); } bc_file_flush(&vm.fout, bc_flush_err); } #endif // !BC_ENABLE_LIBRARY #if !BC_ENABLE_LIBRARY && !BC_ENABLE_MEMCHECK BC_NORETURN #endif // !BC_ENABLE_LIBRARY && !BC_ENABLE_MEMCHECK void bc_vm_fatalError(BcErr e) { bc_vm_err(e); #if !BC_ENABLE_LIBRARY && !BC_ENABLE_MEMCHECK abort(); #endif // !BC_ENABLE_LIBRARY && !BC_ENABLE_MEMCHECK } #if BC_ENABLE_LIBRARY void bc_vm_handleError(BcErr e) { assert(e < BC_ERR_NELEMS); assert(!vm.sig_pop); BC_SIG_LOCK; if (e <= BC_ERR_MATH_DIVIDE_BY_ZERO) { vm.err = (BclError) (e - BC_ERR_MATH_NEGATIVE + BCL_ERROR_MATH_NEGATIVE); } else if (vm.abrt) abort(); else if (e == BC_ERR_FATAL_ALLOC_ERR) vm.err = BCL_ERROR_FATAL_ALLOC_ERR; else vm.err = BCL_ERROR_FATAL_UNKNOWN_ERR; BC_VM_JMP; } #else // BC_ENABLE_LIBRARY void bc_vm_handleError(BcErr 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_ERR_NELEMS); assert(!vm.sig_pop); #if BC_ENABLED if (!BC_S && e >= BC_ERR_POSIX_START) { if (BC_W) { // Make sure to not return an error. id = UCHAR_MAX; err_type = vm.err_ids[BC_ERR_IDX_WARN]; } else return; } #endif // BC_ENABLED BC_SIG_TRYLOCK(lock); // Make sure all of stdout is written first. s = bc_file_flushErr(&vm.fout, bc_flush_err); 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, bc_flush_none, '\n'); bc_file_puts(&vm.ferr, bc_flush_none, err_type); bc_file_putchar(&vm.ferr, bc_flush_none, ' '); bc_file_vprintf(&vm.ferr, vm.err_msgs[e], args); va_end(args); 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, bc_flush_none, "\n "); bc_file_puts(&vm.ferr, bc_flush_none, 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, bc_flush_none, "\n "); bc_file_puts(&vm.ferr, bc_flush_none, vm.func_header); bc_file_putchar(&vm.ferr, bc_flush_none, ' '); bc_file_puts(&vm.ferr, bc_flush_none, f->name); #if BC_ENABLED if (BC_IS_BC && ip->func != BC_PROG_MAIN && ip->func != BC_PROG_READ) { bc_file_puts(&vm.ferr, bc_flush_none, "()"); } #endif // BC_ENABLED } } bc_file_puts(&vm.ferr, bc_flush_none, "\n\n"); s = bc_file_flushErr(&vm.ferr, bc_flush_err); #if !BC_ENABLE_MEMCHECK // Because this function is called by a BC_NORETURN function when fatal // errors happen, we need to make sure to exit on fatal errors. This will // be faster anyway. This function *cannot jump when a fatal error occurs!* if (BC_ERR(id == BC_ERR_IDX_FATAL || s == BC_STATUS_ERROR_FATAL)) exit(bc_vm_atexit((int) BC_STATUS_ERROR_FATAL)); #else // !BC_ENABLE_MEMCHECK if (BC_ERR(s == BC_STATUS_ERROR_FATAL)) vm.status = (sig_atomic_t) s; else #endif // !BC_ENABLE_MEMCHECK { vm.status = (sig_atomic_t) (uchar) (id + 1); } 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 = bc_vm_getenv(env_args_name), *buf, *start; char instr = '\0'; BC_SIG_ASSERT_LOCKED; if (env_args == NULL) return; // Windows already allocates, so we don't need to. #ifndef _WIN32 start = buf = vm.env_args_buffer = bc_vm_strdup(env_args); #else // _WIN32 start = buf = vm.env_args_buffer = env_args; #endif // _WIN32 assert(buf != NULL); 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_ERR_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), false); } static size_t bc_vm_envLen(const char *var) { char *lenv = bc_vm_getenv(var); size_t i, len = BC_NUM_PRINT_WIDTH; int num; 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; bc_vm_getenvFree(lenv); return len; } #endif // BC_ENABLE_LIBRARY void bc_vm_shutdown(void) { BC_SIG_ASSERT_LOCKED; #if BC_ENABLE_NLS if (vm.catalog != BC_VM_INVALID_CATALOG) catclose(vm.catalog); #endif // BC_ENABLE_NLS #if BC_ENABLE_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 #if !BC_ENABLE_LIBRARY bc_vec_free(&vm.env_args); free(vm.env_args_buffer); bc_vec_free(&vm.files); bc_vec_free(&vm.exprs); bc_program_free(&vm.prog); bc_parse_free(&vm.prs); #endif // !BC_ENABLE_LIBRARY bc_vm_freeTemps(); bc_vec_free(&vm.temps); #endif // NDEBUG #if !BC_ENABLE_LIBRARY bc_file_free(&vm.fout); bc_file_free(&vm.ferr); #endif // !BC_ENABLE_LIBRARY } #if !defined(NDEBUG) || BC_ENABLE_LIBRARY void bc_vm_freeTemps(void) { size_t i; for (i = 0; i < vm.temps.len; ++i) { free(((BcNum*) bc_vec_item(&vm.temps, i))->num); } } #endif // !defined(NDEBUG) || BC_ENABLE_LIBRARY 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_fatalError(BC_ERR_FATAL_ALLOC_ERR); return res; } inline size_t bc_vm_growSize(size_t a, size_t b) { size_t res = a + b; if (BC_ERR(res >= SIZE_MAX || res < a || res < b)) bc_vm_fatalError(BC_ERR_FATAL_ALLOC_ERR); return res; } void* bc_vm_malloc(size_t n) { void* ptr; BC_SIG_ASSERT_LOCKED; ptr = malloc(n); if (BC_ERR(ptr == NULL)) bc_vm_fatalError(BC_ERR_FATAL_ALLOC_ERR); return ptr; } void* bc_vm_realloc(void *ptr, size_t n) { void* temp; BC_SIG_ASSERT_LOCKED; temp = realloc(ptr, n); if (BC_ERR(temp == NULL)) bc_vm_fatalError(BC_ERR_FATAL_ALLOC_ERR); return temp; } char* bc_vm_strdup(const char *str) { char *s; BC_SIG_ASSERT_LOCKED; s = strdup(str); if (BC_ERR(s == NULL)) bc_vm_fatalError(BC_ERR_FATAL_ALLOC_ERR); return s; } #if !BC_ENABLE_LIBRARY 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; } #endif // !BC_ENABLE_LIBRARY void bc_vm_putchar(int c, BcFlushType type) { #if BC_ENABLE_LIBRARY bc_vec_pushByte(&vm.out, (uchar) c); #else // BC_ENABLE_LIBRARY bc_file_putchar(&vm.fout, type, (uchar) c); vm.nchars = (c == '\n' ? 0 : vm.nchars + 1); #endif // BC_ENABLE_LIBRARY } char* bc_vm_getenv(const char* var) { char* ret; #ifndef _WIN32 ret = getenv(var); #else // _WIN32 _dupenv_s(&ret, NULL, var); #endif // _WIN32 return ret; } void bc_vm_getenvFree(char* var) { BC_UNUSED(var); #ifdef _WIN32 free(var); #endif // _WIN32 } #if !BC_ENABLE_LIBRARY 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_popAll(&f->labels); bc_vec_popAll(&f->strs); bc_vec_popAll(&f->consts); } #endif // BC_ENABLED #if DC_ENABLED // Note to self: you cannot delete strings and functions. Deal with it. if (BC_IS_DC) bc_vec_popAll(vm.prog.consts); #endif // DC_ENABLED bc_vec_popAll(&f->code); ip->idx = 0; } } static void bc_vm_process(const char *text) { 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_IS_DC || !BC_PARSE_NO_EXEC(&vm.prs)) bc_program_exec(&vm.prog); assert(BC_IS_DC || vm.prog.results.len == 0); if (BC_I) bc_file_flush(&vm.fout, bc_flush_save); } while (vm.prs.l.t != BC_LEX_EOF); } #if BC_ENABLED static void bc_vm_endif(void) { size_t i; bool good; if (BC_NO_ERR(!BC_PARSE_NO_EXEC(&vm.prs))) return; 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 {}"); } else bc_parse_err(&vm.prs, BC_ERR_PARSE_BLOCK); } #endif // BC_ENABLED 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); #if BC_ENABLED if (BC_IS_BC) bc_vm_endif(); #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); 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_ERR_PARSE_COMMENT); else if (BC_ERR(string)) bc_parse_err(&vm.prs, BC_ERR_PARSE_STRING); #if BC_ENABLED else if (BC_IS_BC) bc_vm_endif(); #endif // BC_ENABLED } err: BC_SIG_MAYLOCK; bc_vm_clean(); #if !BC_ENABLE_MEMCHECK assert(vm.status != BC_STATUS_ERROR_FATAL); vm.status = vm.status == BC_STATUS_QUIT || !BC_I ? vm.status : BC_STATUS_SUCCESS; #else // !BC_ENABLE_MEMCHECK vm.status = vm.status == BC_STATUS_ERROR_FATAL || vm.status == BC_STATUS_QUIT || !BC_I ? vm.status : BC_STATUS_SUCCESS; #endif // !BC_ENABLE_MEMCHECK if (!vm.status && !vm.eof) { bc_vec_empty(&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_ERR_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_ERR_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(void) { 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 + + bc_program_exec(&vm.prog); } #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); bc_vec_popAll(&buf); } while (more); BC_SIG_LOCK; bc_vec_free(&buf); #ifndef NDEBUG BC_UNSETJMP; #endif // NDEBUG BC_SIG_UNLOCK; if (!vm.no_exit_exprs && vm.exit_exprs) 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_ENABLE_AFL __AFL_INIT(); #endif // BC_ENABLE_AFL if (BC_IS_BC || !has_file) bc_vm_stdin(); // These are all protected by ifndef NDEBUG because if these are needed, bc is // going 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) { int ttyin, ttyout, ttyerr; 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; bc_vm_sigaction(); bc_vm_init(); 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_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) { char* var = bc_vm_getenv("POSIXLY_CORRECT"); vm.flags |= BC_FLAG_S * (var != NULL); bc_vm_getenvFree(var); } #endif // BC_ENABLED bc_vm_envArgs(env_args); bc_args(argc, argv, true); #if BC_ENABLED if (BC_IS_POSIX) vm.flags &= ~(BC_FLAG_G); #endif // BC_ENABLED BC_SIG_UNLOCK; bc_vm_exec(); } #endif // !BC_ENABLE_LIBRARY void bc_vm_init(void) { BC_SIG_ASSERT_LOCKED; memcpy(vm.max_num, bc_num_bigdigMax, bc_num_bigdigMax_size * sizeof(BcDig)); memcpy(vm.max2_num, bc_num_bigdigMax2, bc_num_bigdigMax2_size * sizeof(BcDig)); bc_num_setup(&vm.max, vm.max_num, BC_NUM_BIGDIG_LOG10); bc_num_setup(&vm.max2, vm.max2_num, BC_NUM_BIGDIG_LOG10); vm.max.len = bc_num_bigdigMax_size; vm.max2.len = bc_num_bigdigMax2_size; bc_vec_init(&vm.temps, sizeof(BcNum), NULL); 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_ENABLE_LIBRARY if (BC_IS_BC && !BC_IS_POSIX) #endif // !BC_ENABLE_LIBRARY { vm.maxes[BC_PROG_GLOBALS_IBASE] = BC_NUM_MAX_IBASE; } #endif // BC_ENABLED } #if BC_ENABLE_LIBRARY void bc_vm_atexit(void) { bc_vm_shutdown(); #ifndef NDEBUG bc_vec_free(&vm.jmp_bufs); #endif // NDEBUG } #else // BC_ENABLE_LIBRARY int bc_vm_atexit(int status) { int s = BC_STATUS_IS_ERROR(status) ? status : BC_STATUS_SUCCESS; bc_vm_shutdown(); #ifndef NDEBUG bc_vec_free(&vm.jmp_bufs); #endif // NDEBUG return s; } #endif // BC_ENABLE_LIBRARY diff --git a/contrib/bc/tests/other.sh b/contrib/bc/tests/other.sh index d2ef4f6d0694..e13891fcad89 100755 --- a/contrib/bc/tests/other.sh +++ b/contrib/bc/tests/other.sh @@ -1,304 +1,303 @@ #! /bin/sh # # SPDX-License-Identifier: BSD-2-Clause # # Copyright (c) 2018-2021 Gavin D. Howard and contributors. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # * Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE # POSSIBILITY OF SUCH DAMAGE. # set -e script="$0" testdir=$(dirname "$script") . "$testdir/../functions.sh" if [ "$#" -ge 1 ]; then d="$1" shift else err_exit "usage: $script dir [exec args...]" 1 fi if [ "$#" -lt 1 ]; then exe="$testdir/../bin/$d" else exe="$1" shift fi if [ "$d" = "bc" ]; then halt="quit" else halt="q" fi num=100000000000000000000000000000000000000000000000000000000000000000000000000000 numres="$num" num70="10000000000000000000000000000000000000000000000000000000000000000000\\ 0000000000" if [ "$d" = "bc" ]; then halt="halt" opt="x" lopt="extended-register" line_var="BC_LINE_LENGTH" else halt="q" opt="l" lopt="mathlib" line_var="DC_LINE_LENGTH" num="$num pR" fi set +e printf '\nRunning %s quit test...' "$d" printf '%s\n' "$halt" | "$exe" "$@" > /dev/null 2>&1 checktest_retcode "$d" "$?" "quit" if [ "$d" = bc ]; then printf '%s\n' "quit" | "$exe" "$@" > /dev/null 2>&1 checktest_retcode "$d" "$?" quit two=$("$exe" "$@" -e 1+1 -e quit) checktest_retcode "$d" "$?" quit if [ "$two" != "2" ]; then err_exit "$d failed test quit" 1 fi fi printf 'pass\n' base=$(basename "$exe") if [ "$base" != "bc" -a "$base" != "dc" ]; then exit 0 fi printf 'Running %s environment var tests...' "$d" if [ "$d" = "bc" ]; then export BC_ENV_ARGS=" '-l' '' -q" export BC_EXPR_EXIT="1" printf 's(.02893)\n' | "$exe" "$@" > /dev/null checktest_retcode "$d" "$?" "environment var" "$exe" -e 4 "$@" > /dev/null err="$?" checktest_retcode "$d" "$?" "environment var" printf 'pass\n' else export DC_ENV_ARGS="'-x'" export DC_EXPR_EXIT="1" printf '4s stuff\n' | "$exe" "$@" > /dev/null checktest_retcode "$d" "$?" "environment var" "$exe" -e 4pR "$@" > /dev/null checktest_retcode "$d" "$?" "environment var" printf 'pass\n' set +e - printf 'three\n' | head -c3 > /dev/null + printf 'three\n' | cut -c1-3 > /dev/null err=$? if [ "$err" -eq 0 ]; then printf 'Running dc Easter script...' easter_res="$testdir/dc_outputs/easter.txt" easter_out="$testdir/dc_outputs/easter_results.txt" outdir=$(dirname "$easter_out") if [ ! -d "$outdir" ]; then mkdir -p "$outdir" fi printf '4 April 2021\n' > "$easter_res" - "$testdir/dc/scripts/easter.sh" "$exe" 2021 | head -c12 > "$easter_out" - printf '\n' >> "$easter_out" + "$testdir/dc/scripts/easter.sh" "$exe" 2021 | cut -c1-12 > "$easter_out" err="$?" checktest "$d" "$err" "Easter script" "$easter_res" "$easter_out" printf 'pass\n' fi fi out1="$testdir/../.log_$d.txt" out2="$testdir/../.log_${d}_test.txt" printf 'Running %s line length tests...' "$d" printf '%s\n' "$numres" > "$out1" export "$line_var"=80 printf '%s\n' "$num" | "$exe" "$@" > "$out2" checktest "$d" "$?" "environment var" "$out1" "$out2" printf '%s\n' "$num70" > "$out1" export "$line_var"=2147483647 printf '%s\n' "$num" | "$exe" "$@" > "$out2" checktest "$d" "$?" "environment var" "$out1" "$out2" printf 'pass\n' printf 'Running %s arg tests...' "$d" f="$testdir/$d/add.txt" exprs=$(cat "$f") results=$(cat "$testdir/$d/add_results.txt") printf '%s\n%s\n%s\n%s\n' "$results" "$results" "$results" "$results" > "$out1" "$exe" "$@" -e "$exprs" -f "$f" --expression "$exprs" --file "$f" -e "$halt" > "$out2" checktest "$d" "$?" "arg" "$out1" "$out2" printf '%s\n' "$halt" | "$exe" "$@" -- "$f" "$f" "$f" "$f" > "$out2" checktest "$d" "$?" "arg" "$out1" "$out2" if [ "$d" = "bc" ]; then printf '%s\n' "$halt" | "$exe" "$@" -i > /dev/null 2>&1 fi printf '%s\n' "$halt" | "$exe" "$@" -h > /dev/null checktest_retcode "$d" "$?" "arg" printf '%s\n' "$halt" | "$exe" "$@" -P > /dev/null checktest_retcode "$d" "$?" "arg" printf '%s\n' "$halt" | "$exe" "$@" -v > /dev/null checktest_retcode "$d" "$?" "arg" printf '%s\n' "$halt" | "$exe" "$@" -V > /dev/null checktest_retcode "$d" "$?" "arg" "$exe" "$@" -f "saotehasotnehasthistohntnsahxstnhalcrgxgrlpyasxtsaosysxsatnhoy.txt" > /dev/null 2> "$out2" err="$?" checkerrtest "$d" "$err" "invalid file argument" "$out2" "$d" "$exe" "$@" "-$opt" -e "$exprs" > /dev/null 2> "$out2" err="$?" checkerrtest "$d" "$err" "invalid option argument" "$out2" "$d" "$exe" "$@" "--$lopt" -e "$exprs" > /dev/null 2> "$out2" err="$?" checkerrtest "$d" "$err" "invalid long option argument" "$out2" "$d" "$exe" "$@" "-u" -e "$exprs" > /dev/null 2> "$out2" err="$?" checkerrtest "$d" "$err" "unrecognized option argument" "$out2" "$d" "$exe" "$@" "--uniform" -e "$exprs" > /dev/null 2> "$out2" err="$?" checkerrtest "$d" "$err" "unrecognized long option argument" "$out2" "$d" "$exe" "$@" -f > /dev/null 2> "$out2" err="$?" checkerrtest "$d" "$err" "missing required argument to short option" "$out2" "$d" "$exe" "$@" --file > /dev/null 2> "$out2" err="$?" checkerrtest "$d" "$err" "missing required argument to long option" "$out2" "$d" "$exe" "$@" --version=5 > /dev/null 2> "$out2" err="$?" checkerrtest "$d" "$err" "given argument to long option with no argument" "$out2" "$d" printf 'pass\n' printf 'Running %s directory test...' "$d" "$exe" "$@" "$testdir" > /dev/null 2> "$out2" err="$?" checkerrtest "$d" "$err" "directory" "$out2" "$d" printf 'pass\n' printf 'Running %s binary file test...' "$d" bin="/bin/sh" "$exe" "$@" "$bin" > /dev/null 2> "$out2" err="$?" checkerrtest "$d" "$err" "binary file" "$out2" "$d" printf 'pass\n' printf 'Running %s binary stdin test...' "$d" cat "$bin" | "$exe" "$@" > /dev/null 2> "$out2" err="$?" checkerrtest "$d" "$err" "binary stdin" "$out2" "$d" printf 'pass\n' if [ "$d" = "bc" ]; then printf 'Running %s limits tests...' "$d" printf 'limits\n' | "$exe" "$@" > "$out2" /dev/null 2>&1 checktest_retcode "$d" "$?" "limits" if [ ! -s "$out2" ]; then err_exit "$d did not produce output on the limits test" 1 fi exec printf 'pass\n' fi